009 - MicroPython TechNotes: 7 Segment Display

Introduction

In this article, we will look at 4-digit 7-segment display. We will learn on how to use it step by step using the MicroPython Language.

Bill Of Materials

  1. ESP32 development board.
  2. Gorilla Cell ESP32 shield.
  3. 4-pin female-female dupont jumper wires.
  4. 4-digit 7-segment display.

Hardware Instruction

  1. First, attach the ESP32 development board on top of ESP32 shield making sure that both the USB port is on the same side.
  2. Next, attach the dupont to the 7-segment display according to the color coding which is black for the ground, red for the VCC, yellow for the DIO, and white for the CLK pin.
  3. Next, attach the other side of the dupont wire to the ESP32 shield by matching the colors of the wire to the colors of the pin headers which is black to black, red to red, yellow and the following colors to the yellow pin headers. For this experiment, I choose the I2C pins on GPIO 21 for the DIO and GPIO 22 for the CLK pin.
  4. Next, attach the external power supply for the ESP32 shield by connecting a type-C USB cable power supply source and make sure that the power switch is slide to the ON state.
  5. Next, connect the ESP32 to the computer by attaching a micro USB cable. Our demo circuit is now ready.

Software Instruction

  1. For this experiment, we will be using Thonny Python IDE as a MicroPython environment.
  2. Now, let the Thonny to detect the ESP32 by clicking the Stop button. When you see triple greater than sign, it means that Thonny detected the ESP32 as Micropython device.
  3. Now, in order to use the 7-segment display we need an external driver library. Luckily, mcauser provides us a fantastic library named micropython-tm1637 which is available on his Github: https://github.com/mcauser/micropython-tm1637
  4. For the experiment, I have prepared 3 example source code below.
  5. Please feel free to modify it to learn more. Happy tinkering!

Video Demonstration

Call To Action

For any concern, write your message in the comment section.

You might also like to support my journey on Youtube by Subscribing. Click this to Subscribe to TechToTinker.

Thank you and have a good days ahead.

See you,

– George Bantique | tech.to.tinker@gmail.com

Source Code

1. Example # 1, exploring basic functionality of the 7-segment:

 1import tm1637
 2from machine import Pin
 3tm = tm1637.TM1637(dio=Pin(21), clk=Pin(22))
 4
 5# The following line of code should
 6# be tested using the REPL
 7# This will demonstrate basic function of 7 segment
 8
 9# 1. TO WRITE A STRING:
10# tm.show('abcd')
11
12# 2. TO WRITE A NUMBER:
13# tm.numbers(1234)
14#    Now to use the decimal point in between
15# tm.numbers(12,34) 
16#    or use
17# tm.numbers(12,34,True)
18#    Now to turn off the decimal point
19# tm.numbers(12,34,False)
20#    So basically the 3rd value determines if
21#    decimal point will be active or not.
22#    So to display time: "12:59"
23# tm.numbers(12, 59)
24#    or 
25# tm.numbers(12, 59, True)
26
27# 3. TO SCROLL THE DISPLAY:
28# tm.scroll('Hello World') # 4 fps
29#    Now to control the speed of scroll
30#    The second value, is the amount of delay in ms
31# tm.scroll('Hello World', 1000) # 1 fps
32# tm.scroll(list(tm1637._SEGMENTS))
33
34# 4. TO SHOW TEMPERATURE:
35#    Works for range -9 to +99
36# tm.temperature(-9)  # -9*C
37# tm.temperature(5)   #  5*C
38# tm.temperature(99)  # 99*C
39#    While values outside the range, will give
40# tm.temperature(-10) # LO*C
41# tm.temperature(100) # HI*C
42
43#5. TO CONTROL THE BRIGHTNESS
44# tm.brightness(0)
45# tm.brightness(7)

2. Example # 2, counter that counts up from 0 to 19 and counts down from 20 to 1 infinitely:

 1# Author: George Bantique | tech.to.tinker@gmail.com | TechToTinker.blogspot.com
 2# Date:   February 2, 2020
 3# Note:   Please feel free to modify this according to your needs.
 4
 5import tm1637
 6from machine import Pin
 7from time import sleep_ms
 8
 9tm = tm1637.TM1637(dio=Pin(21), clk=Pin(22))
10
11# This will count up from 0 to 19 and
12# count down from 20 down to 1.
13while True:
14    # Count up counter:
15    for i in range(20):
16        tm.number(i)
17        sleep_ms(500)
18        
19    # Count down counter:
20    for i in range(20, 0, -1):
21        tm.number(i)
22        sleep_ms(500)

