Sense Hat on Raspberry Pi – The Ultimate Tutorial (Part 2)

tutorial on how to install sense hat on raspberry pi

Let’s continue our discovery of the Sense Hat on Raspberry Pi!
In the previous part, we have seen what is the Sense Hat and how to install it
In this part, we’ll look particularly at how to interact with it in Python

Introduction

The Sense Hat is an expansion board created by the Raspberry Pi Foundation
It provides many sensors like temperature, humidity and pressure
There is also a LED display matrix and a joystick on it
In this post, we’ll see how to use everything in Python scripts

If you didn’t read yet the previous part, I highly recommend starting with that
Here is the link to the beginning of the tutorial: Sense Hat Tutorial Part 1

Also, if you’re new to Python, it’s probably a good idea to start with a Python tutorial. You can read this article for example for a quick overview.
Even if the scripts I’m going to show you here are not complicated, I will not spend time explaining the Python part

That being said, let’s get down to practice!

Collect data from the Sense Hat

The Sense Hat Library

We have briefly seen this in the previous part example, but I will give you a few more details here
To use the functions I will introduce in your script, you need to firstly include the Python library for the Sense HAT at the beginning of your script

A library is a source code that provides everything you need for a specific usage
This avoids having to code all by yourself

Here are the two lines to add at the beginning of each Python code:
from sense_hat import SenseHat
sense = SenseHat()

The first line is to import the library, the second to initialize the “sense” variable that you will use in the entire script

Temperature, humidity and pressure

Theory

Once the library imported, you have access to all the basic functions to collect data from the Sense hat
Here are the first three functions you can use:

  • sense.get_temperature()
  • sense.get_humidity()
  • sense.get_pressure()

The names are explicit.
They don’t need any parameter, and they return directly the value (as a float)

Example

from sense_hat import SenseHat
sense = SenseHat()

#temperature
temp = sense.get_temperature()
print("Temperature: %s C" % temp)

#humidity
humidity = sense.get_humidity()
print("Humidity: %s %%" % humidity)

#pressure
pressure = sense.get_pressure()
print("Pressure: %s Millibars" % pressure)

Output:

Temperature: 28.5211639404 C
Humidity: 43.0516967773 %
Pressure: 998.412353516 Millibars

Temperature is in degrees Celsius, humidity in percentage and pressure in Millibars
We get them with many decimals values, so you can round them if you want: round(temperature)

Orientation and compass

Theory

The next functions I want to show you are orientation and compass
Thanks to the magnetometer, we can almost use it as a compass

As for the other functions, names are explicit:

  • sense.get_orientation()
    You can also use get_orientation_radians() or get_orientation_degrees() to specify the unit you want
  • sense.get_compass()
    Get the direction of North in degrees (compared to the USB ports direction)
    360/0° is North, 90 is East, 270 is West and 180 is South
  • sense.set_imu_config(compass_enabled, gyro_enabled, acc_enabled)
    To select which sensor you want to enable

Calibration

Before using these functions, you need to calibrate the Sense Hat
The procedure is available on this GitHub page, but here is the summary:

  • Install the requirements:
    sudo apt install octave -y
  • Copy the files to a temporary folder:
    cp /usr/share/librtimulib-utils/RTEllipsoidFit ./ -a
  • Run the calibration tool:
    cd RTEllipsoidFit
    RTIMULibCal

A configuration menu like this shows up:

Options are:   
   m - calibrate magnetometer with min/max   
   e - calibrate magnetometer with ellipsoid (do min/max first)   
   a - calibrate accelerometers   
   x - exit Enter option: 

Press “m” and follow the instructions (you have to move your Raspberry Pi in all directions on 6 axes)
Press “s” and then “x” once done

Example

Once your Sense Hat calibrated, you can use the previous functions like this:

from sense_hat import SenseHat

#orientation
sense = SenseHat()
orientation = sense.get_orientation()
print("p: {pitch}, r: {roll}, y: {yaw}".format(**orientation))

#compass
sense.set_imu_config(True, False, False)  # enable only the compass
north = sense.get_compass()
print("North: %s" % north)

Output:

p: 1.34247368137, r: 0.0139023806468, y: 138.151914078
North: 138.151914078

Gyroscope and accelerometer

Theory

You can also use the gyroscope sensor built in the Sense Hat
As for the previous ones, the function name is explicit:

  • get_gyroscope()
    Return the pitch, roll and yaw values in float
  • get_accelerometer()

Don’t forget to use set_imu_config() to enable only the one you want

Example

The usage is almost the same as previously seen:

from sense_hat import SenseHat

sense = SenseHat()

#gyroscope
sense.set_imu_config(False, True, False)  # gyroscope only
gyro_only = sense.get_gyroscope()
print("p: {pitch}, r: {roll}, y: {yaw}".format(**gyro_only))

#accelerometer
sense.set_imu_config(False, False, True)  # accelerometer only
accel_only = sense.get_accelerometer()
print("p: {pitch}, r: {roll}, y: {yaw}".format(**accel_only))

