]>
vault307.fbx.one Git - RPI-PICO-I2C-LCD.git/blob - pico_i2c_lcd.py
4 from lcd_api
import LcdApi
5 from machine
import I2C
7 # PCF8574 pin definitions
12 SHIFT_BACKLIGHT
= 3 # P3
13 SHIFT_DATA
= 4 # P4-P7
17 #Implements a HD44780 character LCD connected via PCF8574 on I2C
19 def __init__(self
, i2c
, i2c_addr
, num_lines
, num_columns
):
21 self
.i2c_addr
= i2c_addr
22 self
.i2c
.writeto(self
.i2c_addr
, bytes([0]))
23 utime
.sleep_ms(20) # Allow LCD time to powerup
25 self
.hal_write_init_nibble(self
.LCD_FUNCTION_RESET
)
26 utime
.sleep_ms(5) # Need to delay at least 4.1 msec
27 self
.hal_write_init_nibble(self
.LCD_FUNCTION_RESET
)
29 self
.hal_write_init_nibble(self
.LCD_FUNCTION_RESET
)
31 # Put LCD into 4-bit mode
32 self
.hal_write_init_nibble(self
.LCD_FUNCTION
)
34 LcdApi
.__init
__(self
, num_lines
, num_columns
)
35 cmd
= self
.LCD_FUNCTION
37 cmd |
= self
.LCD_FUNCTION_2LINES
38 self
.hal_write_command(cmd
)
41 def hal_write_init_nibble(self
, nibble
):
42 # Writes an initialization nibble to the LCD.
43 # This particular function is only used during initialization.
44 byte
= ((nibble
>> 4) & 0x0f) << SHIFT_DATA
45 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte | MASK_E
]))
46 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte
]))
49 def hal_backlight_on(self
):
50 # Allows the hal layer to turn the backlight on
51 self
.i2c
.writeto(self
.i2c_addr
, bytes([1 << SHIFT_BACKLIGHT
]))
54 def hal_backlight_off(self
):
55 #Allows the hal layer to turn the backlight off
56 self
.i2c
.writeto(self
.i2c_addr
, bytes([0]))
59 def hal_write_command(self
, cmd
):
60 # Write a command to the LCD. Data is latched on the falling edge of E.
61 byte
= ((self
.backlight
<< SHIFT_BACKLIGHT
) |
62 (((cmd
>> 4) & 0x0f) << SHIFT_DATA
))
63 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte | MASK_E
]))
64 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte
]))
65 byte
= ((self
.backlight
<< SHIFT_BACKLIGHT
) |
66 ((cmd
& 0x0f) << SHIFT_DATA
))
67 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte | MASK_E
]))
68 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte
]))
70 # The home and clear commands require a worst case delay of 4.1 msec
74 def hal_write_data(self
, data
):
75 # Write data to the LCD. Data is latched on the falling edge of E.
77 (self
.backlight
<< SHIFT_BACKLIGHT
) |
78 (((data
>> 4) & 0x0f) << SHIFT_DATA
))
79 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte | MASK_E
]))
80 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte
]))
82 (self
.backlight
<< SHIFT_BACKLIGHT
) |
83 ((data
& 0x0f) << SHIFT_DATA
))
84 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte | MASK_E
]))
85 self
.i2c
.writeto(self
.i2c_addr
, bytes([byte
]))