]>
vault307.fbx.one Git - RPI-PICO-I2C-LCD.git/blob - pico_i2c_lcd.py
3 from lcd_api
import LcdApi
4 from machine
import I2C
6 # PCF8574 pin definitions
11 SHIFT_BACKLIGHT
= 3 # P3
12 SHIFT_DATA
= 4 # P4-P7
16 #Implements a HD44780 character LCD connected via PCF8574 on I2C
18 def __init__(self
, i2c
, i2c_addr
, num_lines
, num_columns
):
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
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
)
28 self
.hal_write_init_nibble(self
.LCD_FUNCTION_RESET
)
30 # Put LCD into 4-bit mode
31 self
.hal_write_init_nibble(self
.LCD_FUNCTION
)
33 LcdApi
.__init
__(self
, num_lines
, num_columns
)
34 cmd
= self
.LCD_FUNCTION
36 cmd |
= self
.LCD_FUNCTION_2LINES
37 self
.hal_write_command(cmd
)
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
]))
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
]))
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]))
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
]))
65 # The home and clear commands require a worst case delay of 4.1 msec
68 def hal_write_data(self
, data
):
69 # Write data to the LCD. Data is latched on the falling edge of E.
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
]))
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
]))