Chapter 7 Physical Computing with the Sense HAT 183
THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE
while True:
acceleration = sense.get_accelerometer_raw()
x = acceleration['x']
y = acceleration['y']
z = acceleration['z']
You now have variables containing the current accelerometer readings for the three spatial
axes: X, or left and right; Y, or forwards and backwards; and Z, or up or down. The numbers
from the accelerometer sensor can be difficult to read, so type the following to make them
easier to understand by rounding them to the nearest whole number:
x = round(x, 0 )
y = round(y, 0 )
z = round(z, 0 )
Finally, print the three values by typing the following line:
print("x={ 0 }, y={ 1 }, z={ 2 }".format(x, y, z))
Click Run, and you’ll see values from the accelerometer printed to the Python shell area
(Figure 7-28). Unlike your previous program, these will print continuously; to stop them
printing, click the red stop button to stop the program.
5 Figure 7-28: Accelerometer readings rounded to the nearest whole number
You may have noticed that the accelerometer is telling you that one of the axes – the Z axis,
if your Pi is flat on the table – has an acceleration value of 1.0 gravities (1G), yet the Sense
HAT isn’t moving. That’s because it’s detecting the Earth’s gravitational pull – the force that is
pulling the Sense HAT down towards the centre of the Earth, and the reason why if you knock
something off your desk it’ll fall to the floor.