arduino 万年历代码
时间: 2023-09-09 18:13:13 浏览: 532
以下是一个简单的Arduino万年历代码示例,可以显示当前日期和时间,支持闰年和平年的计算:
```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C LCD
byte daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // days in each month
String daysOfWeek[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // days of the week
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Calendar");
}
void loop() {
int year = 2021; // current year
int month = 1; // current month
int day = 1; // current day
int hour = 0; // current hour
int minute = 0; // current minute
int second = 0; // current second
int dayOfWeek = 0; // current day of week
int daysInYear = 365; // days in a year
// check for leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
daysInYear = 366;
}
// calculate day of the year
int dayOfYear = 0;
for (int i = 0; i < month - 1; i++) {
dayOfYear += daysInMonth[i];
}
dayOfYear += day;
// calculate day of the week
dayOfWeek = (dayOfYear + (year - 1) * daysInYear + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400) % 7;
// print date and time
lcd.setCursor(0, 1);
lcd.print(daysOfWeek[dayOfWeek]);
lcd.print(" ");
lcd.print(month);
lcd.print("/");
lcd.print(day);
lcd.print("/");
lcd.print(year);
lcd.print(" ");
lcd.print(hour);
lcd.print(":");
lcd.print(minute);
lcd.print(":");
lcd.print(second);
delay(1000);
}
```
此代码使用I2C LCD显示当前日期和时间,可以根据需要进行修改。
阅读全文