-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi2c_lcd.py
More file actions
73 lines (60 loc) · 2.42 KB
/
i2c_lcd.py
File metadata and controls
73 lines (60 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# i2c_lcd.py - Driver I2C para LCD con PCF8574
import time
from lcd_api import LcdApi
# PCF8574 pin definitions
MASK_RS = 0x01 # P0
MASK_RW = 0x02 # P1
MASK_E = 0x04 # P2
SHIFT_BACKLIGHT = 3 # P3
SHIFT_DATA = 4 # P4-P7
class I2cLcd(LcdApi):
def __init__(self, i2c, i2c_addr, num_lines, num_columns):
self.i2c = i2c
self.i2c_addr = i2c_addr
self.i2c.writeto(self.i2c_addr, bytes([0]))
time.sleep_ms(20)
# Send reset 3 times
self.hal_write_init_nibble(0x30)
time.sleep_ms(5)
self.hal_write_init_nibble(0x30)
time.sleep_ms(1)
self.hal_write_init_nibble(0x30)
time.sleep_ms(1)
# Put LCD into 4-bit mode
self.hal_write_init_nibble(0x20)
time.sleep_ms(1)
LcdApi.__init__(self, num_lines, num_columns)
cmd = 0x20
if num_lines > 1:
cmd |= 0x08
self.hal_write_command(cmd)
def hal_write_init_nibble(self, nibble):
byte = ((nibble >> 4) & 0x0f) << SHIFT_DATA
self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytes([byte]))
def hal_backlight_on(self):
self.i2c.writeto(self.i2c_addr, bytes([1 << SHIFT_BACKLIGHT]))
def hal_backlight_off(self):
self.i2c.writeto(self.i2c_addr, bytes([0]))
def hal_write_command(self, cmd):
byte = ((self.backlight << SHIFT_BACKLIGHT) |
(((cmd >> 4) & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytes([byte]))
byte = ((self.backlight << SHIFT_BACKLIGHT) |
((cmd & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytes([byte]))
if cmd <= 3:
time.sleep_ms(5)
def hal_write_data(self, data):
byte = (MASK_RS |
(self.backlight << SHIFT_BACKLIGHT) |
(((data >> 4) & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytes([byte]))
byte = (MASK_RS |
(self.backlight << SHIFT_BACKLIGHT) |
((data & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytes([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytes([byte]))