I wrote a simple code to test interrupts in Python:
import RPi.GPIO as GPIO
brakepin = 32
brake_value = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(brakepin, GPIO.IN, pull_up_down = GPIO.PUD_UP) #Brake
def brake_isr(channel):
global brake_value
print ("Entered interrupt")
brake_value = GPIO.input(brakepin)
GPIO.add_event_detect(brakepin, GPIO.RISING, callback = brake_isr)
while True:
print("Brake_value: %d" % (brake_value))
time.sleep(0.025)
I am using interrupts to capture when the brakes are pressed on a scooter and when they are not. Ofcourse, 1 indicates the brakes are pressed and 0 indicates they are not. I have three questions:
In the line:
GPIO.setup(brakepin, GPIO.IN, pull_up_down = GPIO.PUD_UP)what should I put the value of pull_up_down? UP or DOWN. Actually both are working the same way, there is no difference. The brake's default value is 0 (when not pressed) because it is connected to ground.In the line:
GPIO.add_event_detect(brakepin, GPIO.RISING, callback = brake_isr)should I put GPIO.RISING or FALLING? Since I want to detect brake events (i.e. when a brake is being pressed and when it is not) I think I should use RISING only.One very weird thing is happening: When I press the brake I get output as:
Brake_value: 1 -> This is as expected. Great!
When I let go off the brake it still remains 1, i.e.:
Brake_value: 1 -> This should be 0
Why is the brake value not coming back to 0 when I let go of the brake
Edit: I modified my interrupt code block to this:
def brake_isr(channel):
print ("Entered interrupt")
global brake_value
while GPIO.input(brakepin) == 1:
brake_value = GPIO.input(brakepin)
brake_value = 0
Well this solved the problem that I was facing with Question 3. However another weird thing is happening with the output (which was happening even before):
Brake_value: 0
.
.
.
When I press the brakes:
Entered interrupt
Entered interrupt
Entered interrupt
Brake_value: 1
Brake_value: 1
.
.
.
When I let go of the brakes:
Entered interrupt
Entered interrupt
Brake_value: 0
Brake_value: 0
.
.
.
Why is the code entering the interrupt block several times when I press the brakes (as can be seen with the multiple print statement) and why is it entering the interrupt when I let go off the brakes? This is happening for time.sleep(1) or time.sleep(0.025), deosnt matter what the delay is.