Bar-graph level indicator#
A Python version of the Structured Text example in Analog Threshold Control. The thresholds are spaced evenly across the input span instead of at 2, 4, 6 and 7.9 V. This version carries none of the guarantees the PLC runtime provides.
#!/usr/bin/env python3
"""Light 0-4 outputs in proportion to a 0-10 V input."""
import signal
import time
import synergy_logic
base = synergy_logic.Base()
base.rollCall(["SLM-AI-8-V", "SLM-DCO-15P"])
level_in = base[1][1]
outputs = base[2]
INPUT_MAX = 8191 # 13-bit analog input, native resolution
SEGMENTS = 4
MARGIN = 41 # a little headroom so full scale reliably lights all four
running = True
def shutdown(signum, frame):
global running
running = False
signal.signal(signal.SIGTERM, shutdown)
signal.signal(signal.SIGINT, shutdown)
try:
while running:
counts = level_in.value
span = INPUT_MAX - MARGIN
lit = min(int(counts / span * SEGMENTS), SEGMENTS)
mask = (1 << lit) - 1 # 0 -> 0b0000, 3 -> 0b0111
outputs.do_bitmapped(mask)
print(f"{counts:5d} counts {level_in.real:5.2f} V {lit} lit")
time.sleep(0.1)
finally:
outputs.do_bitmapped(0)
(1 << lit) - 1 builds the bit pattern directly, so three lit segments give 0b0111. A single bus transaction sets all of them.