I am trying to attach a quadrature rotary encoder via my Arduino to my computer. Since there need to be other systems attached tot he same Arduino which need to be controlled I have a StandardFirmata sketch on it. My idea is that I could read the digital pins for a change (True/False) while I turn the encoder. I then wanted to compare the current state with the previous state to check for a change of state (somewhat like the
attachInterrupt function in Arduino):
import pyfirmata pin3_now=0 pin3_before=0 counter=0 time=core.Clock() board=pyfirmata.Arduino('COM4') #Use iterator thread to avoid buffer overflow it = pyfirmata.util.Iterator(board) it.start() pin3 = board.get_pin('d:3:i') while time.getTime() < 10: pin3_now = pin3.read() pin3_before = pin3_now if pin3_now != pin3_before: counter= counter+1 print counter board.exit()
However, the if statement is never executed. If I print
pin3_now I can change the values changing form False to True and vice versa. I do not understand why the if statement is not executed although a change of state is clearly visible.
I tried putting the values in a list and compare elements of the list. This works, however the detection in change of state is then limited how fast the values are inserted into the list, making a calculation of velocity impossible.
import pyfirmata y_list= pin3_now=0 pin3_before=0 counter=0 #pin4_now=0 #pin4_before=0 time=core.Clock() board=pyfirmata.Arduino('COM4') #Use iterator thread to avoid buffer overflow it = pyfirmata.util.Iterator(board) it.start() pin3 = board.get_pin('d:3:i') #pin4 = board.get_pin('d:4:i') while time.getTime() < 10: pin3_now = pin3.read() pin3_before = pin3_now y_list.append(pin3_now) if len(y_list) > 20: y_list.pop() # Get the velocity if y_list != y_list[-1]: counter= counter+1 # if pin3_now != pin3_before: # counter = counter+1 # else: # pass print counter board.exit()
Could someone explain this phenomenon to me and how I can correct it (or has someone else a better solution to detect the change in state) ?
Thank you in advance