The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

200 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Introducing picamera
The most flexible way to control the Camera Module is using Python, via the handy picamera
library. This gives you full control over the Camera Module’s preview, picture, and video capture
abilities, and allows you to integrate them into your own programs – even combining them
with programs which use the GPIO module through the GPIO Zero library!

Close the Terminal, if it’s still open, by clicking on the X at the top-right of the window, then
load Thonny from the Programming category of the raspberry menu. Save your new project
as Camera, then start importing the libraries your program needs by typing the following into
the script area:

from picamera import PiCamera
from time import sleep
camera = PiCamera()

The last line allows you to control the Camera Module using the camera function. To start,
type the following:

camera.start_preview()
sleep( 10 )
camera.stop_preview()

Click Run, and your desktop will disappear; in its place, you’ll see a full-screen preview of
whatever the camera can see (Figure 8-7). Try moving it around, or waving your hand in front
of the lens, and you’ll see the picture on screen change to match. After 10 seconds the preview
will close and your program will finish – but, unlike the preview from raspistill, no picture will be
saved afterwards.

PYTHON PROGRAMMING
The projects in this chapter assume experience with the Python
programming language, Thonny IDE, and the Raspberry Pi’s GPIO
pins. If you haven’t done so already, please work through the
projects in Chapter 5, Programming with Python, and Chapter 6,
Physical computing with Scratch and Python, first!
Free download pdf