008 - MicroPython TechNotes: 16x2 LCD

Introduction

In this article, we will look at LCD. We will also learn on how to use it using the MicroPython language. LCD stands for Liquid Crystal Display. What I have is 16×2 LCD with Gorilla Cell LCD module which uses i2c protocol to simplify wiring connection.

Pinout

  1. GND – for the ground pins.
  2. VCC – for the supply voltage.
  3. SDA – for the i2c serial data pin.
  4. SCL – for the i2c serial clock pin.

Bill Of Materials

  1. ESP32 development board.
  2. Gorilla Cell ESP32 shield.
  3. 4-pin female to female dupont jumper wires.
  4. and of course the Gorilla Cell LCD module itself.

Hardware Instruction

  1. First attach the dupont jumper wires to the LCD module by following the color coding which is black for the ground, red for the VCC, yellow for the SDA, and white for the SCL pin.
  2. Next, attach the other end of the dupont jumper wires to the Gorilla Cell ESP32 shield by matching the colors of the dupont wires to the colors of the pin headers on ESP32 shield which is black to black, red to red, yellow and the following colors to yellow pin headers. For this experiment, I choose GPIO 21 for the SDA and GPIO 22 for the SCL pins.
  3. Next, power the ESP32 shield by attaching a USB type-C cable. Make sure that the power switch is slide to ON state.
  4. Next, connect the ESP32 to the computer by attaching a micro-USB cable. Our demo is now ready.

Software Instruction

For the software part, we will be needing additional driver library. Luckily, there is available library from Github which is written by Dave Hylands https://github.com/dhylands/python_lcd/

  1. First, open your Thonny Python IDE.
  2. Next, let Thonny to detect and connect to ESP32 by clicking the Stop button.
  3. Next, copy the lcd_api.py below (SOURCE CODE section), click the New button, and paste it in Thonny.
  4. Next, save it to MicroPython root directory by clicking the File menu, select Save As, and click the MicroPython Device.
  5. Next, enter a file name as lcd_api.py.
  6. Repeat steps #3 to steps #5 for i2c_lcd.py.

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:

 1from time import sleep_ms, ticks_ms 
 2from machine import I2C, Pin 
 3from i2c_lcd import I2cLcd 
 4
 5DEFAULT_I2C_ADDR = 0x20
 6
 7i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) 
 8lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)
 9
10# The following line of code should be tested
11# using the REPL:
12
13# 1. To print a string to the LCD:
14#    lcd.putstr('Hello world')
15# 2. To clear the display:
16#	 lcd.clear()
17# 3. To control the cursor position:
18# 	 lcd.move_to(2, 1)
19# 4. To show the cursor:
20#  	 lcd.show_cursor()
21# 5. To hide the cursor:
22#	 lcd.hide_cursor()
23# 6. To set the cursor to blink:
24#	 lcd.blink_cursor_on()
25# 7. To stop the cursor on blinking:
26#	 lcd.blink_cursor_off()
27# 8. To hide the currently displayed character:
28#	 lcd.display_off()
29# 9. To show the currently hidden character:
30#	 lcd.display_on()
31# 10. To turn off the backlight:
32#	 lcd.backlight_off()
33# 11. To turn ON the backlight:
34#	 lcd.backlight_on()
35# 12. To print a single character:
36#	 lcd.putchar('x')
37# 13. To print a custom character:
38#	 happy_face = bytearray([0x00, 0x0A, 0x00, 0x04, 0x00, 0x11, 0x0E, 0x00])
39#	 lcd.custom_char(0, happy_face)
40#	 lcd.putchar(chr(0))

2. Example # 2:

 1from time import sleep_ms, ticks_ms 
 2from machine import I2C, Pin 
 3from i2c_lcd import I2cLcd 
 4
 5DEFAULT_I2C_ADDR = 0x20
 6
 7i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) 
 8lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)
 9
