# coding: utf-8 @lcd_address = 0x3e @rtc_address = 0x32 def lcd_cmd(i2c, cmd) i2c.write(@lcd_address, [0x00, cmd]) end def lcd_data(i2c, data) i2c.write(@lcd_address, [0x40, data]) end def lcd_clear(i2c) lcd_cmd(i2c, 0x01) sleep 0.1 end def lcd_home0(i2c) lcd_cmd(i2c, 0x02) sleep 0.1 end def lcd_home1(i2c) lcd_cmd(i2c, 0x40|0x80) sleep 0.1 end def lcd_cursor(i2c, x, y) pos = (x + y * 0x40) | 0x80 lcd_cmd(i2c, pos) sleep 0.1 end def lcd_init(i2c) sleep 0.2 [0x38, 0x39, 0x14, 0x70, 0x56, 0x6c].each do |cmd| lcd_cmd(i2c, cmd) end sleep(0.3) [0x38, 0x0c, 0x01].each do |cmd| lcd_cmd(i2c, cmd) end sleep(0.1) end def lcd_print(i2c, data) data.length.times do |n| lcd_data(i2c, data[n].ord) end end def rtc2_init(i2c) i2c.write(0x32, [0xE0, 0x00, 0x00]) sleep 0.1 end def rtc2_set(i2c) i2c.write(@rtc_address, [0x00, 0x50, 0x59, 0x23|0x80, 0x01, 0x31, 0x10, 0x20]) sleep 0.1 i2c.write(@rtc_address, [0xF0, 0x00]) sleep 0.1 end def rtc2_get(i2c, tt) buf = i2c.read_integer(@rtc_address, 8) # 8 バイト分読み込み tt['year'] = buf[7] tt['mon'] = buf[6] tt['mday'] = buf[5] tt['hour'] = buf[3] & 0x3f tt['min'] = buf[2] tt['sec'] = buf[1] end #I2C 初期化 i2c = I2C.new(22, 21) # LCD 初期化 lcd_init(i2c) # LCD に "Hello World" 表示 lcd_cursor(i2c, 1, 0) lcd_print(i2c, "Hello!") lcd_home1(i2c) lcd_print(i2c, "from ESP") sleep(5) # RTC 初期化. 時刻設定 rtc2_init(i2c) rtc2_set(i2c) while true # 時刻表示 tt = {} #ハッシュ rtc2_get(i2c, tt) time0 = sprintf("%02x-%02x-%02x", tt['year'], tt['mon'], tt['mday']) time1 = sprintf("%02x:%02x:%02x", tt['hour'], tt['min'], tt['sec']) lcd_home0(i2c) lcd_print(i2c, time0) puts time0 lcd_home1(i2c) lcd_print(i2c, time1) puts time1 sleep(1) end class RTC2 end class LCD 3 4 ADDRESS = 0x3e 5 6 def initialize(i2c) 7 @i2c = i2c 8 end 9 10 def cmd(cmd) 11 @i2c.write(LCD::ADDRESS, [0x00, cmd]) 12 end 13 14 def data(data) 15 @i2c.write(LCD::ADDRESS, [0x40, data]) 16 end 17 18 def clear() 19 cmd(0x01) 20 sleep 0.1 21 end 22 23 def home0() 24 cmd(0x02) 25 sleep 0.1 26 end 27 28 def home1() 29 cmd(0x40|0x80) 30 sleep 0.1 31 end 32 33 def cursor(x, y) 34 pos = (x + y * 0x40) | 0x80 35 cmd(pos) 36 sleep 0.1 37 end 38 39 def init() 40 sleep 0.2 41 [0x38, 0x39, 0x14, 0x70, 0x56, 0x6c].each do |cmd| 42 cmd(cmd) 43 end 44 sleep(0.3) 45 [0x38, 0x0c, 0x01].each do |cmd| 46 cmd(cmd) 47 end 48 sleep(0.1) 49 end 50 51 def print(data) 52 data.length.times do |n| 53 data(data[n].ord) 54 end 55 end 56 57 end