1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import RPi.GPIO as GPIO from random import sample import string import time
class LCD1602: LCD_RS = 14 LCD_E = 15 LCD_D4 = 17 LCD_D5 = 18 LCD_D6 = 27 LCD_D7 = 22
LCD_WIDTH = 16 LCD_CHR = True LCD_CMD = False
LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0
E_PULSE = 0.0005 E_DELAY = 0.0005
def __init__(self): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self.LCD_E, GPIO.OUT) GPIO.setup(self.LCD_RS, GPIO.OUT) GPIO.setup(self.LCD_D4, GPIO.OUT) GPIO.setup(self.LCD_D5, GPIO.OUT) GPIO.setup(self.LCD_D6, GPIO.OUT) GPIO.setup(self.LCD_D7, GPIO.OUT) self.lcd_init()
def lcd_init(self): self.lcd_byte(0x33, self.LCD_CMD) self.lcd_byte(0x32, self.LCD_CMD) self.lcd_byte(0x06, self.LCD_CMD) self.lcd_byte(0x0C, self.LCD_CMD) self.lcd_byte(0x28, self.LCD_CMD) self.lcd_byte(0x01, self.LCD_CMD) time.sleep(self.E_DELAY)
def lcd_byte(self, bits, mode): GPIO.output(self.LCD_RS, mode) GPIO.output(self.LCD_D4, False) GPIO.output(self.LCD_D5, False) GPIO.output(self.LCD_D6, False) GPIO.output(self.LCD_D7, False) if bits & 0x10 == 0x10: GPIO.output(self.LCD_D4, True) if bits & 0x20 == 0x20: GPIO.output(self.LCD_D5, True) if bits & 0x40 == 0x40: GPIO.output(self.LCD_D6, True) if bits & 0x80 == 0x80: GPIO.output(self.LCD_D7, True)
self.lcd_toggle_enable()
GPIO.output(self.LCD_D4, False) GPIO.output(self.LCD_D5, False) GPIO.output(self.LCD_D6, False) GPIO.output(self.LCD_D7, False) if bits & 0x01 == 0x01: GPIO.output(self.LCD_D4, True) if bits & 0x02 == 0x02: GPIO.output(self.LCD_D5, True) if bits & 0x04 == 0x04: GPIO.output(self.LCD_D6, True) if bits & 0x08 == 0x08: GPIO.output(self.LCD_D7, True)
self.lcd_toggle_enable()
def lcd_toggle_enable(self): time.sleep(self.E_DELAY) GPIO.output(self.LCD_E, True) time.sleep(self.E_PULSE) GPIO.output(self.LCD_E, False) time.sleep(self.E_DELAY)
def lcd_string(self, message, line): message = message.ljust(self.LCD_WIDTH, " ") self.lcd_byte(line, self.LCD_CMD) for i in range(self.LCD_WIDTH): self.lcd_byte(ord(message[i]), self.LCD_CHR)
if __name__ == '__main__': a = LCD1602() while True: a.lcd_string(''.join(sample(string.ascii_letters, k=8)), a.LCD_LINE_1) a.lcd_string(''.join(sample(string.ascii_letters, k=8)), a.LCD_LINE_2) time.sleep(3)
|