10lcd.clear()
11lcd.putstr('Example # 2')
12sleep_ms(1000)
13count = 0
14
15while True:
16    print('Counter: {}'.format(count))
17    lcd.clear() # Clears the LCD,
18                # Sets the cursor position to 0,0 
19    lcd.putstr('Counter: {}' .format(count))
20    count = count + 1
21    sleep_ms(1000)

3. lcd_api.py driver library:

  1"""Provides an API for talking to HD44780 compatible character LCDs.""" 
  2import time 
  3class LcdApi: 
  4    """Implements the API for talking with HD44780 compatible character LCDs. 
  5    This class only knows what commands to send to the LCD, and not how to get 
  6    them to the LCD. 
  7    It is expected that a derived class will implement the hal_xxx functions. 
  8    """ 
  9    # The following constant names were lifted from the avrlib lcd.h 
 10    # header file, however, I changed the definitions from bit numbers 
 11    # to bit masks. 
 12    # 
 13    # HD44780 LCD controller command set 
 14    LCD_CLR = 0x01              # DB0: clear display 
 15    LCD_HOME = 0x02             # DB1: return to home position 
 16    LCD_ENTRY_MODE = 0x04       # DB2: set entry mode 
 17    LCD_ENTRY_INC = 0x02        # --DB1: increment 
 18    LCD_ENTRY_SHIFT = 0x01      # --DB0: shift 
 19    LCD_ON_CTRL = 0x08          # DB3: turn lcd/cursor on 
 20    LCD_ON_DISPLAY = 0x04       # --DB2: turn display on 
 21    LCD_ON_CURSOR = 0x02        # --DB1: turn cursor on 
 22    LCD_ON_BLINK = 0x01         # --DB0: blinking cursor 
 23    LCD_MOVE = 0x10             # DB4: move cursor/display 
 24    LCD_MOVE_DISP = 0x08        # --DB3: move display (0-> move cursor) 
 25    LCD_MOVE_RIGHT = 0x04       # --DB2: move right (0-> left) 
 26    LCD_FUNCTION = 0x20         # DB5: function set 
 27    LCD_FUNCTION_8BIT = 0x10    # --DB4: set 8BIT mode (0->4BIT mode) 
 28    LCD_FUNCTION_2LINES = 0x08  # --DB3: two lines (0->one line) 
 29    LCD_FUNCTION_10DOTS = 0x04  # --DB2: 5x10 font (0->5x7 font) 
 30    LCD_FUNCTION_RESET = 0x30   # See "Initializing by Instruction" section 
 31    LCD_CGRAM = 0x40            # DB6: set CG RAM address 
 32    LCD_DDRAM = 0x80            # DB7: set DD RAM address 
 33    LCD_RS_CMD = 0 
 34    LCD_RS_DATA = 1 
 35    LCD_RW_WRITE = 0 
 36    LCD_RW_READ = 1 
 37    def __init__(self, num_lines, num_columns): 
 38        self.num_lines = num_lines 
 39        if self.num_lines > 4: 
 40            self.num_lines = 4 
 41        self.num_columns = num_columns 
 42        if self.num_columns > 40: 
 43            self.num_columns = 40 
 44        self.cursor_x = 0 
 45        self.cursor_y = 0 
 46        self.implied_newline = False 
 47        self.backlight = True 
 48        self.display_off() 
 49        self.backlight_on() 
 50        self.clear() 
 51        self.hal_write_command(self.LCD_ENTRY_MODE | self.LCD_ENTRY_INC) 
 52        self.hide_cursor() 
 53        self.display_on() 
 54    def clear(self): 
 55        """Clears the LCD display and moves the cursor to the top left 
 56        corner. 
 57        """ 
 58        self.hal_write_command(self.LCD_CLR) 
 59        self.hal_write_command(self.LCD_HOME) 
 60        self.cursor_x = 0 
 61        self.cursor_y = 0 
 62    def show_cursor(self): 
 63        """Causes the cursor to be made visible.""" 
 64        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | 
 65                               self.LCD_ON_CURSOR) 
 66    def hide_cursor(self): 
 67        """Causes the cursor to be hidden.""" 
 68        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY) 
 69    def blink_cursor_on(self): 
 70        """Turns on the cursor, and makes it blink.""" 
 71        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | 
 72                               self.LCD_ON_CURSOR | self.LCD_ON_BLINK) 
 73    def blink_cursor_off(self): 
 74        """Turns on the cursor, and makes it no blink (i.e. be solid).""" 
 75        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | 
 76                               self.LCD_ON_CURSOR) 
 77    def display_on(self): 
 78        """Turns on (i.e. unblanks) the LCD.""" 
 79        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY) 
 80    def display_off(self): 
 81        """Turns off (i.e. blanks) the LCD.""" 
 82        self.hal_write_command(self.LCD_ON_CTRL) 
 83    def backlight_on(self): 
 84        """Turns the backlight on. 
 85        This isn't really an LCD command, but some modules have backlight 
 86        controls, so this allows the hal to pass through the command. 
 87        """ 
 88        self.backlight = True 
 89        self.hal_backlight_on() 
 90    def backlight_off(self): 
 91        """Turns the backlight off. 
 92        This isn't really an LCD command, but some modules have backlight 
 93        controls, so this allows the hal to pass through the command. 
 94        """ 
 95        self.backlight = False 
 96        self.hal_backlight_off() 
 97    def move_to(self, cursor_x, cursor_y): 
 98        """Moves the cursor position to the indicated position. The cursor 
 99        position is zero based (i.e. cursor_x == 0 indicates first column). 
100        """ 
101        self.cursor_x = cursor_x 
102        self.cursor_y = cursor_y 
103        addr = cursor_x & 0x3f 
104        if cursor_y & 1: 
105            addr += 0x40    # Lines 1 & 3 add 0x40 
106        if cursor_y & 2:    # Lines 2 & 3 add number of columns 
107            addr += self.num_columns 
108        self.hal_write_command(self.LCD_DDRAM | addr) 
109    def putchar(self, char): 
110        """Writes the indicated character to the LCD at the current cursor 
111        position, and advances the cursor by one position. 
112        """ 
113        if char == 'n': 
114            if self.implied_newline: 
115                # self.implied_newline means we advanced due to a wraparound, 
116                # so if we get a newline right after that we ignore it. 
117                pass 
118            else: 
119                self.cursor_x = self.num_columns 
120        else: 
121            self.hal_write_data(ord(char)) 
122            self.cursor_x += 1 
123        if self.cursor_x >= self.num_columns: 
124            self.cursor_x = 0 
125            self.cursor_y += 1 
126            self.implied_newline = (char != 'n') 
127        if self.cursor_y >= self.num_lines: 
128            self.cursor_y = 0 
129        self.move_to(self.cursor_x, self.cursor_y) 
130    def putstr(self, string): 
131        """Write the indicated string to the LCD at the current cursor 
132        position and advances the cursor position appropriately. 
133        """ 
134        for char in string: 
135            self.putchar(char) 
136    def custom_char(self, location, charmap): 
137        """Write a character to one of the 8 CGRAM locations, available 
138        as chr(0) through chr(7). 
139        """ 
140        location &= 0x7 
141        self.hal_write_command(self.LCD_CGRAM | (location << 3)) 
142        self.hal_sleep_us(40) 
143        for i in range(8): 
144            self.hal_write_data(charmap[i]) 
145            self.hal_sleep_us(40) 
146        self.move_to(self.cursor_x, self.cursor_y)
147        
148    def hal_backlight_on(self): 
149        """Allows the hal layer to turn the backlight on. 
150        If desired, a derived HAL class will implement this function. 
151        """ 
152        pass 
153    def hal_backlight_off(self): 
154        """Allows the hal layer to turn the backlight off. 
155        If desired, a derived HAL class will implement this function. 
156        """ 
157        pass 
158    def hal_write_command(self, cmd): 
159        """Write a command to the LCD. 
160        It is expected that a derived HAL class will implement this 
161        function. 
162        """ 
163        raise NotImplementedError 
164    def hal_write_data(self, data): 
165        """Write data to the LCD. 
166        It is expected that a derived HAL class will implement this 
167        function. 
168        """ 
169        raise NotImplementedError 
170    def hal_sleep_us(self, usecs): 
171        """Sleep for some time (given in microseconds).""" 
172        time.sleep_us(usecs)