3. Example # 3, clock by taking advantage of the builtin RTC module in ESP32:

 1# Author: George Bantique | tech.to.tinker@gmail.com | TechToTinker.blogspot.com
 2# Date:   February 2, 2020
 3# Note:   Please feel free to modify this according to your needs.
 4
 5import tm1637
 6from machine import Pin
 7from time import sleep_ms
 8from machine import RTC
 9
10rtc = RTC()
11tm = tm1637.TM1637(dio=Pin(21), clk=Pin(22))
12
13rtc.datetime((2021, 2, 2, 1, 12, 01, 0, 0))
14# rtc.datetime((YYYY, MM, DD, WD, HH, MM, SS, MS))
15# WD 1 = Monday
16# WD 7 = Sunday
17
18isPoint = True
19
20while True:
21    t = rtc.datetime()
22    tm.numbers(t[4], t[5], isPoint)
23    sleep_ms(200)
24    isPoint = not isPoint

4. Library for 7 Segment Display:

  1"""
  2MicroPython TM1637 quad 7-segment LED display driver
  3https://github.com/mcauser/micropython-tm1637
  4MIT License
  5Copyright (c) 2016 Mike Causer
  6Permission is hereby granted, free of charge, to any person obtaining a copy
  7of this software and associated documentation files (the "Software"), to deal
  8in the Software without restriction, including without limitation the rights
  9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 10copies of the Software, and to permit persons to whom the Software is
 11furnished to do so, subject to the following conditions:
 12The above copyright notice and this permission notice shall be included in all
 13copies or substantial portions of the Software.
 14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 15IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 16FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 17AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 18LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 19OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 20SOFTWARE.
 21"""
 22
 23from micropython import const
 24from machine import Pin
 25from time import sleep_us, sleep_ms
 26
 27TM1637_CMD1 = const(64)  # 0x40 data command
 28TM1637_CMD2 = const(192) # 0xC0 address command
 29TM1637_CMD3 = const(128) # 0x80 display control command
 30TM1637_DSP_ON = const(8) # 0x08 display on
 31TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
 32TM1637_MSB = const(128)  # msb is the decimal point or the colon depending on your display
 33
 34# 0-9, a-z, blank, dash, star
 35_SEGMENTS = bytearray(b'x3Fx06x5Bx4Fx66x6Dx7Dx07x7Fx6Fx77x7Cx39x5Ex79x71x3Dx76x06x1Ex76x38x55x54x3Fx73x67x50x6Dx78x3Ex1Cx2Ax76x6Ex5Bx00x40x63')
 36
 37class TM1637(object):
 38    """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
 39    def __init__(self, clk, dio, brightness=7):
 40        self.clk = clk
 41        self.dio = dio
 42
 43        if not 0 <= brightness <= 7:
 44            raise ValueError("Brightness out of range")
 45        self._brightness = brightness
 46
 47        self.clk.init(Pin.OUT, value=0)
 48        self.dio.init(Pin.OUT, value=0)
 49        sleep_us(TM1637_DELAY)
 50
 51        self._write_data_cmd()
 52        self._write_dsp_ctrl()
 53
 54    def _start(self):
 55        self.dio(0)
 56        sleep_us(TM1637_DELAY)
 57        self.clk(0)
 58        sleep_us(TM1637_DELAY)
 59
 60    def _stop(self):
 61        self.dio(0)
 62        sleep_us(TM1637_DELAY)
 63        self.clk(1)
 64        sleep_us(TM1637_DELAY)
 65        self.dio(1)
 66
 67    def _write_data_cmd(self):
 68        # automatic address increment, normal mode
 69        self._start()
 70        self._write_byte(TM1637_CMD1)
 71        self._stop()
 72
 73    def _write_dsp_ctrl(self):
 74        # display on, set brightness
 75        self._start()
 76        self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
 77        self._stop()
 78
 79    def _write_byte(self, b):
 80        for i in range(8):
 81            self.dio((b >> i) & 1)
 82            sleep_us(TM1637_DELAY)
 83            self.clk(1)
 84            sleep_us(TM1637_DELAY)
 85            self.clk(0)
 86            sleep_us(TM1637_DELAY)
 87        self.clk(0)
 88        sleep_us(TM1637_DELAY)
 89        self.clk(1)
 90        sleep_us(TM1637_DELAY)
 91        self.clk(0)
 92        sleep_us(TM1637_DELAY)
 93
 94    def brightness(self, val=None):
 95        """Set the display brightness 0-7."""
 96        # brightness 0 = 1/16th pulse width
 97        # brightness 7 = 14/16th pulse width
 98        if val is None:
 99            return self._brightness
100        if not 0 <= val <= 7:
101            raise ValueError("Brightness out of range")
102
103        self._brightness = val
104        self._write_data_cmd()
105        self._write_dsp_ctrl()
106
107    def write(self, segments, pos=0):
108        """Display up to 6 segments moving right from a given position.
109        The MSB in the 2nd segment controls the colon between the 2nd
110        and 3rd segments."""
111        if not 0 <= pos <= 5:
112            raise ValueError("Position out of range")
113        self._write_data_cmd()
114        self._start()
115
116        self._write_byte(TM1637_CMD2 | pos)
117        for seg in segments:
118            self._write_byte(seg)
119        self._stop()
120        self._write_dsp_ctrl()
121
122    def encode_digit(self, digit):
123        """Convert a character 0-9, a-f to a segment."""
124        return _SEGMENTS[digit & 0x0f]
125
126    def encode_string(self, string):
127        """Convert an up to 4 character length string containing 0-9, a-z,
128        space, dash, star to an array of segments, matching the length of the
129        source string."""
130        segments = bytearray(len(string))
131        for i in range(len(string)):
132            segments[i] = self.encode_char(string[i])
133        return segments
134
135    def encode_char(self, char):
136        """Convert a character 0-9, a-z, space, dash or star to a segment."""
137        o = ord(char)
138        if o == 32:
139            return _SEGMENTS[36] # space
140        if o == 42:
141            return _SEGMENTS[38] # star/degrees
142        if o == 45:
143            return _SEGMENTS[37] # dash
144        if o >= 65 and o <= 90:
145            return _SEGMENTS[o-55] # uppercase A-Z
146        if o >= 97 and o <= 122:
147            return _SEGMENTS[o-87] # lowercase a-z
148        if o >= 48 and o <= 57:
149            return _SEGMENTS[o-48] # 0-9
150        raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
151
152    def hex(self, val):
153        """Display a hex value 0x0000 through 0xffff, right aligned."""
154        string = '{:04x}'.format(val & 0xffff)
155        self.write(self.encode_string(string))
156
157    def number(self, num):
158        """Display a numeric value -999 through 9999, right aligned."""
159        # limit to range -999 to 9999
160        num = max(-999, min(num, 9999))
161        string = '{0: >4d}'.format(num)
162        self.write(self.encode_string(string))
163
164    def numbers(self, num1, num2, colon=True):
165        """Display two numeric values -9 through 99, with leading zeros
166        and separated by a colon."""
167        num1 = max(-9, min(num1, 99))
168        num2 = max(-9, min(num2, 99))
169        segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
170        if colon:
171            segments[1] |= 0x80 # colon on
172        self.write(segments)
173
174    def temperature(self, num):
175        if num < -9:
176            self.show('lo') # low
177        elif num > 99:
178            self.show('hi') # high
179        else:
180            string = '{0: >2d}'.format(num)
181            self.write(self.encode_string(string))
182        self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
183
184    def show(self, string, colon=False):
185        segments = self.encode_string(string)
186        if len(segments) > 1 and colon:
187            segments[1] |= 128
188        self.write(segments[:4])
189
190    def scroll(self, string, delay=250):
191        segments = string if isinstance(string, list) else self.encode_string(string)
192        data = [0] * 8
193        data[4:0] = list(segments)
194        for i in range(len(segments) + 5):
195            self.write(data[0+i:4+i])
196            sleep_ms(delay)
197
198
199class TM1637Decimal(TM1637):
200    """Library for quad 7-segment LED modules based on the TM1637 LED driver.
201    This class is meant to be used with decimal display modules (modules
202    that have a decimal point after each 7-segment LED).
203    """
204
205    def encode_string(self, string):
206        """Convert a string to LED segments.
207        Convert an up to 4 character length string containing 0-9, a-z,
208        space, dash, star and '.' to an array of segments, matching the length of
209        the source string."""
210        segments = bytearray(len(string.replace('.','')))
211        j = 0
212        for i in range(len(string)):
213            if string[i] == '.' and j > 0:
214                segments[j-1] |= TM1637_MSB
215                continue
216            segments[j] = self.encode_char(string[i])
217            j += 1
218        return segments

References And Credits

  1. mcauser micropython-tm1637 library: https://github.com/mcauser/micropython-tm1637/

  2. Purchase Gorilla Cell ESP32 kit from: gorillacell.kr



Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.