The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

184 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


With your programming running, try carefully picking the Sense HAT and Raspberry Pi up
and rotating them around – but make sure not to dislodge any of its cables! With the Pi’s
network and USB ports pointing to the floor, you’ll see the values change so the Z axis reads
0G and the X axis now reads 1G; turn it again so the HDMI and power ports are pointing to
the floor and now it’s the Y axis that reads 1G. If you do the opposite and have the HDMI port
pointing to the ceiling, you’ll see -1G on the Y axis instead.
Using the knowledge that the Earth’s gravity is roughly around 1G, and your knowledge of
the spatial axes, you can use readings from the accelerometer to figure out which way is down


  • and, likewise, which way is up. You can also use it to detect movement: try carefully shaking
    the Sense HAT and Raspberry Pi, and watch the numbers as you do: the harder you shake, the
    greater the acceleration.
    When you’re using sense.get_accelerometer_raw(), you’re telling the Sense HAT to
    turn off the other two sensors in the IMU – the gyroscopic sensor and the magnetometer –
    and return data purely from the accelerometer. Naturally, you can do the same thing with the
    other sensors too.
    Find the line acceleration = sense.get_accelerometer_raw() and change it to:


orientation = sense.get_gyroscope_raw()

Change the word acceleration on all three lines below it to orientation. Click Run,
and you’ll see the orientation of the Sense HAT for all three axes, rounded to the nearest whole
number. Unlike the last time you checked orientation, though, this time the data is coming
purely from the gyroscope without using the accelerometer or magnetometer. This can be
useful if you want to know the orientation of a moving Sense HAT on the back of a robot, for
example, without the movement confusing matters, or if you’re using the Sense HAT near a
strong magnetic field
Stop your program by clicking on the red stop button. To use the magnetometer, delete
everything from your program except for the first four lines, then type the following below the
while True line:

north = sense.get_compass()
print(north)

Run your program and you’ll see the direction of magnetic north printed repeatedly to the
Python shell area. Carefully rotate the Sense HAT and you’ll see the heading change as the
Sense HAT’s orientation relative to north shifts: you’ve built a compass! If you have a magnet


  • a fridge magnet will do – try moving it around the Sense HAT to see what that does to the
    magnetometer’s readings.

Free download pdf