123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618 |
- """
- Author: Tobias Müller
- Date: 13.09.2023
- Version: 1.0
- This file contains a class for a LCD.
- """
- ############################## Modules ##############################
- from machine import Pin, PWM, I2C
- import re
- ############################## Code ##############################
- class LCD:
- """
- Class to control a DOGS104-A LC-Display.
- """
- ############################## Attributes ##############################
- __lcd_setting_para = {"LCD_PARA_EXT_FUNC": 0x09, # Extended Function (4 line mode) # type: ignore
- "LCD_PARA_BIAS_SET": 0x12, # Bias Setting (BS1 = 1) # type: ignore
- "LCD_PARA_INT_OSC": 0x1B, # Internal OSC (BS0 = 1, Bias = 1/6)
- "LCD_PARA_FOL_CON": 0x6E, # Follower Control (Devider on, Set Value)
- "LCD_PARA_DIS_CON": 0x0C} # Display on/off Control (Cursor off, Blink off)
- __lcd_contrast_para = {"LCD_PARA_POW_CON": 0x54, # Power Control (Booster on) and Contrast (C5, C4)
- "LCD_PARA_CONTRAST": 0x70} # Contrast (C3 - C0)
- __lcd_line_mode_para = {"LCD_PARA_LINES": 0x12} # Line Mode
-
- __lcd_direction_para = {"LCD_PARA_ENTRY_MODE": 0x04} # Display direction / orientation
- __lcd_control_para_priv = {"CONTROL_BYTE": 0x00, # Control Byte
- "CONTROL_BYTE_C0": 0x80, # Control Byte (C0 = 1)
- "CONTROL_BYTE_RS": 0x40, # Control Byte (RS = 1)
- "CONTROL_BYTE_C0_RS": 0xC0, # Control Byte (C0 = 1, RS = 1)
- "FUNCTION_SET": 0x38, # Function Set
- "FUNCTION_SET_RE": 0x3A, # Function Set (RE = 1)
- "FUNCTION_SET_IS": 0x39, # Function Set (IS = 1)
- "CLEAR_DISPLAY": 0x01, # Clear Display
- "DISPLAY_ROW_1": 0x80, # Display Row 1
- "DISPLAY_ROW_2": 0xA0, # Display Row 2
- "DISPLAY_ROW_3": 0xC0, # Display Row 3
- "DISPLAY_ROW_4": 0xE0, # Display Row 4
- "DISPLAY_COLUMN": 0x0A} # Columns per Display Row
- __lcd_rom_para = {"LCD_PARA_ROM_SEL": 0x72}
- __lcd_rom = {"ROM A": 0, "ROM B": 1, "ROM C": 2,
- "A": 0, "B": 1, "C": 2,
- 1: 0, 2: 1, 3: 2}
- __i2c_ports = {"I2C0": {"SDA_PINS": [0, 4 ,8 ,12 ,16 ,20],
- "SCL_PINS": [1, 5, 9, 13, 17, 21]},
- "I2C1": {"SDA_PINS": [2, 6, 10, 14, 18, 26],
- "SCL_PINS": [3, 7, 11, 15, 19, 27]}}
-
- __i2c_frequencies = {"STANDARD_MODE": 100000,
- "FAST_MODE": 400000}
- __i2c_address = 0x3c
- ############################## Constructor ##############################
- def __init__(self,
- i2c_sda_pin: int|str = 2,
- i2c_scl_pin: int|str = 3,
- i2c_frequency: int|str = "STANDARD_MODE",
- lcd_backlight_pin: int|str = 28,
- lcd_brightness: int = 100,
- lcd_contrast: int = 60,
- lcd_ascii_rom: int|str = "ROM B",
- lcd_line_mode: int = 0,
- lcd_direction_top: int|bool = False):
- """
- Initialize LCD. Alls arguments can be changed later as a property.
- Args:
- i2c_sda_pin (int | str, optional): Set SDA-Pin for I2C-Bus. Defaults to 2.
- i2c_scl_pin (int | str, optional): Set SCL-Pin for I2C-Bus. Defaults to 3.
- i2c_frequency (int | str, optional): Set I2C frequency. Defaults to "STANDARD_MODE".
- lcd_backlight_pin (int | str, optional): Set LCD backlight pin. Defaults to 28.
- lcd_brightness (int, optional): Set LCD brightness in percent. Defaults to 100.
- lcd_contrast (int, optional): Set LCD contrast in percent. Defaults to 60.
- lcd_ascii_rom (int | str, optional): Set ASCII-ROM. Defaults to "ROM B".
- lcd_line_mode (int, optional): Set LCD line mode for 2-, 3- or 4-lines. Defaults to 0.
- lcd_direction_top (int | bool, optional): Set LCD direction to top. Defaults to False.
- """
- # Check and store input values
- self.__i2c_bus, self.__i2c_sda_pin, self.__i2c_scl_pin = self.__check_i2c_ports(i2c_sda_pin,
- i2c_scl_pin)
- self.__i2c_frequency = self.__check_i2c_frequency(i2c_frequency)
- self.__lcd_backlight_pin = self.__check_lcd_backlight_pin(lcd_backlight_pin)
- self.__lcd_brightness = self.__check_lcd_brightness(lcd_brightness)
- self.__lcd_contrast = self.__check_lcd_contrast(lcd_contrast)
- self.__lcd_ascii_rom = self.__check_lcd_ascii_rom(lcd_ascii_rom)
- self.__lcd_line_mode = self.__check_lcd_line_mode(lcd_line_mode)
- self.__lcd_direction_top = self.__check_lcd_direction_top(lcd_direction_top)
- # init i2c and backlight
- self.__init_i2c()
- self.__init_backlight_pwm()
-
- ############################## Properties private ##############################
-
- @property
- def __lcd_control_para(self):
- lcd_control_para = self.__lcd_control_para_priv.copy()
- if self.__lcd_line_mode:
- lcd_control_para["FUNCTION_SET"] = 0x3C
- if self.__lcd_direction_top:
- lcd_control_para["DISPLAY_ROW_1"] = 0x8A
- lcd_control_para["DISPLAY_ROW_2"] = 0xAA
- lcd_control_para["DISPLAY_ROW_3"] = 0xCA
- lcd_control_para["DISPLAY_ROW_4"] = 0xEA
- return lcd_control_para
- ############################## Properties ##############################
- @property
- def lcd_brightness(self):
- return self.__lcd_brightness
- @lcd_brightness.setter
- def lcd_brightness(self, lcd_brightness: int):
- self.__lcd_brightness = self.__check_lcd_brightness(lcd_brightness)
- self.__set_lcd_brightness()
-
- @property
- def lcd_ascii_rom(self):
- return self.__lcd_ascii_rom
- @lcd_ascii_rom.setter
- def lcd_ascii_rom(self, lcd_ascii_rom: int|str):
- self.__lcd_ascii_rom = self.__check_lcd_ascii_rom(lcd_ascii_rom)
- self.__set_lcd_ascii_rom()
- @property
- def lcd_contrast(self):
- return self.__lcd_contrast
- @lcd_contrast.setter
- def lcd_contrast(self, lcd_contrast: int):
- print("Hallo")
- self.__lcd_contrast = self.__check_lcd_contrast(lcd_contrast)
- self.__set_lcd_contrast()
- @property
- def lcd_direction_top(self):
- return self.__lcd_direction_top
- @lcd_direction_top.setter
- def lcd_direction_top(self, lcd_direction_top: int|bool):
- buffer = self.read()
- self.__lcd_direction_top = self.__check_lcd_direction_top(lcd_direction_top)
- self.clear()
- self.__set_lcd_direction()
- self.clear()
- self.print(str(buffer))
- @property
- def lcd_line_mode(self):
- return self.__lcd_line_mode
- @lcd_line_mode.setter
- def lcd_line_mode(self, lcd_line_mode: int):
- buffer = self.__check_lcd_line_mode(lcd_line_mode)
- if lcd_line_mode and self.__lcd_line_mode == 0:
- self.clear(row=4)
- if lcd_line_mode == 3 and self.__lcd_line_mode != 3:
- self.clear(row=3)
- self.__lcd_line_mode = buffer
- self.__set_lcd_line_mode()
- @property
- def lcd_backlight_pin(self):
- return self.__lcd_backlight_pin
- @lcd_backlight_pin.setter
- def lcd_backlight_pin(self, lcd_backlight_pin: int|str):
- self.__check_lcd_backlight_pin(lcd_backlight_pin)
- self.__deinit_backlight_pwm()
- self.lcd_backlight_pin = lcd_backlight_pin
- self.__init_backlight_pwm()
- @property
- def i2c_frequency(self):
- return self.__i2c_frequency
- @i2c_frequency.setter
- def i2c_frequency(self, i2c_frequency: int|str):
- self.__check_i2c_frequency(i2c_frequency)
- self.__deinit_i2c()
- self.__i2c_frequency = i2c_frequency
- self.__init_i2c()
- @property
- def i2c_sda_pin(self):
- return self.__i2c_sda_pin
- @i2c_sda_pin.setter
- def i2c_sda_pin(self, i2c_sda_pin: int|str):
- self.change_i2c_port(i2c_sda_pin, self.__i2c_scl_pin)
- @property
- def i2c_scl_pin(self):
- return self.__i2c_scl_pin
- @i2c_scl_pin.setter
- def i2c_scl_pin(self, i2c_scl_pin: int|str):
- self.change_i2c_port(self.__i2c_sda_pin, i2c_scl_pin)
- ############################## Methods private ##############################
- @staticmethod
- def __reset_pin(pin: int|str):
- Pin(pin, Pin.IN, pull=None)
- @staticmethod
- def __check_lcd_brightness(lcd_brightness: int):
- if not isinstance(lcd_brightness, int):
- raise ValueError(f"Value \"{lcd_brightness}\" of \"lcd_brightness\" is not type \"int\"!")
- elif lcd_brightness < 0 or lcd_brightness > 100:
- raise ValueError(f"Value \"{lcd_brightness}\" of \"lcd_brightness\" is out of range!")
- else:
- return lcd_brightness
- @staticmethod
- def __check_lcd_backlight_pin(lcd_backlight_pin: int|str):
- if not isinstance(lcd_backlight_pin, int) and not isinstance(lcd_backlight_pin, str):
- raise ValueError(f"Value \"{lcd_backlight_pin}\" of \"lcd_backlight_pin\" is not type" +
- " \"int\" or \"str\"!")
- elif isinstance(lcd_backlight_pin, str) and not re.match(r"^GP\d\d?$",lcd_backlight_pin):
- raise ValueError(f"String value \"{lcd_backlight_pin}\" of \"lcd_backlight_pin\" has" +
- " wrong format!")
- else:
- return lcd_backlight_pin
- @staticmethod
- def __check_lcd_line_mode(lcd_line_mode: int):
- if not isinstance(lcd_line_mode, int):
- raise ValueError(f"Value \"{lcd_line_mode}\" of \"lcd_line_mode\" is not type \"int\"!")
- elif lcd_line_mode < 0 or lcd_line_mode > 4:
- raise ValueError(f"Value \"{lcd_line_mode}\" of \"lcd_line_mode\" is out of range!")
- else:
- return lcd_line_mode
- @staticmethod
- def __check_lcd_direction_top(lcd_direction_top: int|bool):
- if not isinstance(lcd_direction_top, int) and not isinstance(lcd_direction_top, bool):
- raise ValueError(f"Value \"{lcd_direction_top}\" of \"lcd_direction_top\" is not type" +
- " \"int\" or \"bool\"!")
- elif isinstance(lcd_direction_top, int) and (lcd_direction_top < 0 or lcd_direction_top > 1):
- raise ValueError(f"Value \"{lcd_direction_top}\" of \"lcd_direction_top\" is out of range!")
- else:
- return lcd_direction_top
- @staticmethod
- def __check_lcd_contrast(lcd_contrast: int):
- if not isinstance(lcd_contrast, int):
- raise ValueError(f"Value \"{lcd_contrast}\" of \"lcd_contrast\" is not type \"int\"!")
- elif lcd_contrast < 0 or lcd_contrast > 100:
- raise ValueError(f"Value \"{lcd_contrast}\" of \"lcd_contrast\" is out of range!")
- else:
- return lcd_contrast
- def __check_lcd_ascii_rom(self, lcd_ascii_rom: int|str):
- if not isinstance(lcd_ascii_rom, int) and not isinstance(lcd_ascii_rom, str):
- raise ValueError(f"Value \"{lcd_ascii_rom}\" of \"lcd_ascii_rom\" is not type" +
- " \"int\" or \"str\"!")
- elif((isinstance(lcd_ascii_rom, int) and lcd_ascii_rom not in self.__lcd_rom.keys()) or
- (isinstance(lcd_ascii_rom, str) and lcd_ascii_rom.upper() not in self.__lcd_rom.keys())):
- raise ValueError(f"Value \"{lcd_ascii_rom}\" of \"lcd_ascii_rom\" is not supported!")
- else:
- return lcd_ascii_rom
- def __check_i2c_ports(self, i2c_sda_pin: int|str, i2c_scl_pin: int|str):
- if not isinstance(i2c_sda_pin, int) and not isinstance(i2c_sda_pin, str):
- raise ValueError(f"Value \"{i2c_sda_pin}\" of \"i2c_sda_pin\" is not type \"int\"" +
- " or \"str\"!")
- elif not isinstance(i2c_scl_pin, int) and not isinstance(i2c_scl_pin, str):
- raise ValueError(f"Value \"{i2c_scl_pin}\" of \"i2c_scl_pin\" is not type \"int\"" +
- " or \"str\"!")
- elif isinstance(i2c_sda_pin, str) and not re.match(r"^GP\d\d?$",i2c_sda_pin):
- raise ValueError(f"String value \"{i2c_sda_pin}\" of \"i2c_sda_pin\" has wrong format!")
- elif isinstance(i2c_scl_pin, str) and not re.match(r"^GP\d\d?$",i2c_scl_pin):
- raise ValueError(f"String value \"{i2c_scl_pin}\" of \"i2c_scl_pin\" has wrong format!")
- elif ((isinstance(i2c_sda_pin, int) and
- not i2c_sda_pin in self.__i2c_ports["I2C0"]["SDA_PINS"] and
- not i2c_sda_pin in self.__i2c_ports["I2C1"]["SDA_PINS"]) or
- (isinstance(i2c_sda_pin, str) and
- not int(i2c_sda_pin[2:]) in self.__i2c_ports["I2C0"]["SDA_PINS"] and
- not int(i2c_sda_pin[2:]) in self.__i2c_ports["I2C1"]["SDA_PINS"])):
- raise ValueError(f"Value \"{i2c_sda_pin}\" of \"i2c_sda_pin\" is not an I2C SDA-Pin!")
- elif ((isinstance(i2c_scl_pin, int) and
- not i2c_scl_pin in self.__i2c_ports["I2C0"]["SCL_PINS"] and
- not i2c_scl_pin in self.__i2c_ports["I2C1"]["SCL_PINS"]) or
- (isinstance(i2c_scl_pin, str) and
- not int(i2c_scl_pin[2:]) in self.__i2c_ports["I2C0"]["SCL_PINS"] and
- not int(i2c_scl_pin[2:]) in self.__i2c_ports["I2C1"]["SCL_PINS"])):
- raise ValueError(f"Value \"{i2c_scl_pin}\" of \"i2c_scl_pin\" is not an I2C SCL-Pin!")
- elif ((((isinstance(i2c_sda_pin, int) and
- i2c_sda_pin in self.__i2c_ports["I2C0"]["SDA_PINS"]) or
- (isinstance(i2c_sda_pin, str) and
- int(i2c_sda_pin[2:]) in self.__i2c_ports["I2C0"]["SDA_PINS"])) and not
- ((isinstance(i2c_scl_pin, int) and
- i2c_scl_pin in self.__i2c_ports["I2C0"]["SCL_PINS"]) or
- (isinstance(i2c_scl_pin, str) and
- int(i2c_scl_pin[2:]) in self.__i2c_ports["I2C0"]["SCL_PINS"]))) or
- (((isinstance(i2c_sda_pin, int) and
- i2c_sda_pin in self.__i2c_ports["I2C1"]["SDA_PINS"]) or
- (isinstance(i2c_sda_pin, str) and
- int(i2c_sda_pin[2:]) in self.__i2c_ports["I2C1"]["SDA_PINS"])) and not
- ((isinstance(i2c_scl_pin, int) and
- i2c_scl_pin in self.__i2c_ports["I2C1"]["SCL_PINS"]) or
- (isinstance(i2c_scl_pin, str) and
- int(i2c_scl_pin[2:]) in self.__i2c_ports["I2C1"]["SCL_PINS"])))):
- raise ValueError(f"Value \"{i2c_scl_pin}\" of \"i2c_scl_pin\" and " +
- f"Value \"{i2c_sda_pin}\" of \"i2c_sda_pin\" " +
- "are not part of the same I2C Bus!")
- else:
- if ((isinstance(i2c_sda_pin, int) and
- i2c_sda_pin in self.__i2c_ports["I2C0"]["SDA_PINS"]) or
- (isinstance(i2c_sda_pin, str) and
- int(i2c_sda_pin[2:]) in self.__i2c_ports["I2C0"]["SDA_PINS"])):
- return 0, i2c_sda_pin, i2c_scl_pin
- else:
- return 1, i2c_sda_pin, i2c_scl_pin
- def __check_i2c_frequency(self, i2c_frequency: int|str):
- if not isinstance(i2c_frequency, int) and not isinstance(i2c_frequency, str):
- raise ValueError(f"Value \"{i2c_frequency}\" of \"i2c_frequency\" is not type \"int\"" +
- " or \"str\"!")
- elif (isinstance(i2c_frequency, int) and not i2c_frequency in self.__i2c_frequencies.values() or
- isinstance(i2c_frequency, str) and not i2c_frequency in self.__i2c_frequencies.keys()):
- raise ValueError(f"Value \"{i2c_frequency}\" of \"i2c_frequency\" is not supported!")
- else:
- return i2c_frequency
-
- def __init_i2c(self):
- self.__i2c = I2C(self.__i2c_bus,
- sda=Pin(self.__i2c_sda_pin),
- scl=Pin(self.__i2c_scl_pin),
- freq=(self.__i2c_frequency if isinstance(self.__i2c_frequency, int) else
- self.__i2c_frequencies[self.__i2c_frequency]))
- buffer = (self.__lcd_control_para["CONTROL_BYTE"],
- self.__lcd_control_para["FUNCTION_SET_RE"],
- self.__lcd_setting_para["LCD_PARA_EXT_FUNC"],
- self.__lcd_setting_para["LCD_PARA_BIAS_SET"],
- self.__lcd_control_para["FUNCTION_SET_IS"],
- self.__lcd_setting_para["LCD_PARA_INT_OSC"],
- self.__lcd_setting_para["LCD_PARA_FOL_CON"],
- self.__lcd_control_para["FUNCTION_SET"],
- self.__lcd_setting_para["LCD_PARA_DIS_CON"])
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- self.__set_lcd_line_mode()
- self.__set_lcd_ascii_rom()
- self.__set_lcd_contrast()
- self.__set_lcd_direction()
- self.clear()
- def __deinit_i2c(self):
- self.__reset_pin(self.__i2c_scl_pin)
- self.__reset_pin(self.__i2c_sda_pin)
- def __init_backlight_pwm(self):
- self.__backlight_pwm = PWM(Pin(self.__lcd_backlight_pin))
- self.__backlight_pwm.freq(1000)
- self.__set_lcd_brightness()
- def __deinit_backlight_pwm(self):
- self.__backlight_pwm.deinit()
- self.__reset_pin(self.__lcd_backlight_pin)
- def __set_lcd_brightness(self):
- self.__backlight_pwm.duty_u16(round(65635 * (self.__lcd_brightness / 100)))
- def __set_lcd_ascii_rom(self):
- if isinstance(self.__lcd_ascii_rom, str):
- lcd_ascii_rom = self.__lcd_ascii_rom.upper()
- else:
- lcd_ascii_rom = self.__lcd_ascii_rom
- buffer = (self.__lcd_control_para["CONTROL_BYTE_C0"],
- self.__lcd_control_para["FUNCTION_SET_RE"],
- self.__lcd_control_para["CONTROL_BYTE_C0"],
- self.__lcd_rom_para["LCD_PARA_ROM_SEL"],
- self.__lcd_control_para["CONTROL_BYTE_C0_RS"],
- self.__lcd_rom[lcd_ascii_rom] << 0x02,
- self.__lcd_control_para["CONTROL_BYTE"],
- self.__lcd_control_para["FUNCTION_SET"])
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- def __set_lcd_contrast(self):
- contrast = round(63 * (self.__lcd_contrast / 100))
- buffer = (self.__lcd_control_para["CONTROL_BYTE"],
- self.__lcd_control_para["FUNCTION_SET_IS"],
- self.__lcd_contrast_para["LCD_PARA_POW_CON"] | (contrast >> 0x04),
- self.__lcd_contrast_para["LCD_PARA_CONTRAST"] | (contrast & 0x0F),
- self.__lcd_control_para["FUNCTION_SET"])
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- def __set_lcd_direction(self):
- buffer = [self.__lcd_control_para["CONTROL_BYTE"],
- self.__lcd_control_para["FUNCTION_SET_RE"]]
- if self.__lcd_direction_top:
- buffer.append(self.__lcd_direction_para["LCD_PARA_ENTRY_MODE"] | 0x01)
- else:
- buffer.append(self.__lcd_direction_para["LCD_PARA_ENTRY_MODE"] | 0x02)
- buffer.append(self.__lcd_control_para["FUNCTION_SET"])
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- def __set_lcd_line_mode(self):
- buffer = [self.__lcd_control_para["CONTROL_BYTE"],
- self.__lcd_control_para["FUNCTION_SET_RE"]]
- if self.__lcd_line_mode:
- buffer.append(self.__lcd_line_mode_para["LCD_PARA_LINES"] |
- ((self.__lcd_line_mode - 1) << 0x02))
- else:
- buffer.append(self.__lcd_line_mode_para["LCD_PARA_LINES"])
- buffer.append(self.__lcd_control_para["FUNCTION_SET"])
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- def __check_keywords(self, keywords: dict[str,int|bool], keys: list[str]):
- rows = 0x04 if self.__lcd_line_mode == 0x00 else 0x02 if self.__lcd_line_mode == 0x03 else 0x03
- output = {"rows": rows, "row": 0x01, "column": 0x01, "auto_line_break": True, "separate": False}
- for key, val in keywords.items():
- if key not in keys:
- raise KeyError(f"Keyword \"{key}\" is unknown!")
- elif key == "row":
- if not isinstance(val, int):
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is not type \"int\"!")
- elif val > rows or val < 1:
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is out of range!")
- else:
- output.update({key: val})
- elif key == "column":
- if not isinstance(val, int):
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is not type \"int\"!")
- elif val > self.__lcd_control_para["DISPLAY_COLUMN"] or val < 0x01:
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is out of range!")
- else:
- output.update({key: val})
- elif key == "auto_line_break":
- if not isinstance(val, int) and not isinstance(val, bool):
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is not type" +
- " \"int\" or \"bool\"!")
- elif isinstance(val, int) and (val < 0 or val > 1):
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is out of range!")
- else:
- output.update({key: val})
- elif key == "separate":
- if not isinstance(val, int) and not isinstance(val, bool):
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is not type" +
- " \"int\" or \"bool\"!")
- elif isinstance(val, int) and (val < 0 or val > 1):
- raise ValueError(f"Value \"{val}\" of keyword \"{key}\" is out of range!")
- else:
- output.update({key: val})
- return output.copy()
- ############################## Methods public ##############################
- def change_i2c_port(self, i2c_sda_pin: int|str, i2c_scl_pin: int|str):
- """
- Used to change I2C port.
- Args:
- i2c_sda_pin (int | str): SDA-Pin of I2C Port
- i2c_scl_pin (int | str): SCL-Pin of I2C Port
- """
- self.__check_i2c_ports(i2c_sda_pin, i2c_scl_pin)
- self.__deinit_i2c()
- (self.__i2c_bus,
- self.__i2c_sda_pin,
- self.__i2c_scl_pin) = self.__check_i2c_ports(i2c_sda_pin, i2c_scl_pin)
- self.__init_i2c()
- def print(self, text: str, **keywords):
- """
- Used to print text on the LCD.
- Args:
- text (str): Text, which is printed on the LCD.
- Keywords:
- row (int): Row to start printing. Defaults to 1.
- column (int): Column to start printing. Defaults to 1.
- auto_line_break (int | bool): Breaks the line automatically. Defaults to True.
- """
- def check_text(text: str):
- if not isinstance(text, str):
- raise ValueError(f"Value \"{text}\" of \"text\" is not type \"str\"!")
- elif len(text) == 0:
- raise ValueError(f"Value \"{text}\" of \"text\" is out of range!")
- keys = ["row", "column", "auto_line_break"]
- keys = self.__check_keywords(keywords, keys)
- rows = keys["rows"]
- row = keys["row"]
- column = keys["column"]
- auto_line_break = keys["auto_line_break"]
- check_text(text)
- linefeed = ("\n","\r")
- buffer = []
- for line in range(row,rows + 0x01):
- if len(text) == 0x00 or (not auto_line_break and line > row):
- break
- buffer.append(self.__lcd_control_para["CONTROL_BYTE_C0"])
- buffer.append(self.__lcd_control_para["DISPLAY_ROW_" + str(line)] + (column - 0x01))
- for char in range(0x00, (self.__lcd_control_para["DISPLAY_COLUMN"] - (column - 0x01)) if
- len(text) > (self.__lcd_control_para["DISPLAY_COLUMN"] - (column - 0x01)) else
- len(text)):
- if text[char] in linefeed:
- text = text[char + 0x01:]
- for _ in range(char, (self.__lcd_control_para["DISPLAY_COLUMN"] - (column - 0x01)) if
- len(text) > (self.__lcd_control_para["DISPLAY_COLUMN"] - (column - 0x01)) else
- len(text)):
- buffer.append(self.__lcd_control_para["CONTROL_BYTE_C0_RS"])
- buffer.append(ord(" "))
- break
- buffer.append(self.__lcd_control_para["CONTROL_BYTE_C0_RS"])
- buffer.append(ord(text[char]))
- else:
- text = text[self.__lcd_control_para["DISPLAY_COLUMN"] - (column - 0x01):]
- column = 0x01
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- def clear(self, **keywords):
- """
- Used to clear the LCD. If the keywords row or column are not used,
- the method will clear the whole display.
- Keywords:
- row (int): Row to start printing. Defaults to 1.
- column (int): Column to start printing. Defaults to 1.
- auto_line_break (int | bool): Breaks the line automatically. Defaults to True.
- """
- buffer = []
- if len(keywords) == 0:
- buffer.append(self.__lcd_control_para["CONTROL_BYTE"])
- buffer.append(self.__lcd_control_para["CLEAR_DISPLAY"])
- else:
- keys = ["row", "column"]
- keys = self.__check_keywords(keywords, keys)
- row = keys["row"]
- column = keys["column"]
- buffer.append(self.__lcd_control_para["CONTROL_BYTE_C0"])
- buffer.append(self.__lcd_control_para["DISPLAY_ROW_" + str(row)] + (column - 0x01))
- for _ in range(0x00, self.__lcd_control_para["DISPLAY_COLUMN"]):
- buffer.append(self.__lcd_control_para["CONTROL_BYTE_C0_RS"])
- buffer.append(ord(" "))
- if "column" in keywords.keys():
- break
- self.__i2c.writeto(self.__i2c_address, bytes(buffer))
- def read(self, **keywords):
- """
- Used to read from the LCD.
- Keywords:
- row (int): Row to start reading from. Defaults to 1.
- column (int): Column to start reading from. Defaults to 1.
- separate (int | bool): Separate each line into a list. Defaults to False.
-
- Returns:
- list: (separate=True) Returns each line into a list of separate strings.
- str: (separate=False) Returns all lines as one string.
- """
- def remove_whitespace(text: str):
- textlen = len(text)
- endpos = textlen
- for char in range(0x00, textlen):
- if text[textlen - char - 0x01] == " ":
- endpos -= 0x01
- else:
- break
- return text[:endpos]
- keys = ["row", "column", "separate"]
- keys = self.__check_keywords(keywords, keys)
- rows = keys["rows"]
- row = keys["row"]
- column = keys["column"]
- separate = keys["separate"]
- buffer = []
- for line in range(0x01, rows + 0x01):
- tmp = (self.__lcd_control_para["CONTROL_BYTE_C0"],
- self.__lcd_control_para["DISPLAY_ROW_" + str(line)],
- self.__lcd_control_para["CONTROL_BYTE_RS"])
- self.__i2c.writeto(self.__i2c_address,bytes(tmp))
- tmp = self.__i2c.readfrom(self.__i2c_address,11)
- tmp = list(tmp[1:])
- tmp = [chr(tmp[i]) for i in range(0, len(tmp))]
- if ("row" in keywords.keys() or "column" in keywords.keys()) and line != row:
- tmp = [""]
- if "column" in keywords.keys() and line == row:
- tmp = tmp[column - 0x01]
- buffer.append("".join(tmp))
- if not separate:
- return remove_whitespace("".join(buffer))
- else:
- for pos in range(0, len(buffer)):
- buffer[pos] = remove_whitespace(buffer[pos])
- return buffer
- if __name__ == "__main__":
- lcd = LCD(lcd_line_mode=0x03)
- lcd.print("Hochschule Anhalt")
- lcd.lcd_brightness = 50
|