August 17, 2016

Display two digits numbers on the Raspberry PI Sense HAT

Here is a small Python script to display two digits numbers on the Raspberry PI Sense HAT led matrix.

The script is very useful if you want to display humidity and temperature without scrolling.


The show_number function accepts the number to be displayed and RGB values of the color to be used.
Here is the full script.

from sense_hat import SenseHat
import time

OFFSET_LEFT = 1
OFFSET_TOP = 2

NUMS =[1,1,1,1,0,1,1,0,1,1,0,1,1,1,1,  # 0
       0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,  # 1
       1,1,1,0,0,1,0,1,0,1,0,0,1,1,1,  # 2
       1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,  # 3
       1,0,0,1,0,1,1,1,1,0,0,1,0,0,1,  # 4
       1,1,1,1,0,0,1,1,1,0,0,1,1,1,1,  # 5
       1,1,1,1,0,0,1,1,1,1,0,1,1,1,1,  # 6
       1,1,1,0,0,1,0,1,0,1,0,0,1,0,0,  # 7
       1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,  # 8
       1,1,1,1,0,1,1,1,1,0,0,1,0,0,1]  # 9

# Displays a single digit (0-9)
def show_digit(val, xd, yd, r, g, b):
  offset = val * 15
  for p in range(offset, offset + 15):
    xt = p % 3
    yt = (p-offset) // 3
    sense.set_pixel(xt+xd, yt+yd, r*NUMS[p], g*NUMS[p], b*NUMS[p])

# Displays a two-digits positive number (0-99)
def show_number(val, r, g, b):
  abs_val = abs(val)
  tens = abs_val // 10
  units = abs_val % 10
  if (abs_val > 9): show_digit(tens, OFFSET_LEFT, OFFSET_TOP, r, g, b)
  show_digit(units, OFFSET_LEFT+4, OFFSET_TOP, r, g, b)


################################################################################
# MAIN

sense = SenseHat()
sense.clear()

for i in range(0, 100):
  show_number(i, 200, 0, 60)
  time.sleep(0.2)

sense.clear()

3 comments:

  1. This is amazing! Thank you so much for creating this. I was spinning my wheels for a little while trying to come up with my own solution but this looks great!

    Thanks again!
    Dwayne

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. New to the rpi and python. I'm at a loss as to how this is writing the numbers via the loop in show_digit and how NUMS is used. Any chance of some pseudocode to help in understanding?

    ReplyDelete