The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

192 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Look carefully at the line which prints the result to the LEDs: the %s is known as a
placeholder, and gets replaced with the content of the variable temp. Using this, you can
format the output nicely with a label, ‘Temperature:’, and a unit of measurement, ‘degrees
Celsius,’ which makes your program a lot more friendly.
Next, define a function for the humidity sensor:

def humidity():
humidity = sense.get_humidity()
humidity = round(humidity, 1 )
sense.show_message("Humidity: %s percent" % humidity)

Then the pressure sensor:

def pressure():
pressure = sense.get_pressure()
pressure = round(pressure, 1 )
sense.show_message("Pressure: %s millibars" % pressure)

And finally the compass reading from the magnetometer:

def compass():
for i in range( 0 , 10 ):
north = sense.get_compass()
north = round(north, 1 )
sense.show_message("North: %s degrees" % north)

The short for loop in this function takes ten readings from the magnetometer to ensure
that it has enough data to give you an accurate result. If you find that the reported value keeps
shifting, try extending it to 20, 30, or even 100 loops to improve the accuracy further.
Your program now has five functions, each of which takes a reading from one of the Sense
HAT’s sensors and scrolls them across the LEDs. It needs a way to choose which sensor you
want to use, though, and the joystick is perfect for that.
Type the following:

sense.stick.direction_up = orientation
sense.stick.direction_right = temperature
sense.stick.direction_down = compass
sense.stick.direction_left = humidity
sense.stick.direction_middle = pressure
Free download pdf