Joystick events

Theory

Another thing I want to show is the joystick
You can use it as an input interface in your scripts
As often with user interface development, the Python library allows you to catch events

There is two main functions that I will show you here:

  • wait_for_event()
    As the name suggests, the script is paused until something happened
    The function returned three values: timestamp, action and direction
  • get_events()
    Rather than waiting for new events, you can directly check if something has happened recently
    This function gives you the history of all events that have happened since the last call

Example

from sense_hat import SenseHat
from time import sleep

sense = SenseHat()
event = sense.stick.wait_for_event()
print("The joystick was {} {}".format(event.action, event.direction))
sleep(0.1)
event = sense.stick.wait_for_event()
print("The joystick was {} {}".format(event.action, event.direction))

With the wait_for_event() function, your script is paused until you touch the joystick
Then it displays the action and direction (that you can use in a more complex program, for a menu or a game for example)

Display data on the Sense Hat screen

Ok, the last thing I want to show you is how to display things on the Sense Hat LED Matrix
There are many functions to display colors, text, images or to configure things like orientation and light level
But for this tutorial I will keep things simple: text and colors pixels

Display texts

Theory

You have already seen how to do this in the first part of this tutorial, but I will explain here how it works
The API offers two ways to display text on the screen: letters or text

Here are the two functions you can use:

  • show_message(text, speed, text_color, back_color)
    Text is a sting, the speed is a float (0.1 by default) and colors are a list of three values (R, G, B)
    You’ll understand in the examples below
  • show_letter(letter, text_color, back_color)
    Almost the same thing. Letter is a string of one character, and colors are (R, G, B) lists

For both functions, default colors are a white text on a black background
If this is ok for you, colors parameters are not mandatory.

Example

from sense_hat import SenseHat
from time import sleep

sense = SenseHat()

#set your colors here
background = (198, 30, 74)
color = (255, 255, 255)

#display a message on the screen
sense.show_message("RaspberryTips <3", 0.05, color, background)
sleep(1)

#display only one letter
sense.show_letter("@")
sleep(2)

#turn off the screen
sense.clear()

In this example, I show you the two functions in action, and added a bonus one (the clear function)
Two clarifications now:

  • The speed in the show_message() function represents the pause time between each letter. So, the bigger this value is, the slower is the scroll speed
  • If you want, you can use the show_message() without all parameters, here are a few examples that works:
    sense.show_message("Text")
    sense.show_message("Text", 0.1)
    sense.show_message("Text", text_colour=[255, 0, 0]) sense.show_message("Text", back_colour=[255, 0, 0])

Set pixels colors

Theory

You have seen the rainbow colors on boot, so you already know that it’s possible to set each pixel to a specific color
In this part, we’ll play with two functions:

  • set_pixels(pixel_list)
    The parameter is a list of 64 colors to define all pixels colors at once
  • set_pixel(x, y, color)
    or set_pixel(x, y, r, g, b)
    You have the choice to set the color as a list or as three different parameters, don’t ask me why only in this function πŸ™‚
    x is the left/right column, y is the top/bottom line (values from 0 to 7)

Example

from sense_hat import SenseHat
from time import sleep
from random import randint

sense = SenseHat()

R = (198, 30, 74)       #raspberrytips red
W = (255, 255, 255)     #white

#set all pixels at once
pixels = [
     W, W, W, W, W, W, W, W,
     W, R, R, W, R, R, W, W,
     R, R, R, R, R, R, R, W,
     R, R, R, R, R, R, R, W,
     R, R, R, R, R, R, R, W,
     W, R, R, R, R, R, W, W,
     W, W, R, R, R, W, W, W,
     W, W, W, R, W, W, W, W
]

sense.set_pixels(pixels)
sleep(5)
sense.clear()

#set one pixel at at time
while True:
        X = randint(0, 7)
        Y = randint(0, 7)
        sense.set_pixel(X, Y, R)
        sleep(0.2)

Yes, I love you πŸ™‚
Use CTRL+C to stop the script once your screen is full of red pixels

If you don’t know, randint() return a random value between the two parameter
And while True is an infinite loop to display all the pixels
But you can use static values and/or repeat the set_pixel() function if you prefer

API Reference

We have already seen a good list of functions today, but if you want to go further, you can check the API reference here
On this page, you can find all the functions available in the Sense Hat library, to do anything with it

Conclusion

That’s it for this second part, we have seen many things in Python today, and I hope you liked it
Take time to play with it, change my code or try other things
Learning new things is important, but having fun is better πŸ™‚

I will probably add one or two other parts to this tutorial in the following weeks, and add the link here
Meanwhile, feel free to leave a comment below if you are interested in something specific
I was thinking of using the Sense Hat with Scratch and probably build a bigger project in Python as a conclusion, but I’m open to any suggestion

And please share your links to photos and videos in the comments below, I know you are an artist πŸ™‚
You can also use the contact page if you prefer

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 3

No votes so far! Be the first to rate this post.

As you found this post useful...

Spread the word!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *