Python 3 with the SenseHat

0

Welcome and congratulations on deciding to learn Python!

The intent of this repository series is to teach Python in a way that is fun, exciting, and efficient. The SenseHat for the Raspberry Pi provides an excellent platform to teach and explore programming while being useful and entertaining from the very beginning! My hope is that coders of all ages and experience levels will be able to benefit from this material.

The content starts off at the beginning level typical of most tutorials with a Hello World application. There are multiple versions of the example application for each repository that demonstrate additional programming concepts. It is important to start at the first version, type all of the code yourself, and see the results before moving to the next version. Part of the goal is to provide some repetition of typing the language which will greatly reduce the time it takes to learn Python – or any programming language for that matter.

For more information on Python and what is has to offer see the Introduction to Python: Absolute Beginners article.

Get the most out of these tutorials!

These tutorials are intended to teach through example and repetition. You are highly encouraged to type out each and every code example yourself so that you may fully grasp the content being shown as well as better retain the information you have learned. This will greatly reduce the time it takes to learn Python – or any other programming language for that matter.

Most of these tutorials will consist of multiple versions of the same program. This is to demonstrate the basics of a concept and then to expand upon it in successive versions. Again, it is strongly recommended that you type out each version of the program from start to finish. The repetition will increase your understanding and retention of the subject matter more than you might believe.

The content in each lesson will grow in complexity. To begin with these examples will be primarily written in procedural code. An Object Oriented (OO) version of these programs will be the next learning series. At this point you do not need to understand the difference between procedural and Object Oriented programming to follow these tutorials.

Download the code examples (optional).

You can download the supporting code files from the following link:

To download click the green “clone or download” button and select Download Zip. Once downloaded you can right click and extract the zip file to access the code examples.

Write the program HelloWorld_1.py!

To follow with the tradition of the countless coders that have come before you, we will start a Hello World application.

# Application - HelloWorld_1.py

# import the sense_hat module
from sense_hat import SenseHat

# use the SenseHat() class to create an object 'sense'
sense = SenseHat()

# Use the show_message() method of the 'sense' object to display
# your message. The sense hat led screen should scroll Hello World
sense.show_message("Hello World")

# Rotate the display by 180 degrees
sense.set_rotation(180)
# display the message with new orientation
sense.show_message("Hello World")

# Rotate the display by 90 degrees
sense.set_rotation(90)
# display the message with new orientation
sense.show_message("Hello World")

# Rotate the display by 270 degrees
sense.set_rotation(270)
# display the message with new orientation
sense.show_message("Hello World")

Run The Program

If you connect to your Raspberry Pi remotely you will need to use SFTP to copy the files to your Raspbery Pi and then use SSH to run commands. Whether you connect remotely or if you have your Raspberry Pi hooked up to a monitor and keyboard, simply navigate to the directory where you saved your HelloWorld_1.py file and type the following at the prompt:

python3 HelloWorld_1.py

Now, look toward your Sense Hat and you should see the words Hello World scroll on the LED matrix four different times with a different orientation each time!

If you are new to Linux commands please read the article Linux in Minutes: Essential Commands and Tricks

Review The Code

Line 4:

from sense_hat import SenseHat

This line imports the SenseHat class from the sense_hat module. The sense_hat module contains the code that interfaces with the actual hardware device. The SenseHat class is used to create an object that allows us to interact with the hardware. This type of interface is often referred to as an API (Application Programming Interface).

Line 7:

sense = SenseHat()

Here we are creating an instance, or an object, using the SenseHat() class as our blueprint. In this example we are creating the SenseHat() object and storing it in the variable ‘sense’. This way we can access the functions from the SenseHat() class by interacting with the ‘sense’ object.

Line 11:

sense.show_message("Hello World")

This line uses the show_message() method of the sense object to scroll the words “Hello World” on the SenseHat LED Matrix – give it a try! This line also demonstrates how to access the functions and methods from the SenseHat() Class using the sense object we instantiated earlier.

Note: When you instantiate an object, that is create an object, from a class that object contains all of the variables and methods defined in the class. These methods can be accessed by other classes and applications when imported as seen in this line of code.

Lines 13-26:

# Rotate the display by 180 degrees
sense.set_rotation(180)
# display the message with new orientation
sense.show_message("Hello World")
 
# Rotate the display by 90 degrees
sense.set_rotation(90)
# display the message with new orientation
sense.show_message("Hello World")
 
# Rotate the display by 270 degrees
sense.set_rotation(270)
# display the message with new orientation
sense.show_message("Hello World")

Depending on how you have your SenseHat and Raspberry Pi positioned, your text may be scrolling upside down like on mine. You can fix this by using the set_rotation() method. These lines of code demonstrate the different orientations in which you can display content on your LED matrix.

Revision: HelloWorld_2.py

In this example we have decided on a fixed screen orientation, use a variable to store our display text, and set text and background colors.

# Application - HelloWorld_2.py

# import the sense_hat module
from sense_hat import SenseHat

# create an instance (object) from the SenseHat class
sense = SenseHat()

# Below we create a String variable called textToDisplay
# Then assign the value of Hello World to that variable
textToDisplay = "Hello World"

# Set text and background colors using tuples in RGB format
textColor = (255,255,0)
backColor = (0,0,255)

# Correct the display orientation if neccessary
sense.set_rotation(180)

# Display the text stored in the textToDisplay variable on
# sense hat LED matrix
sense.show_message(textToDisplay,
                   text_colour = textColor,
                   back_colour = backgroundColor)

# Clear the LED screen
sense.clear()

Run The Program

Type in command line or terminal:

python3 HelloWorld_2.py

Now, look toward your Sense Hat. You should see the words Hello World scroll on the LED matrix in yellow text with a blue background!

Review The Code

In the first example we used the show_message() method to scroll text on the LED matrix and adjusted the display orientation. In this revision the application will display colored text with a colored background. Note that lines that have not changed will not be commented on.

Line 11:

textToDisplay = "Hello World"

Here we create a string variable named ‘textToDisplay’ and assign it the text value of “Hello World” for later use. As you will see, this variable will be supplied to the show_message() method instead of using text surrounded by quotation marks like before.

What is a variable anyway?

An important concept to grasp in programming is the concept of a variable. In the simplest terms a variable is a place for a program to put data so that it may be recalled or used in someway at a later time. Variables are also useful for storing calculated/dynamic values. In a more literal sense a variable points to a place in memory (RAM for example) where the value is stored. You can access the stored data (space in memory) by accessing variable pointer which points to where the data is stored in memory. This concept will become more important as your programs become more complex.

A note on Data Types and Data Structures

There many different types of variables in Python. Some of the data types include:

  • Strings – These hold text values.
  • Integers – These store whole numbers like 4 or 10000
  • Floats – These store numbers with decimal places like 3.14 or 0.323433

There are also data structures, which is one of the areas where Python shines. Data structures are arguably the most useful variables in all programming. While an int , including:

  • Lists – Can store any variable type and as many as you need in what are called elements. Values can be changed after assignment.
  • Tuples – Can store any variable type and as many of them as you need in what are called elements. Values cannot be changes after assignment.
  • Dictionaries – These are similar to associative arrays in PHP or HashMaps in Java. It is a list where each element is a key => value pair. The key being the index that is looked up and the value being what is stored at that index.

Lines 14-15:

textColor = (255,255,0)
backColor = (0,0,255)

Here we create two tuple data structures of three elements and assign the values in the RGB (Red Green Blue) color format. The show_message() method can take these as arguments to set the text and background color using the RGB color pattern. Each value can be in a range of 0-255. Adjusting these values will change the color displayed on the LED matrix. In this case the text will be yellow and the background will be blue.

Line 18:

sense.set_rotation(180)

If you need to adjust the display orientation of your LED matrix do so here.

Line 22:

sense.show_message(textToDisplay,
                   text_colour = textColor,
                   back_colour = backgroundColor)

The show_message() method takes up to four arguments:

  • text_string – String containing any text
  • text_colour – List in RGB format
  • back_colour – List in RGB format
  • scroll_speed – Float representing the speed the text will scroll on the LED matrix (default: 0.1)

Example:

>>> from sense_hat import SenseHat
>>> sense = SenseHat()
>>> myString = "Print me please"
>>> redText = (255,0,0)
>>> whiteBack = (255,255,255)
>>> speed = 0.5
>>>
>>> sense.show_message(myString, text_colour = redText, back_colour = whiteBack, scroll_speed = speed)
>>> sense.clear()

The above code will scroll “Print me please” across the LED matrix with red text on a white background. Try experimenting with the color and scroll_speed values.

Line 27:

sense.clear()

This line uses the clear() method of the SenseHat() class to clear the LED matrix of any light output. After using the show_message() method with the back_colour parameter set the background will remain that color when the text has finished scrolling. You need to manually call the clear() method for the LED matrix to return to normal (all lights off).

Revision: HelloWorld_3.py

Now that we have an understanding of how to store data in variables we can get input from the user. Here we will update our script so that the program will print whatever the user wants!

# Application - HelloWorld_3.py

# import the sense_hat module
from sense_hat import SenseHat

# Create an instance (object) of the SenseHat() class called 'sense'
sense = SenseHat()

# Get text input from the user and store it in a String
# variable called textToDisplay
textToDisplay = input("Enter text: ")

# Set text and background colors using tuples in RGB format
textColor = (255,255,0)
backColor = (0,0,255)

# Correct the display orientation if neccessary
sense.set_rotation(180)

# Display the text stored in the textToDisplay variable on
# sense hat LED matrix
sense.show_message(textToDisplay,
                   text_colour = textColor,
                   back_colour = backColor)

# Clear the LED matrix
sense.clear()

Run The Program

Type in command line or terminal:

python3 HelloWorld_3.py

The program should ask you to Enter text: at which point you can enter anything you would like to scroll on the LED matrix and press the Enter key. At this point look towards your Sense Hat and see the text scroll across your LEDs!

Review The Code

Line 11

textToDisplay = input("Enter text: ")

The biggest change to this application is that instead of setting the value of the text to display in our program, we are asking the user to provide that text. We do this by using the input() method. The input method takes a string (text) argument that you can provide to tell the user what to do (i.e. Enter text). When the user types their text and presses enter the input() method returns the value that the user provided and in this case stores it in the same textToDisplay variable as before.

Conclusion

This concludes the lesson, but I hope you enjoyed reading and experimenting as much as I enjoyed writing the article. Make sure to give the Review section below a quick once over and think about what you learned in this lesson. Once you have done that you are ready to move on to your next lesson! Thank you and if you have any questions, comments, or find a typo/error please use the comment form below and let me know!

Review

Topics covered were:

  • Importing modules for use – Remember the sense_hat module.
  • Creating an instance (object) of a class – The ‘sense’ object you created.
  • Using a classes methods by accessing an instance (object) of the class – Remember the sense.show_message() method.
  • Variable data types and data structures – The textToDisplay String variable and the RGB Tuples for textColor and backColor.
Share.

About Author

James Cathcart has a Bachelors of Science for Software Application Programming and is currently pursuing his Masters of Science for Cyber-Security Engineering. He became a computer enthusiast before his teenage years and is passionate about software development and security.

Leave A Reply