diff options
| author | Abdellah El Morabit <nsrddyn@gmail.com> | 2024-11-24 13:04:20 +0100 |
|---|---|---|
| committer | Abdellah El Morabit <nsrddyn@gmail.com> | 2024-11-24 13:04:20 +0100 |
| commit | d2dea805ee0ec0724a5f2802fed71d20036799bc (patch) | |
| tree | 920b2c07dc37a497a6b61b9e65eab96a0adae700 /bin/source/hardware_driver.py | |
| parent | 9f3e2f9df51db83a0fd64e2979f71394ab3cef36 (diff) | |
| parent | b78c236641f3f8c1c2041910cc156397fdc6c293 (diff) | |
Merge remote-tracking branch 'refs/remotes/origin/main'
Diffstat (limited to 'bin/source/hardware_driver.py')
| -rw-r--r-- | bin/source/hardware_driver.py | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/bin/source/hardware_driver.py b/bin/source/hardware_driver.py new file mode 100644 index 0000000..1afb219 --- /dev/null +++ b/bin/source/hardware_driver.py @@ -0,0 +1,68 @@ +from smbus2 import SMBus +from time import sleep + +ALIGN_FUNC = {"left": "ljust", "right": "rjust", "center": "center"} +CLEAR_DISPLAY = 0x01 +ENABLE_BIT = 0b00000100 +LINES = {1: 0x80, 2: 0xC0, 3: 0x94, 4: 0xD4} + +LCD_BACKLIGHT = 0x08 +LCD_NOBACKLIGHT = 0x00 + + +class LCD(object): + + def __init__(self, address=0x27, bus=1, width=20, rows=4, backlight=True): + self.address = address + self.bus = SMBus(bus) + self.delay = 0.0005 + self.rows = rows + self.width = width + self.backlight_status = backlight + + self.write(0x33) + self.write(0x32) + self.write(0x06) + self.write(0x0C) + self.write(0x28) + self.write(CLEAR_DISPLAY) + sleep(self.delay) + + def _write_byte(self, byte): + self.bus.write_byte(self.address, byte) + self.bus.write_byte(self.address, (byte | ENABLE_BIT)) + sleep(self.delay) + self.bus.write_byte(self.address, (byte & ~ENABLE_BIT)) + sleep(self.delay) + + def write(self, byte, mode=0): + backlight_mode = LCD_BACKLIGHT if self.backlight_status else LCD_NOBACKLIGHT + self._write_byte(mode | (byte & 0xF0) | backlight_mode) + self._write_byte(mode | ((byte << 4) & 0xF0) | backlight_mode) + + def text(self, text, line, align="left"): + self.write(LINES.get(line, LINES[1])) + text, other_lines = self.get_text_line(text) + text = getattr(text, ALIGN_FUNC.get(align, "ljust"))(self.width) + for char in text: + self.write(ord(char), mode=1) + if other_lines and line <= self.rows - 1: + self.text(other_lines, line + 1, align=align) + + def backlight(self, turn_on=True): + self.backlight_status = turn_on + self.write(0) + + def get_text_line(self, text): + line_break = self.width + if len(text) > self.width: + line_break = text[: self.width + 1].rfind(" ") + if line_break < 0: + line_break = self.width + return text[:line_break], text[line_break:].strip() + + def clear(self): + self.write(CLEAR_DISPLAY) + + def read(self): + self._read_i2c_block_data |
