The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

160 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Greetings from Python
Load Thonny, in either simple or standard modes, by clicking on the Raspbian menu icon,
choosing Programming, and clicking on either Thonny link. If you’re using the Sense HAT
emulator and it gets covered by the Thonny window, click and hold the mouse button on either
window’s title bar – at the top, in blue – and drag it to move it around the desktop until you can
see both windows.

To use the Sense HAT, or Sense HAT emulator, in a Python program, you need to import the
Sense HAT library. Type the following into the script area, remembering to use sense_emu (in
place of sense_hat) if you’re using the Sense HAT emulator:

from sense_hat import SenseHat
sense = SenseHat()

The Sense HAT library has a simple function for taking a message, formatting it so that it
can be shown on the LED display, and scrolling it smoothly. Type the following:

sense.show_message("Hello, World!")

Save your program as Hello Sense HAT, then click the Run button. You’ll see your message
scroll slowly across the Sense HAT’s LED matrix, lighting up the LED pixels to form each letter
in turn (Figure 7-7). Congratulations: your program’s a success!

PYTHON LINE CHANGE
Python code written for a physical Sense HAT runs on the Sense
HAT emulator, and vice-versa, with only one change. If you’re using
the Sense HAT emulator with Python you’ll need to change the line
from sense_hat import SenseHat in all the programs from
this chapter to from sense_emu import SenseHat instead.
If you want to then run them on a physical Sense HAT again, just
change the line back!
Free download pdf