to a LOW signal). There are two ways to implement a pull-up or pull-down:
Hardware—Connect the GPIO 18 pin to either the 3.3V voltage pin for a pull-up (using a
10,000- to 50,000-ohm resistor to limit the current) or to a GND pin (using a 1,000-ohm
resistor) for a pull-down.
Software—The RPi.GPIO library provides the option of defining a pull-up or pull-down for
the pin internally, using an option in the setup() method:
Click here to view code image
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Adding this line forces the GPIO 18 pin to always be in a HIGH status if the pin is not connected
directly to ground.
If you’re using the Pi Cobbler, you can use either the hardware or software pull-up or pull-down
method. However, the Gertboard doesn’t provide for the hardware feature, so in this hour, you’ll
stick with using a software pull-up on your input lines, and then you’ll use the push-button switch to
connect the pin to the GND signal to trigger the LOW value.
Now you’re ready to move on to some coding!
Input Polling
The most basic method for watching for a switch is called polling. The Python code checks the
current value of a GPIO input pin at a regular interval. The GPIO input changing value means the
switch was pressed. Listing 24.3 shows the script2403.py program, which demonstrates this
feature.
LISTING 24.3 The script2403.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.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
9: GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
10: GPIO.output(18, GPIO.LOW)
11:
12: try:
13: while True:
14: if (GPIO.input(24) == GPIO.LOW):
15: print('Back door')
16: GPIO.output(18, GPIO.HIGH)
17: elif (GPIO.input(25) == GPIO.LOW):
18: print('Front door')
19: GPIO.output(18, GPIO.HIGH)
20: else:
21: GPIO.output(18, GPIO.LOW)
22: time.sleep(0.1)
23: except KeyboardInterrupt:
24: GPIO.cleanup()