I am trying to write a simple Python program that will hook to a little microcontroller alarm project I'm working on. The microcontroller is connected to eight switches. It outputs a binary value based on the switch state over a serial port.
I'm trying to write the python program decoder and am using hard coded values to check my logic. Here's what I've written:
switches='11011101'
currentstate = {}
prevstate = {}
def initswitches():
for x in range (0,8):
name = "switch" + str(x)
currentstate[name] = switches[x]
prevstate[name] = switches[x]
def setswitches():
for x in range (0,8):
name = "switch" + str(x)
currentstate[name] = switches[x]
def checkswitches():
for switch in range (0,8):
name = "switch" + str(switch)
if ( currentstate[name] != prevstate[name]):
print name + " value changed to " + str(switch)
initswitches()
for y in range (0,2):
setswitches()
print "Loop" + str(y)
print "Switches:"
print switches
print "Current state:"
print currentstate
print "Previous state:"
print prevstate
checkswitches()
prevstate = currentstate
switches='01001001'
print
print
and here's the output:
Loop0
Switches:
11011101
Current state:
{'switch3': '1', 'switch2': '0', 'switch1': '1', 'switch0': '1', 'switch7': '1', 'switch6': '0', 'switch5': '1', 'switch4': '1'}
Previous state:
{'switch3': '1', 'switch2': '0', 'switch1': '1', 'switch0': '1', 'switch7': '1', 'switch6': '0', 'switch5': '1', 'switch4': '1'}
Loop1
Switches:
01001001
Current state:
{'switch3': '0', 'switch2': '0', 'switch1': '1', 'switch0': '0', 'switch7': '1', 'switch6': '0', 'switch5': '0', 'switch4': '1'}
Previous state:
{'switch3': '0', 'switch2': '0', 'switch1': '1', 'switch0': '0', 'switch7': '1', 'switch6': '0', 'switch5': '0', 'switch4': '1'}
As you can see, I am able to set the binary values to each switch correctly to current state, but for some reason previous state is always matching current state. Loop0 shows expected behavior, but Loop1 should have previous state matching what was output for Loop0 . I cannot find where I am setting previous state to match currentstate before the checkswitches function is called. Can someone tell me where I am going wrong?