]> vault307.fbx.one Git - RPI-PICO-I2C-LCD.git/blob - pico_i2c_lcd.py
Update README.md
[RPI-PICO-I2C-LCD.git] / pico_i2c_lcd.py
1 import utime
2
3 from lcd_api import LcdApi
4 from machine import I2C
5
6 # PCF8574 pin definitions
7 MASK_RS = 0x01 # P0
8 MASK_RW = 0x02 # P1
9 MASK_E = 0x04 # P2
10
11 SHIFT_BACKLIGHT = 3 # P3
12 SHIFT_DATA = 4 # P4-P7
13
14 class I2cLcd(LcdApi):
15
16 #Implements a HD44780 character LCD connected via PCF8574 on I2C
17
18 def __init__(self, i2c, i2c_addr, num_lines, num_columns):
19 self.i2c = i2c
20 self.i2c_addr = i2c_addr
21 self.i2c.writeto(self.i2c_addr, bytes([0]))
22 utime.sleep_ms(20) # Allow LCD time to powerup
23 # Send reset 3 times
24 self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
25 utime.sleep_ms(5) # Need to delay at least 4.1 msec
26 self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
27 utime.sleep_ms(1)
28 self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
29 utime.sleep_ms(1)
30 # Put LCD into 4-bit mode
31 self.hal_write_init_nibble(self.LCD_FUNCTION)
32 utime.sleep_ms(1)
33 LcdApi.__init__(self, num_lines, num_columns)
34 cmd = self.LCD_FUNCTION
35 if num_lines > 1:
36 cmd |= self.LCD_FUNCTION_2LINES
37 self.hal_write_command(cmd)
38
39 def hal_write_init_nibble(self, nibble):
40 # Writes an initialization nibble to the LCD.
41 # This particular function is only used during initialization.
42 byte = ((nibble >> 4) & 0x0f) << SHIFT_DATA
43 self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
44 self.i2c.writeto(self.i2c_addr, bytes([byte]))
45
46 def hal_backlight_on(self):
47 # Allows the hal layer to turn the backlight on
48 self.i2c.writeto(self.i2c_addr, bytes([1 << SHIFT_BACKLIGHT]))
49
50 def hal_backlight_off(self):
51 #Allows the hal layer to turn the backlight off
52 self.i2c.writeto(self.i2c_addr, bytes([0]))
53
54 def hal_write_command(self, cmd):
55 # Write a command to the LCD. Data is latched on the falling edge of E.
56 byte = ((self.backlight << SHIFT_BACKLIGHT) |
57 (((cmd >> 4) & 0x0f) << SHIFT_DATA))
58 self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
59 self.i2c.writeto(self.i2c_addr, bytes([byte]))
60 byte = ((self.backlight << SHIFT_BACKLIGHT) |
61 ((cmd & 0x0f) << SHIFT_DATA))
62 self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
63 self.i2c.writeto(self.i2c_addr, bytes([byte]))
64 if cmd <= 3:
65 # The home and clear commands require a worst case delay of 4.1 msec
66 utime.sleep_ms(5)
67
68 def hal_write_data(self, data):
69 # Write data to the LCD. Data is latched on the falling edge of E.
70 byte = (MASK_RS |
71 (self.backlight << SHIFT_BACKLIGHT) |
72 (((data >> 4) & 0x0f) << SHIFT_DATA))
73 self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
74 self.i2c.writeto(self.i2c_addr, bytes([byte]))
75 byte = (MASK_RS |
76 (self.backlight << SHIFT_BACKLIGHT) |
77 ((data & 0x0f) << SHIFT_DATA))
78 self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
79 self.i2c.writeto(self.i2c_addr, bytes([byte]))