From 2f24129ab1df7e3fea96ae0088b623ba7496e033 Mon Sep 17 00:00:00 2001 From: bstin Date: Mon, 23 Sep 2024 09:56:26 -0500 Subject: [PATCH] Extended print with newline and center char The print function will now recognize newline and center chars and modify string accordingly. The newline and center chars are configurable but set as "\n" and "\c" by default. --- lcd_i2c/lcd_i2c.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/lcd_i2c/lcd_i2c.py b/lcd_i2c/lcd_i2c.py index e1c7567..deb4bf2 100644 --- a/lcd_i2c/lcd_i2c.py +++ b/lcd_i2c/lcd_i2c.py @@ -59,6 +59,8 @@ def __init__(self, self._display_mode: int = 0 self._display_function: int = 0 self._cursor_position: Tuple[int, int] = (0, 0) # (x, y) + self._newline_char="\n" + self._center_char="\c" @property def addr(self) -> int: @@ -396,15 +398,23 @@ def create_char(self, location: int, charmap: List[int]) -> None: def print(self, text: str) -> None: """ Print text on LCD - :param test: Text to show on the LCD :type text: str + Note: + - if self._newline_char is passed line will be broken there + - if self._center_char is found, line will be centered """ _cursor_x, _cursor_y = self.cursor_position - - for char in text: - self._command(value=ord(char), mode=Const.RS) - + split_str=text.split(self._newline_char) + for line in split_str: + if line.find('\c')>=0: + newline=line.strip('\c') + newline=newline.center(self._cols) + else: + newline=line + for char in newline: + self._command(value=ord(char), mode=Const.RS) + self.set_cursor(0,1) self.cursor_position = (_cursor_x + len(text), _cursor_y) def _command(self, value: int, mode: int = 0) -> None: @@ -452,3 +462,4 @@ def _expander_write(self, value: int) -> None: :type value: int """ self._i2c.writeto(self.addr, bytes([value | self._backlightval])) +