【ESP8266+TM1650时钟数码管+DS3231模块】制作网络时钟
- 所需元器件
- 接线方式
- 代码
所需元器件
- ESP8266 NodeMCU——开发板
- TM1650时钟数码管——显示时钟
- DS3231模块——网络对时
接线方式
- TM1650
SCL—>D1
SDA—>D2 - DS3231
SCL—>D1
SDA—>D2
代码
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Wire.h>
#include <TM1650.h>
#include <SPI.h> // not used here, but needed to prevent a RTClib compile error
#include <RTClib.h>
#include <UnixTime.h>const char *ssid = "***";
const char *password = "***";DS3231 RTC;
TM1650 d;
UnixTime stamp(8); // 定义东八区时间WiFiUDP ntpUDP;
// NTPClient timeClient(ntpUDP, "cn.ntp.org.cn", 28800);
NTPClient timeClient(ntpUDP, "cn.ntp.org.cn");int h, m, s = 0;
int ii = 0;String intToStr(int x) {if (x < 10) {return "0" + String(x);}return String(x);
}void setup() {Serial.begin(74880);// Start the I2C interfaceWire.begin();d.init();d.displayOn();d.setBrightnessGradually(5);RTC.begin();WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) { // 连接wifiii++;Serial.print(".");if (ii % 2 == 0) {d.setDot(1, true);} else {d.setDot(1, false);}delay(500);}timeClient.begin();d.displayString("8888");
}void loop() {// 0点更新时间if (h + m + s == 0) {timeClient.update();Serial.println("开始同步NTP时间");stamp.getDateTime(timeClient.getEpochTime());RTC.adjust(DateTime(stamp.year, stamp.month, stamp.day, stamp.hour, timeClient.getMinutes(), timeClient.getSeconds()));Serial.println("同步NTP时间完成");}// 以下获取RTC时间DateTime now = RTC.now();h = now.hour();m = now.minute();s = now.second();// 以下格式化HH:MM并显示String hhmm = intToStr(h) + intToStr(m);char charBuf[10];hhmm.toCharArray(charBuf, 10);d.displayString(charBuf);// 以下显示秒的跳动d.setDot(1, true);delay(500);d.setDot(1, false);delay(500);
}
时钟效果