ich habe mich die letzten Tage einmal daran versucht ein 20x4 LCD (HD44780 kompatibel) mit dem Raspberry Pi anzusteuern. Dabei kam folgender Code heraus:
Code: Alles auswählen
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time
class LCD20x4(object):
PIN_MAPPING = {'RS':7, 'E':8, 'DB4':25, 'DB5':24, 'DB6':23, 'DB7':18, 'DB0': 11, 'DB1': 9, 'DB2':10, 'DB3': 22}
PIN_NUMBERING = GPIO.BCM
BIT_MODE = 4 #-> 4: 4-bit, 8: 8-bit
LINE_OFFSETS = [0x00, 0x40, 0x14, 0x54]
LINE_WIDTH = 20
LINE_NUMBER = len(LINE_OFFSETS)
def __init__(self):
GPIO.setmode(LCD20x4.PIN_NUMBERING)
GPIO.setup(LCD20x4.PIN_MAPPING['RS'], GPIO.OUT)
GPIO.setup(LCD20x4.PIN_MAPPING['E'], GPIO.OUT)
for i in range(LCD20x4.BIT_MODE):
GPIO.setup(LCD20x4.PIN_MAPPING['DB{0}'.format(7 - i)], GPIO.OUT)
self.reset()
def __del__(self):
GPIO.cleanup()
def _cmd(self, data, char_mode=False, delay=0.00005):
GPIO.output(LCD20x4.PIN_MAPPING['RS'], char_mode)
for n in range(8 // LCD20x4.BIT_MODE):
for i in range(LCD20x4.BIT_MODE):
bit_shift = (7 - (i + (LCD20x4.BIT_MODE * n)))
GPIO.output(LCD20x4.PIN_MAPPING['DB{0}'.format(7 - i)], bool(data & (1 << bit_shift)))
for _ in range(2):
GPIO.output(LCD20x4.PIN_MAPPING['E'], not GPIO.input(LCD20x4.PIN_MAPPING['E']))
time.sleep(delay)
def reset(self):
for i in range(LCD20x4.BIT_MODE):
GPIO.output(LCD20x4.PIN_MAPPING['DB{0}'.format(7 - i)], False)
function_set = (1 << 5) | ((1 if LCD20x4.BIT_MODE == 8 else 0) << 4) | (1 << 3)
if LCD20x4.BIT_MODE < 8:
self._cmd(0x33, delay = 0.015)
self._cmd(0x32, delay = 0.015)
self._cmd(function_set, delay = 0.015)
else:
for _ in range(3):
self._cmd(function_set, delay = 0.015)
self.display_off()
self.clear_display()
self.display_on()
def clear_display(self):
self._cmd(0x01, delay = 0.010)
def display_off(self):
self._cmd(0x08)
def display_on(self):
self._cmd(0x0C)
def set_cursor_position(self, line, column):
if line in range(1, LCD20x4.LINE_NUMBER + 1) and column in range(1, LCD20x4.LINE_WIDTH + 1):
self._cmd(0x80 + LCD20x4.LINE_OFFSETS[line - 1] + (column - 1))
else:
raise ValueError('... invalid line or column position')
def write_line(self, line, column, text):
self.set_cursor_position(line, column)
for char in text[:(LCD20x4.LINE_WIDTH - column + 1)]:
self.write_char(char)
def clear_line(self, line, column=1):
if line in range(1, LCD20x4.LINE_NUMBER + 1) and column in range(1, LCD20x4.LINE_WIDTH + 1):
self.write_line(line, column, ' ' * (LCD20x4.LINE_WIDTH - column + 1))
def write_char(self, char):
self._cmd(ord(char), True)
if __name__ == '__main__':
lcd = LCD20x4()
for i in range(LCD20x4.LINE_NUMBER):
lcd.write_line(i + 1, i + 1, 'Hello world!')
time.sleep(0.5)
Schöne Grüße