The best way is to use an interrupt.
In the previous code, the button detecting is always going on. But in some larger projects, this is inefficient and may greatly affect the performance. The best status should be: the program keeps running, but only when the button is operated, the shell informs the user; the program continues its process if the button part is ended. In that case, the main process would not be hindered by printing useless information.
Save the code button.py as interrupt_button.py.
The code will be like this:
import RPi.GPIO as GPIO
import time
button_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(button_pin, GPIO.IN, GPIO.PUD_UP)
def my_callback(channel):
button_status = GPIO.input(button_pin) # Read button input and give the value to status
if button_status == 1: # Check status value
print "Button Released!"
else:
print "Button Pressed!"
# Define a edge detection
GPIO.add_event_detect(button_pin, GPIO.BOTH, my_callback, bouncetime=20)
while True:
print "I'm so boring, nothing left to do."
time.sleep(3)
We move the contents in the while loop previously to a my_callback function, and add a print “I’m so boring, nothing left to do.”every 3 seconds. And add GPIO.ass_event_detect, which defines the detected pin as button_pin, the event type as GPIO.BOTH, the callback function after signals detected as my_callback, and the bouncetime=200.
There are three types of event: FALL from high to low (GPIO.FALLING), RISE from low to high (GPIO.RISING) and BOTH FALLING and RISING (GPIO.BOTH). Here we need to detect BOTH, so we use GPIO.BOTH. In my_callback, its parameter channel is imported when add_event_detect calls this function. The parameter value is the pin number at which an event is detected. You don’t need to understand too much, but just write this parameter.
boucetime is used to filter out some useless signals caused by button jittering. The button connects/breaks the circuit by the metal strip inside. When the button is pressed or released, the metal will jitter. The quick-response Raspberry Pi will detect the signal of jittering and wrongly takes it for several quick button pressing. Adding the bouncetime means that if the operation of the button is less than 20ms per time, it’s null. So the Raspberry Pi will ignore the continuous signals in 20ms and not regard it as button being pressed or released. You can adjust this parameter, and check what happens then.
Save and run the code. If there is no change of button operation, like it’s being pressed or not pressed at all, the main program while will have nothing to run, and it will print “I’m so boring…” as set. Once you press down or release the button, the program will detect the operation and print the information accordingly on the screen immediately. It’s interesting, isn’t it?
Till now, we have learnt the code for simple control and also a little complex control of digital signals. Then, where are we off to?