While loop not working immediately while reading from a Sensor without printing the read from the sensor?

382 Views Asked by At

I am attempting to read multiple Reflective IR Sensors continuously until each one is blocked. I am using an Arduino running Standard Firmata and Pythons Pyfirmata library.

Every time I try a standard read without printing the result in a while loop I am getting a 15 to 30 second delay (I cannot figure out why):

Example1 - works but with random unexplained delay:

Sensor1 = board.get_pin('a,0,i') #analogue, pin 0, input mode

while Sensor1.read() != 0: #Sensor defaults to 0.6 V but when blocked 0.0v

   Sensor1.read()

Example2 - works but I now have a bunch of sensor read outputs:

Sensor1 = board.get_pin('a,0,i') #analogue, pin 0, input mode

while Sensor1.read() != 0: #Sensor defaults to 0.6 V but when blocked 0.0v

   Sensor1.read()

   print(Sensor1.read()) # this prints a bunch of read outputs

For some reason when I add the print(Sensor1.read()) I will get an immediate response when the sensor is blocked. But if I remove this portion of code to eliminate the garbage output I get an unexplained time delay in between when the sensor is blocked and when it is recognized by the code and moves on. What I would like to do is constantly read the sensor without printing that read and get an immediate response of breaking the while loop once the sensor is blocked and produces the 0.0v. I believe that I also have the option of suppressing the print outputs for these while loops but I want to know if there is an alternative? Thank you so much for reviewing this question and thanks a million for any help!

2

There are 2 best solutions below

3
On

The read() might not always be exact 0. Maybe use a threshold value, for example:

while Sensor1.read() > 10:

Another solution would be to use interrupts and set flags, so you don't have to do the polling (and could put the device to sleep).

0
On

I know i'ts an old topic, but I ran into this problem with pyfirmata a few days ago, and today I solved it simply by printing a new line with the end= parameter, it creates a new line, but the following prints stays on the same line.

Sensor1 = board.get_pin('a,0,i')

while Sensor1.read() != 0:
   Sensor1.read()
   print('', end='')