arduino uno 製作時鐘(RTC 1307(i2c) and LCD(i2c))

 1.利用RTC 1307(i2c) and LCD(i2c)製作時鐘首先需要各個library

        LCD (I2C)        LiquidCrystal I2C

        RTC 1307         DS1307RTC 及 Time


2. 接線圖

    


3. 寫入程式(可利用chatGPT生成)

#include <Wire.h> // 引入 I2C 库
#include <LiquidCrystal_I2C.h> // 引入 I2C LCD 库
#include <DS1307RTC.h> // 引入 DS1307 RTC 库

LiquidCrystal_I2C lcd(0x27, 16, 2); // 使用 I2C 地址 0x27, 16x2 字符的 LCD

void setup() {
  Serial.begin(9600); // 初始化串口通信
  lcd.init(); // 初始化 LCD
  lcd.backlight(); // 打开背光
  setSyncProvider(RTC.get); // 同步 RTC
  if(timeStatus() != timeSet) {
    Serial.println("Unable to sync with the RTC");
  } else {
    Serial.println("RTC has set the system time");
  }
}

void loop() {
  tmElements_t tm; // 定义時間元素結構體
  if (RTC.read(tm)) { // 讀取時間
    lcd.setCursor(0, 0); // 设置游標位置
    lcd.print("Time: ");
    print2digits(tm.Hour); // 輸出小時
    lcd.print(":");
    print2digits(tm.Minute); // 輸出分鐘
    lcd.print(":");
    print2digits(tm.Second); // 輸出秒
    lcd.setCursor(0, 1); // 移動到第二行
    lcd.print("Date: ");
    lcd.print(tm.Day); // 輸出日期
    lcd.print("/");
    lcd.print(tm.Month); // 輸出月份
    lcd.print("/");
    lcd.print(tmYearToCalendar(tm.Year)); // 輸出年份
  } else {
    if (RTC.chipPresent()) {
      Serial.println("The DS1307 is stopped.  Please run the SetTime");
      Serial.println("example to initialize the time and begin running.");
      Serial.println();
    } else {
      Serial.println("DS1307 read error!  Please check the circuitry.");
      Serial.println();
    }
    delay(9000); // 等待9秒後再重新讀取時間
  }
  delay(1000); // 每隔1秒更新時間
}

void print2digits(int number) { // 打印時間,如果小於 10,補零
  if (number >= 0 && number < 10) {
    lcd.print("0"); // 補零
  }
  lcd.print(number); // 打印時間
}

0 留言

張貼留言

Post a Comment (0)

較新的 較舊