4. i2c_lcd.py driver library:

 1"""Implements a HD44780 character LCD connected via PCF8574 on I2C. 
 2   This was tested with: https://www.wemos.cc/product/d1-mini.html""" 
 3from lcd_api import LcdApi 
 4from machine import I2C 
 5from time import sleep_ms 
 6# The PCF8574 has a jumper selectable address: 0x20 - 0x27 
 7#DEFAULT_I2C_ADDR = 0x20 
 8# Defines shifts or masks for the various LCD line attached to the PCF8574 
 9MASK_RS = 0x01 
10MASK_RW = 0x02 
11MASK_E = 0x04 
12SHIFT_BACKLIGHT = 3 
13SHIFT_DATA = 4 
14class I2cLcd(LcdApi): 
15    """Implements a HD44780 character LCD connected via PCF8574 on I2C.""" 
16    def __init__(self, i2c, i2c_addr, num_lines, num_columns): 
17        self.i2c = i2c 
18        self.i2c_addr = i2c_addr 
19        self.i2c.writeto(self.i2c_addr, bytearray([0])) 
20        sleep_ms(20)   # Allow LCD time to powerup 
21        # Send reset 3 times 
22        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
23        sleep_ms(5)    # need to delay at least 4.1 msec 
24        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
25        sleep_ms(1) 
26        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
27        sleep_ms(1) 
28        # Put LCD into 4 bit mode 
29        self.hal_write_init_nibble(self.LCD_FUNCTION) 
30        sleep_ms(1) 
31        LcdApi.__init__(self, num_lines, num_columns) 
32        cmd = self.LCD_FUNCTION 
33        if num_lines > 1: 
34            cmd |= self.LCD_FUNCTION_2LINES 
35        self.hal_write_command(cmd) 
36    def hal_write_init_nibble(self, nibble): 
37        """Writes an initialization nibble to the LCD. 
38        This particular function is only used during initialization. 
39        """ 
40        byte = ((nibble >> 4) & 0x0f) << SHIFT_DATA 
41        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
42        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
43    def hal_backlight_on(self): 
44        """Allows the hal layer to turn the backlight on.""" 
45        self.i2c.writeto(self.i2c_addr, bytearray([1 << SHIFT_BACKLIGHT])) 
46    def hal_backlight_off(self): 
47        """Allows the hal layer to turn the backlight off.""" 
48        self.i2c.writeto(self.i2c_addr, bytearray([0])) 
49    def hal_write_command(self, cmd): 
50        """Writes a command to the LCD. 
51        Data is latched on the falling edge of E. 
52        """ 
53        byte = ((self.backlight << SHIFT_BACKLIGHT) | (((cmd >> 4) & 0x0f) << SHIFT_DATA)) 
54        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
55        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
56        byte = ((self.backlight << SHIFT_BACKLIGHT) | ((cmd & 0x0f) << SHIFT_DATA)) 
57        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
58        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
59        if cmd <= 3: 
60            # The home and clear commands require a worst case delay of 4.1 msec 
61            sleep_ms(5) 
62    def hal_write_data(self, data): 
63        """Write data to the LCD.""" 
64        byte = (MASK_RS | (self.backlight << SHIFT_BACKLIGHT) | (((data >> 4) & 0x0f) << SHIFT_DATA)) 
65        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
66        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
67        byte = (MASK_RS | (self.backlight << SHIFT_BACKLIGHT) | ((data & 0x0f) << SHIFT_DATA)) 
68        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
69        self.i2c.writeto(self.i2c_addr, bytearray([byte]))

References And Credits

  1. Dave Hylands python lcd library: https://github.com/dhylands/python_lcd/

  2. Gorilla Cell ESP32 development kit: gorillacell.kr



Posts in this series



No comments yet!

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