# ตัวอย่าง การเขียนโปรแกรม Micropython ควบคุมการทำงาน ESP32
# LAB14 DS1307 RTC LCD I2C
# นายพิชญะ ภูปุย อังคาร 6 สิงหาคม 2567
from machine import Pin, I2C
import utime
from ds1307 import DS1307
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
print("LAB14 DS1307 RTC LCD I2C - Viboon Kumpanavarawan")
# กำหนดขา I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# กำหนดที่อยู่ของ LCD และ DS1307
LCD_ADDR = 0x27
DS1307_ADDR = 0x68
# สร้างออบเจ็กต์สำหรับ LCD และ DS1307
lcd = I2cLcd(i2c, LCD_ADDR, 2, 16)
rtc = DS1307(i2c)
# ฟังก์ชันแสดงเวลาบน LCD
def display_time():
# อ่านเวลาจาก DS1307
(year, month, day, weekday, hour, minute, second, _) = rtc.datetime()
# แสดงวันที่และเวลาในรูปแบบที่ต้องการ
date_str = "{:02d}/{:02d}/{:04d}".format(day, month, year)
time_str = "{:02d}:{:02d}:{:02d}".format(hour, minute, second)
lcd.clear()
lcd.putstr(date_str)
lcd.move_to(0, 1)
lcd.putstr(time_str)
# ตั้งเวลาครั้งแรก (ถ้าต้องการ)
# rtc.datetime((ปี, เดือน, วัน, วันในสัปดาห์, ชั่วโมง, นาที, วินาที, subsecond))
# rtc.datetime((2024, 6, 26, 3, 12, 0, 0, 0))
# Loop แสดงเวลา
while True:
display_time()
utime.sleep(1)