The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 7 Physical Computing with the Sense HAT 187

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Try pushing the joystick in various directions to see your messages appear!

Joystick control in Python
Start a new program in Thonny and save it as Sense HAT Joystick. Begin with the usual three
lines that set up the Sense HAT and clear the LED matrix:


from sense_hat import SenseHat
sense = SenseHat()
sense.clear()

Next, set up an infinite loop:

while True:

Then tell Python to listen for inputs from the Sense HAT joystick with the following line,
which Thonny will automatically indent for you:


for event in sense.stick.get_events():

Finally, add the following line – which, again Thonny will indent for you – to actually do
something when a joystick press is detected:


print(event.direction, event.action)

Click Run, and try pushing the joystick in various directions. You’ll see the direction you’ve
chosen printed to the Python shell area: up, down, left, right, and middle for when you’ve
pushed the joystick down like a push-button switch.
You’ll also see that you’re given two events each time you push the joystick once: one
event, pressed, for when you first push a direction; the other event, released, for when the
joystick returns to centre. You can use this in your programs: think of a character in a game,
which could be made to start moving when the joystick is pressed in a direction then stop as
soon as it’s released.


FINAL CHALLENGE
Can you use the Sense HAT’s joystick to control a Scratch
sprite on the stage area? Can you make it so if the sprite
collects another sprite, representing an object, the Sense
HAT’s LEDs display a cheery message?
Free download pdf