182 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE
Inertial sensing in Python
Start a new program in Thonny and save it as Sense HAT Movement. Fill in the usual starting
lines, remembering to use sense_emu if you’re using the Sense HAT emulator:
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
To use information from the IMU to work out the current orientation of the Sense HAT on its
three axes, type the following:
orientation = sense.get_orientation()
pitch = orientation["pitch"]
roll = orientation["roll"]
yaw = orientation["yaw"]
print("pitch {0} roll {1} yaw {2} ".format(pitch, roll, yaw))
Click Run and you’ll see readings for the Sense HAT’s orientation split across the three axes
(Figure 7-27). Try rotating the Sense HAT and clicking Run again; you should see the numbers
change to reflect its new orientation.
5 Figure 7-27: Showing the Sense HAT’s pitch, roll, and yaw values
The IMU can do more than measure orientation, though: it can also detect movement. To
get accurate readings for movement, the IMU needs to be read frequently in a loop: unlike
for orientation, taking a single reading won’t get you any useful information when it comes to
detecting movement. Delete everything after sense.clear() then type the following code: