Some links in this post may be affiliate links. We may get paid if you buy something or take an action after clicking one of these, but without addictional costs for you compared to direct buying.

Using a 10-segment Led Bar with Raspberry PI and Python

Raspberry PI 10 segment led bar featured image
0
(0)

10 segment LED bar are commonly used to get visual indicators, usually to measure filling status. You can use these electronic items with Raspberry PI, switching on-off each led separately

In this tutorial I’m going to show you how to wire and use a common 10 segment Led bar with Raspberry PI.

10 segment led bar image

Led bar is composed simply by 10 leds put in a single row. Each led can be switched on-off independently from each other.

While its front clearly shows available leds, its backside exposes the 20 pins used to drive leds status. Each LED has 2 pins, which are to be connected to positive and negative sources.

Unfortunately, there’s no clear way to identify what side goes to ground or Vcc (3V). From what I experienced with mine one, the side with label goes to Raspberry PI GPIOs which will drive on-off single LEDs, while the other side goes to Vcc.

Internal circuit can be schematized as in following picture:

10 segment led bar internal circuit_2

10 segment Led bar are used in many applications, most common of which is indicating the filling level of whatever you want (water tank, battery charge, signal strenght and so on).

In this tutorial I’m going to use a Raspberry PI Zero W, but this guide applies to all Raspberry PI computer boards.

What We Need

As usual, I suggest adding from now to your favourite e-commerce shopping cart all needed hardware, so that at the end you will be able to evaluate overall costs and decide if continuing with the project or removing them from the shopping cart. So, hardware will be only:

Raspberry PI Zero WH board

Check hardware prices with following links:

Amazon raspberry pi boards box
Amazon raspberry pi Zero W box
Amazon Micro SD box
Amazon Raspberry PI Power Supply box
Amazon 10 segment led bar box
Amazon Dupont Wiring box
Amazon Resistors box
Amazon Breadboard box

Wiring Diagram

Please find below my wiring schema:

Raspberry PI 10 segment led bar wiring diagram_2

Please find below some pictures from my cablig:

Raspberry PI 10 segment led bar complete
Raspberry PI 10 segment led bar details cabling
Raspberry PI 10 segment led bar running leds

Step-By-Step Procedure

Prepare Operating system

Start installing Raspberry PI OS Lite (for a headless, fast OS) or installing Raspberry PI OS Desktop (in this case using its internal terminal).

Make your OS updated:

sudo apt update -y && sudo apt upgrade -y

Install RPI.GPIO, as it enables PIN interfacing and management from Python:

sudo apt install rpi.gpio

Prepare 10 segment Led Bar Python Script

Going to programming phase, you can download directly in your Raspberry PI the python script from my download area:

wget https://peppe8o.com/download/python/10SegLedBar.py

It will include 3 main functions / working modes:

  • LedSegOut: showing a user-defined led configuration
  • LedSegCycle: turning LEDs on/off in a continuous loop
  • LedSegPerc: showing a number of LEDs on, according to a user-defined percentage (for example, to show a filling state)

In following paragraphs we’ll deep in code lines, before running it.

Start importing required libraries:

import sys
import time
import RPi.GPIO as GPIO

We’ll map connected GPIOs within a single variable, so that we’ll configure all 10 segments together with the so created array:

led_list = [14,15,18,23,24,25,8,7,1,12]

GPIOs are set to be defined with BCM (BroadCom) naming and initialized as output:

GPIO.setmode(GPIO.BCM)

for pin in led_list:
  GPIO.setup(pin,GPIO.OUT)

Finally, we arrived to functions. Our first function, named LedSegOut, requires as input a variable array, which must be an array of 10 elements (each one can be True/False or 1/0). Because of its circuit, LEDs are connected from one side to Vcc. To power on, they will need a 0 (or False) from programmable GPIOs, while they will power off when GPIO goes to 1.

The list+map+ lambda function inverts this logic, so that you can work with a more comfortable association, making it possible to mark 1 as power on and 0 to power off:

  • lambda in python is a small anonymous function. Gets a variable (“n:”) and manipulates with a simple one line function (“not(n)”). In our case, this lambda function creates the opposite of 0 or 1 values.
  • map in python applies a specified function (in its first parameter, lambda function in our script) to each single object of a given iterable (its second parameter, the array in our case)
  • list function is required to convert map result (which is a map object) to a list, so that we can directly apply in following line as output to GPIOs
def LedSegOut(array):
  array=list(map(lambda n: not(n),array))
  GPIO.output(led_list, array)

Result will be that if, for example you run LedSegOut([0,0,0,0,0,1,1,1,1,1]) you will get half of leds powered on.

The LedSegCycle function is used to power on 1 LED at time, switching from one to the other in an infinite loop (until you press CTRL+C to trigger the except exit). It doesn’t need any input. It uses the python shift function (“array[1:]+array[:1]”) to change at each while loop iteration the selected LED. It also uses LedSegOut to make LEDs powered on.

The time sleep funtion defines how much time it takes to pass from one LED to following one. The lower this delay, the faster your cycle will run:

def LedSegCycle():
  array=[0,0,0,0,0,0,0,0,0,1]
  while True:
   try:
    array = array[1:]+array[:1]
    LedSegOut(array)
    time.sleep(.05)
   except KeyboardInterrupt:
    GPIO.cleanup()
    sys.exit()

LedSegPerc function works by setting an array of thresholds instead of LED status. It requires a number between 0 and 100 (so you don’t have to specify “%” character). When this function runs, it compares the number in input (“n”) to each thresholds array item. This is made compact with a ternary operator in lambda function. “(1,0)[x>n]” is a compact and fast alternative way to write “if x>n then x=1 else x=0”. So, each threshold value is changed to 0 or 1 if input is higher or lower to that threshold value. Finally, LEDs are again switched on/off by using LedSegOut function:

def LedSegPerc(n):
  thresholds=[100,90,80,70,60,50,40,30,20,10]
  array=list(map(lambda x: (1,0)[x>n],thresholds))
  LedSegOut(array)

The main loop lets you choose which function to execute (by commenting the other 2 and leaving uncommented the function you want to use). In my script there are also examples of values you can use or edit for your very first tests:

while True:
  try:
   # LedSegOut([0,0,0,0,0,1,1,1,1,1])
   LedSegCycle()
   # LedSegPerc(81)
  except KeyboardInterrupt:
    GPIO.cleanup()
    sys.exit()

As usual, the “except KeyboardInterrupt:” will keep your terminate command (wih keyboard CTRL+C combination) and will clean GPIOs status exiting correctly from script.

Run Python Script

Once ready and once you have choose what function to test (uncommenting your test one and commenting with “#” char the other functions), you can run this script with following terminal command:

python3 10SegLedBar.py

And if your cabling is correct, you will see your 10 segment LED bar starting to run.

If nothing happens, please check your cabling. If cabling is ok, try changing verse to your bar as different producers could apply the label in different positions.

Enjoy!

How useful was this post?

Click on a star to rate it anonymously!

Average rating 0 / 5. Vote count: 0

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

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 *

I accept the Privacy Policy