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

(singke) #1
25: print('End of test')

The code sets up the GPIO 18 pin for output (line 7) and then the GPIO 24 and GPIO 25 pins for input
(for the back and front doorbells, respectively; lines 8 and 9). Then the code goes into a loop, polling
the status of the GPIO 24 and GPIO 25 pins in each iteration. If the GPIO 24 pin is LOW, the code
prints a message that the back doorbell is ringing and lights the LED. If the GPIO 25 pin is LOW, the
code prints a message that the front doorbell is ringing and lights the LED.


By-the-Way: Doorbell Emailer
You can add any code you like to the if-then code block when a doorbell ring is
detected. For example, you can use the email feature from Hour 20, “Using the
Network,” to send a customized email message to yourself each time a doorbell rings.

Polling is a simple way of detecting an input value, but there are other ways. The next section
explores them.


Input Events


Polling is a somewhat tricky way to determine when a switch has been pressed. You have to manually
read the input value in each iteration and then determine whether the value has changed.


Most of the time, you’re not as interested in the value of the input at any specific moment as you are in
when the value changes. Rising occurs when the input changes from LOW to HIGH, and falling
happens when the input changes from HIGH to LOW.


A couple different methods in the RPi.GPIO module allow you to detect rising and falling events on
an input pin.


Synchronous Events


The wait_for_edge() method stops your program until it detects either a rising or falling event
on the input signal. If you just want your program to pause and wait for the event, this is the method to
use. Listing 24.4 shows the script2404.py program, which demonstrates how to use the
wait_for_edge() method to wait for a change in the input.


LISTING 24.4 The script2404.py Program Code


Click here to view code image


1: #!/usr/bin/python3
2:
3: import RPi.GPIO as GPIO
4:
5: GPIO.setmode(GPIO.BCM)
6: GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
7: GPIO.wait_for_edge(24, GPIO.FALLING)
8: print('The button was pressed')
9: GPIO.cleanup()

This script listens for the GPIO 24 signal. The program pauses at line 7 and does nothing until it
detects a falling input value. (Remember: You’re tying the input channel HIGH, so when you press the

Free download pdf