Previously we covered GPIO with motors and servos, what about buttons?
The classic example is to light up an LED on a button press, but we can do better than that!
I am using the TFT Hat from Adafruit, but the same principle applies whichever buttons you use, just match the correct pin number.
import os
import picamera
import gpiozero
from gpiozero import Button
import time
import datetime
from time import sleep
camera = picamera.PiCamera()
button = Button(23)
def snap():
print("Snap!")
datestamp = datetime.datetime.now().strftime('./camera/%Y-%m-%d-%H-%M.jpg')
camera.capture(datestamp)
os.system("sudo fbi -T 2 -d /dev/fb1 -noverbose -a {}".format(datestamp))
while True:
if button.is_pressed:
snap()
# do nothing
sleep(0.1)
We start with the usual import section. We need to execute commands, do some time stuff, and take pictures. For the button we will use GPIOZero.
The official camera has a nice PiCamera module, and GPIOZero has a friendly Button object that makes this project crazy easy.
Our Snap function works out the text version of the date and time, starting with year, and on down to minute. I just slapped my forehead when I spotted that I should have not been so silly, overwriting my images , but for demo purposes, you get the idea.
If you were going to use this for real you would need to add seconds or more granularity :)
Once we take the picture using camera.capture we then execute FBI on the command line. No, we are not calling the cops, but using the frame buffer tool to output the just taken picture to the small TFT screen.
We have a small infinite loop to check the button is_pressed property, but we could have easily used the more event-based approach of supplying our function as the method for the when_pressed feature instead.
Our tiny delay is just to stop the Pi from trying to do too much too fast, have a play with how fast you can run it before problems arise!