whereas sensor
turn to 1 when there is no object in front of the sensor, you can make a loop that waits for the object to pass; something like:
from functools import partial
sensor_ir = partial(gpio.input, 36)
while True:
if sensor_ir() == 0:
objetos += 1
# Enquanto o objeto não sair da frente...
while sensor_ir() != 1:
pass
So get into the if
when it detects an object and only comes out of the second while
when the object goes through. I also used the function functools.partial
to make the code more readable, making it sensor_ir()
is equivalent to gpio.input(36)
.
But I must warn you that this solution does not provide Bouncing in the Sigal. That is, if your sensor varies between 0 and 1 by short intervals (noise) due to its internal features the system may still mismeasure.
If you don’t want to hold your application in an infinite loop, you can create a flag indicating whether or not the current object has been accounted for.
contabilizado = False
while True:
if sensor_ir() == 0 and not contabilizado:
objetos += 1
contabilizado = True
elif sensor_ir() == 1:
contabilizado = False
Thus, it will only be added when the sensor is 0 and contabilizado
is false; immediately contabilizado
becomes true, so in the next iterations where sensor is still 0 the object will not be counted again. Only from the moment sensor becomes 1, which is when the object leaves the sensor, contabilizado
returns to false allowing to count the next object.
About the Bouncing, It is natural for a sensor to have noises between transitions. For example, the graph below represents the signal behavior when pressing a button. It should be 0 when the button is free and 1 when pressed; however, when pressed, there will be a transition noise in which the signal will vary between 0 and 1 in a "uncontrolled" way. For a faithful acquisition of the signal it is necessary to treat this behavior in a way to ensure that the reading is not made in this period.
Anderson thank you so much for the lesson given in this post, I did here as you taught me and is working perfectly. I thank you so much. Congratulations!!!!
– Henrique Komoto