The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 8 The Raspberry Pi Camera Module 205

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


5 Figure 8-10: Create a new folder for your captured images


Having to restart your program every time you capture a picture for your animation isn’t
very good, so you need to change it to run in a loop. Unlike the previous loops you’ve created,
though, this one needs a way to close gracefully – otherwise, if you stop the program while
the camera preview is showing, you won’t be able to see the desktop any more! To do this, you
need to use two special instructions: try and except.
Start by deleting everything after camera.start_preview(), then typing:


frame = 1

This creates a new variable, frame, which your program will use to store the current frame
number. You’ll use this shortly to ensure that you’re saving a new file every time; without it,
you’ll just be saving over the top of your first image every time you press the button!
Next, set up your loop by typing:


while True:
try:

The new instruction try tells Python to run whatever code is inside – which is going to be
the code for capturing images. Type:


button.wait_for_press()
camera.capture('/home/pi/Desktop/animation/frame%03d.jpg' % frame)
frame += 1
Free download pdf