0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ラズパイ】LCDディスプレイに時計を表示する

Last updated at Posted at 2025-04-18

ラズパイにLCDディスプレイを接続し、時計表示させる。
ディスプレイはラズパイ購入時に付いてきたLCDを使う。

環境は
Raspberry Pi4 ModelB + Ubuntu 22.04.2

以下参考に…

こんな感じで表示される
IMG_9063.jpeg

物理接続は以下参照

moduleインストール

# apt install i2c-tools
# apt-get install python3-smbus               #Python言語でI2Cバスを操作するためのライブラリ
# wget http://osoyoo.com/driver/i2clcda.py

I2Cアドレスの確認

# i2cdetect -y 1
timedisplay.py
import smbus
import time
import datetime

# I2C通信設定
I2C_ADR = 0x27 # I2Cアドレス
LCD_WDT = 16 # 文字数上限
LCD_BKL = 0x08 # バックライトON
LIST = [0x33, 0x32, 0x06, 0x0C, 0x28, 0x01]

bus = smbus.SMBus(1) # 接続バスの番号指定

def initialize():
    send_data(LCD_BKL, 0)  # バックライトON
    for i in LIST:
        send_data(i, 0)
        time.sleep(0.0005)

def send_data(bits, mode):
    upbits = mode | (bits & 0xF0) | LCD_BKL
    lwbits = mode | ((bits<<4) & 0xF0) | LCD_BKL
    bus.write_byte(I2C_ADR, upbits)
    bus.write_byte(I2C_ADR, (upbits | 0b00000100))
    bus.write_byte(I2C_ADR, (upbits & ~0b00000100))
    bus.write_byte(I2C_ADR, lwbits)
    bus.write_byte(I2C_ADR, (lwbits | 0b00000100))
    bus.write_byte(I2C_ADR, (lwbits & ~0b00000100))

def set_display(message, line):
    message = message.center(LCD_WDT," ") # メッセージ表示 中央揃え
    send_data(line, 0)
    for i in range(LCD_WDT):
        send_data(ord(message[i]), 1)

# メイン処理
def main():
    initialize() # 初期化
    while True:
        # 現在時刻取得
        current_time = datetime.datetime.now() # 現在時刻取得
        set_display(time.strftime("%Y/%m/%d (%a)", time.gmtime()), 0x80) # 1行目:年月日(曜日)表示
        set_display(current_time.strftime("%H:%M:%S"), 0xC0) # 2行目:現在時間表示
        time.sleep(0.1)

try:
    # mainを実行
    main()
except KeyboardInterrupt:
    # 例外処理(Ctrl+C)
    pass
finally:
    # 終了時に行う処理
    send_data(LCD_BKL)

いじょう

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?