summaryrefslogtreecommitdiff
path: root/bin/hardware_driver.py
diff options
context:
space:
mode:
Diffstat (limited to 'bin/hardware_driver.py')
-rw-r--r--bin/hardware_driver.py68
1 files changed, 68 insertions, 0 deletions
diff --git a/bin/hardware_driver.py b/bin/hardware_driver.py
new file mode 100644
index 0000000..1afb219
--- /dev/null
+++ b/bin/hardware_driver.py
@@ -0,0 +1,68 @@
1from smbus2 import SMBus
2from time import sleep
3
4ALIGN_FUNC = {"left": "ljust", "right": "rjust", "center": "center"}
5CLEAR_DISPLAY = 0x01
6ENABLE_BIT = 0b00000100
7LINES = {1: 0x80, 2: 0xC0, 3: 0x94, 4: 0xD4}
8
9LCD_BACKLIGHT = 0x08
10LCD_NOBACKLIGHT = 0x00
11
12
13class LCD(object):
14
15 def __init__(self, address=0x27, bus=1, width=20, rows=4, backlight=True):
16 self.address = address
17 self.bus = SMBus(bus)
18 self.delay = 0.0005
19 self.rows = rows
20 self.width = width
21 self.backlight_status = backlight
22
23 self.write(0x33)
24 self.write(0x32)
25 self.write(0x06)
26 self.write(0x0C)
27 self.write(0x28)
28 self.write(CLEAR_DISPLAY)
29 sleep(self.delay)
30
31 def _write_byte(self, byte):
32 self.bus.write_byte(self.address, byte)
33 self.bus.write_byte(self.address, (byte | ENABLE_BIT))
34 sleep(self.delay)
35 self.bus.write_byte(self.address, (byte & ~ENABLE_BIT))
36 sleep(self.delay)
37
38 def write(self, byte, mode=0):
39 backlight_mode = LCD_BACKLIGHT if self.backlight_status else LCD_NOBACKLIGHT
40 self._write_byte(mode | (byte & 0xF0) | backlight_mode)
41 self._write_byte(mode | ((byte << 4) & 0xF0) | backlight_mode)
42
43 def text(self, text, line, align="left"):
44 self.write(LINES.get(line, LINES[1]))
45 text, other_lines = self.get_text_line(text)
46 text = getattr(text, ALIGN_FUNC.get(align, "ljust"))(self.width)
47 for char in text:
48 self.write(ord(char), mode=1)
49 if other_lines and line <= self.rows - 1:
50 self.text(other_lines, line + 1, align=align)
51
52 def backlight(self, turn_on=True):
53 self.backlight_status = turn_on
54 self.write(0)
55
56 def get_text_line(self, text):
57 line_break = self.width
58 if len(text) > self.width:
59 line_break = text[: self.width + 1].rfind(" ")
60 if line_break < 0:
61 line_break = self.width
62 return text[:line_break], text[line_break:].strip()
63
64 def clear(self):
65 self.write(CLEAR_DISPLAY)
66
67 def read(self):
68 self._read_i2c_block_data