If condition script writing as null?

Im attempting to write a very simple script that will run on a 1sec interval as the communications heartbeat. The script simply writes to a tag a 0 or a 1 depending on what its current state is at time of running (1 second interval). However every time it checks it seems to write the variable as null? cant really figure out why. This is the code im using:

HeartBeatRead = system.tag.read("[default]IgnitionHeartbeat/HeartBeat")
HeartBeatWrite = system.tag.write("[default]IgnitionHeartbeat/HeartBeat")
HeartBeatWrite = 1
if HeartBeatRead == 0:
HeartBeatWrite = 1
HeartBeatWrite = 0

Perhaps there is a better way to accomplish this? thanks.


First off, please use the pre-formatted text option, as it saves indentation, which matters in Jython.

You can do this using this button when you add a post:


So, you didn’t mention which version, as you are using read and write I am assuming 7.9, if you are on 8.0 or 8.1 you should as good practice use readBlocking etc, however the simple read will still work.

I think your code should look more like this:

HeartBeatRead = system.tag.read("[default]IgnitionHeartbeat/HeartBeat")

if HeartBeatRead.value == 0:
   system.tag.write("[default]IgnitionHeartbeat/HeartBeat", 1)
   system.tag.write("[default]IgnitionHeartbeat/HeartBeat", 0)
1 Like

Thanks for the help, that did the trick. Still working on my jython syntax. Ill keep the code formatting in mind for the future.

Thanks again!

1 Like

You can avoid some duplication with a relatively simple rewrite:

path = "[default]IgnitionHeartbeat/HeartBeat"
HeartBeatRead = system.tag.read(path)
system.tag.write(path, not HeartBeatRead.value)

not is a Python operator that returns the inverse of the current value as a boolean - so 1 (True) becomes False (0), and vice-versa.