Reputation: 57
I am python programming a RPi. I am using 'wait for edge' to count a Hall Sensor output for the RPM of a flywheel with two magnets attached. The rpm routine is as follows:
# Imports
import RPi.GPIO as GPIO
import time
# Set GPIO Mode as BCM
GPIO.setmode(GPIO.BCM)
GPIO.setup(17 , GPIO.IN) # Hall sensor attached to GPIO 17
def rpm():
pulse = 0 # Reset pulse counter
endTime = time.time()+1 # Calculate end time in 1 second
while time.time() < endTime: # Loop while time is less than end time
GPIO.wait_for_edge(17, GPIO.FALLING) # Wait for a falling edge
pulse += 1 # Increment pulse
pulse = str((pulse*60)/2) # Calculate for pulse per minute
return pulse # Return the 'RPM'
if __name__ == "__main__":
print("You ran this module directly (and did not import it.")
input("\n\nPress the enter key to exit.")
The code works fine when the wheel is spinning and edge is triggered. The issue is when the wheel stops and the edge is not triggered, the while loop never checks the exit clause and the programme stalls. How can I guarantee to break out by the endTime even when pulse = 0? Thanks.
Upvotes: 1
Views: 1506
Reputation: 2182
use the timeout
parameter so it will only wait for so long. For example, this code would only wait for 1 second before breaking out of the loop.
GPIO.wait_for_edge(17, GPIO.FALLING, timeout = 1000)
You could also use (endTime-time.time())*1000
as your timeout to make it wait until endTime to break out
Upvotes: 3