The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

188 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


You can also use the joystick to trigger functions, rather than being limited to using a for
loop. Delete everything below sense.clear(), and type the following:

def red():
sense.clear( 255 , 0 , 0 )

def blue():
sense.clear( 0 , 0 , 255 )

def green():
sense.clear( 0 , 255 , 0 )

def yellow():
sense.clear( 255 , 255 , 0 )

These functions change the whole Sense HAT LED matrix to a single colour: red, blue, green,
or yellow – which is going to make seeing that your program works extremely easy! To actually
trigger them, you need to tell Python which function goes with which joystick input. Type the
following lines:

sense.stick.direction_up = red
sense.stick.direction_down = blue
sense.stick.direction_left = green
sense.stick.direction_right = yellow
sense.stick.direction_middle = sense.clear

Finally, the program needs an infinite loop – known as the main loop – in order to keep
running, and therefore keep watching for joystick inputs, rather than just running through the
code you’ve written once and quitting. Type the following two lines:

while True:
pass

Click Run, and try moving the joystick: you’ll see the LEDs light up in glorious colour! To
turn the LEDs off, push the joystick like a push-button: the middle direction is set to use
the sense.clear() function to turn them all off. Congratulations: you can capture input
from the joystick!
Free download pdf