The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 6 Physical computing with Scratch and Python 129

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


LED control in Scratch
Load Scratch 2 from the Raspbian menu, click on More Blocks in the blocks palette, then the
‘Add an Extension’ button. Now click on ‘Pi GPIO’ (Figure 6-3), then OK. This loads the blocks
you need to control the Pi’s GPIO header from Scratch 2. You’ll see the new blocks appear in
the blocks palette; when you need them, they’re available in the More Blocks category.


5 Figure 6-3: Add the Pi.GPIO extension to Scratch 2


Start by dragging a when clicked Events block onto the scripts area, then place a
set gpio to output high block underneath it. You’ll need to choose the number of the pin
you’re using: click on the small arrow to open the drop-down selection and click on ‘25’ to tell
Scratch you’re controlling the GPIO 25 pin.


when clicked


setgpio^25 to output high


Click the green flag to run your program. You’ll see your LED light up: you’ve programmed
your first physical computing project! Click the red octagon to stop your program: notice how
the LED stays lit? That’s because your program only ever told the Pi to turn the LED on – that’s
what the ‘output high’ part of your set gpio 25 to output high block means. To turn it off
again, click on the down arrow at the end of the block and choose ‘output low’ from the list.


when clicked


setgpio^25 to output low


Click the green flag again, and this time your program turns the LED off. To make things
more interesting, add a forever control block and a couple of wait 1 secs blocks to create
a program to flash the LED on and off every second.

Free download pdf