The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 7 Physical Computing with the Sense HAT 191

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Python project: Sense HAT Tricorder
Now you know your way around the Sense HAT, it’s time to put everything you’ve learned
together to build a tricorder – a device immediately familiar to fans of a certain science-fiction
franchise as being able to report on various sensors built into it.
Start a new project in Thonny and save it as Tricorder, then start with the traditional lines
you need to make a Sense HAT program:


from sense_hat import SenseHat
sense = SenseHat()
sense.clear()

Next, you need to start defining functions for each of the Sense HAT’s various sensors. Start
with the inertial measurement unit by typing:


def orientation():
orientation = sense.get_orientation()
pitch = orientation["pitch"]
roll = orientation["roll"]
yaw = orientation["yaw"]

Because you’re going to be scrolling the results from the sensor across the LEDs, it makes
sense to round them so that you’re not waiting for dozens of decimal places. Rather than
whole numbers, though, round them to one decimal place by typing the following:


pitch = round(pitch, 1 )
roll = round(roll, 1 )
yaw = round(yaw, 1 )

Finally, you need to tell Python to scroll the results to the LEDs, so the tricorder works as a
hand-held device without needing to be connected to a monitor or TV:


sense.show_message("Pitch {0} , Roll {1} , Yaw {2} ".
format(pitch, roll, yaw))


Now that you have a full function for reading and displaying the orientation from the IMU, you
need to create similar functions for each of the other sensors. Start with the temperature sensor:


def temperature():
temp = sense.get_temperature()
temp = round(temp, 1 )
sense.show_message("Temperature: %s degrees Celsius" % temp)
Free download pdf