Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

button, the signal goes from HIGH to LOW.) When the event occurs, the program is released and
continues processing.


The downside to this is that you can wait for only one event at a time. If someone rings the front
doorbell while you’re waiting for the back doorbell to ring, you’ll miss the event. The next method
solves this problem.


Asynchronous Events


You don’t have to stop the entire program and wait for an event to occur. Instead, you can use
asynchronous events. With asynchronous events, you can define multiple events for the program to
listen for. Each event points to a method inside your code that runs when the event is triggered.


You use the add_event_detect() method to define the event and the method to trigger, like this:


Click here to view code image


GPIO.add_event_detect(channel, event, callback=method)

You can register as many events as you need in your program to monitor as many channels as you
need. Listing 24.5 shows the script2405.py program, which demonstrates how to use this
feature.


LISTING 24.5 The script2405.py Program Code


Click here to view code image


1: #!/usr/bin/python3
2:
3: import RPi.GPIO as GPIO
4: import time
5:
6: GPIO.setmode(GPIO.BCM)
7: GPIO.setup(18, GPIO.OUT)
8: GPIO.output(18, GPIO.LOW)
9: GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
10: GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
11:
12: def backdoor(channel):
13: GPIO.output(18, GPIO.HIGH)
14: print('Back door')
15: time.sleep(0.1)
16: GPIO.output(18, GPIO.LOW)
17:
18: def frontdoor(channel):
19: GPIO.output(18, GPIO.HIGH)
20: print('Front door')
21: time.sleep(0.1)
22: GPIO.output(18, GPIO.LOW)
23:
24: GPIO.add_event_detect(24, GPIO.FALLING, callback=backdoor)
25: GPIO.add_event_detect(25, GPIO.FALLING, callback=frontdoor)
26:
27: try:
28: while True:
29: pass
30: except KeyboardInterrupt:
31: GPIO.cleanup()
Free download pdf