【ESP8266+TM1650时钟数码管+DS3231模块】制作网络时钟

【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 interface
  Wire.begin();
  d.init();
  d.displayOn();
  d.setBrightnessGradually(5);
  RTC.begin();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {  // 连接wifi
    ii++;
    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);
}


时钟效果

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值