# Raspberry Pi Pico W + AQM1602 I2C LCD
# SDA: GP16, SCL: GP17, I2C0 使用
from machine import Pin, I2C
import time
# I2C設定
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=100000)
# LCD I2C アドレス
LCD_ADDR = 0x3E
# 送信用バッファ
buf = bytearray(2)
# -----------------------------------------------------
# LCDにコマンド送信
# -----------------------------------------------------
def lcd_write_cmd(cmd):
buf[0] = 0x00 # Control byte: CO=0, RS=0
buf[1] = cmd
try:
i2c.writeto(LCD_ADDR, buf)
except OSError as e:
print("I2C Write Error (cmd):", e)
# -----------------------------------------------------
# LCDにデータ送信(1文字)
# -----------------------------------------------------
def lcd_write_data(data):
buf[0] = 0x40 # Control byte: CO=0, RS=1
buf[1] = data
try:
i2c.writeto(LCD_ADDR, buf)
except OSError as e:
print("I2C Write Error (data):", e)
# -----------------------------------------------------
# LCD初期化
# -----------------------------------------------------
def lcd_init():
init_cmds = [0x38, 0x39, 0x14, 0x73, 0x56, 0x6C, 0x38, 0x0C, 0x01]
time.sleep_ms(40)
for cmd in init_cmds:
lcd_write_cmd(cmd)
time.sleep_ms(1)
time.sleep_ms(2)
# -----------------------------------------------------
# カーソル位置設定 (x:0-15, y:0-1)
# -----------------------------------------------------
def lcd_set_cursor(x, y):
addr = 0x80 + x if y == 0 else 0xC0 + x
lcd_write_cmd(addr)
# -----------------------------------------------------
# 表示クリア
# -----------------------------------------------------
def lcd_clear():
lcd_write_cmd(0x01)
time.sleep_ms(2)
# -----------------------------------------------------
# カーソルをホームに戻す
# -----------------------------------------------------
def lcd_home():
lcd_write_cmd(0x02)
time.sleep_ms(2)
# -----------------------------------------------------
# 文字列を表示
# -----------------------------------------------------
def lcd_print(text):
for c in text:
lcd_write_data(ord(c))
# -----------------------------------------------------
# メイン処理
# -----------------------------------------------------
try:
# 接続されている I2C デバイスの一覧を表示(デバッグ用)
devices = i2c.scan()
if LCD_ADDR not in devices:
print("ERROR: LCD (0x3E) not found on I2C bus.")
else:
lcd_init()
lcd_clear()
lcd_home()
lcd_print("Hello World!")
lcd_set_cursor(0, 1)
lcd_print("RaspberryPiPicoW")
except Exception as e:
print("Unexpected error:", e)
0 件のコメント:
コメントを投稿