はじめに
こんにちは。
この記事は Kojirock1一人 Advent Calendar 2019の8日目の記事です。
今回も、事前に買った初心者キットに入っていたものを使いながら色々遊んでみます。
今回はI2C LCDというやつを使ってみます。
こちらは、比較的色々と参考記事があったので以下のサイトを参考に再現してみます。
やってみた
早速つなげてみました。
コードは参考サイトのものをコピーさせていただき、少し修正を行いました。
バスと、アドレスは 以下のコードで事前に調べています。
コマンド
$ sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- 27 -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- --
スクリプト
# -*- coding: utf-8 -*- #!/usr/bin/python from time import sleep from time import gmtime, strftime import datetime import smbus #initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() I2C_ADDR = 0x27 LCD_WIDTH = 16 LCD_CHR = 1 LCD_CMD = 0 LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0 LCD_BACKLIGHT = 0x08 ENABLE = 0b00000100 E_PULSE = 0.0005 E_DELAY = 0.0005 bus = smbus.SMBus(1) # Rev 2 Pi uses 1 def lcd_init(): # Initialise display lcd_byte(0x33,LCD_CMD) # 110011 Initialise lcd_byte(0x32,LCD_CMD) # 110010 Initialise lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size lcd_byte(0x01,LCD_CMD) # 000001 Clear display sleep(E_DELAY) def lcd_byte(bits, mode): bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT # High bits bus.write_byte(I2C_ADDR, bits_high) lcd_toggle_enable(bits_high) # Low bits bus.write_byte(I2C_ADDR, bits_low) lcd_toggle_enable(bits_low) def lcd_toggle_enable(bits): sleep(E_DELAY) bus.write_byte(I2C_ADDR, (bits | ENABLE)) sleep(E_PULSE) bus.write_byte(I2C_ADDR,(bits & ~ENABLE)) sleep(E_DELAY) def lcd_string(message,line): # Send string to display message = message.ljust(LCD_WIDTH," ") lcd_byte(line, LCD_CMD) for i in range(LCD_WIDTH): lcd_byte(ord(message[i]),LCD_CHR) def main(): lcd_init() while True: local_time = datetime.datetime.now() lcd_string("Current Time is", LCD_LINE_1) lcd_string(local_time.strftime("%H:%M"), LCD_LINE_2) sleep(1) try: main() except KeyboardInterrupt: pass finally: LCD_BACKLIGHT = 0x00 lcd_byte(0x01, LCD_CMD) GPIO.cleanup()
実際に動かしてみました!
表示されました!
終わりに
今回も参考サイトがあったので助かりましたw
こういう表示系はテンションが上ります。
日本語は表示できないのかな?
もうちょい調べてみます。
現場からは以上です。