构思: 采用esp8266芯片 获取网络上的时间API接口 获取时间
元器件清单:
四位数码管显示模块
D1 UNO R3开发板
蜂鸣器
触摸按钮
#include <TM1637.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#define ssid "A"
#define psd "11111111"
#define api1 "http://quan.suning.com/getSysTime.do"
#define CLK D5 //显示模块
#define DIO D4
#define BT D3 //按钮
#define Call D6 //蜂鸣器
String getTime;//定义时间数据
int timeShi1;
int timeShi2;
int timeFen1;
int timeFen2;
int timeLight = 1;
TM1637 tm1637(CLK, DIO);//初始化显示模块
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, psd);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(WiFi.localIP());
//等待wifi(上)
tm1637.init();
tm1637.set(1);
tm1637.point(POINT_ON);
//初始化 set设置亮度 point是模块上的冒号
pinMode(BT, INPUT);
pinMode(Call, OUTPUT);
//设置按钮 BT
//设置蜂鸣器 Call
}
void loop() {
delay(500);//每0.5秒重复一次
digitalWrite(Call, LOW);//初始化蜂鸣器
setTime();//刷新显示模块上的时间
int btState = digitalRead(BT);//获取按钮的值
if (btState == HIGH) {
changeLight();//修改亮度
}
callWhile();//判断是否在整点
/*
每当整点的时候 让蜂鸣器响
而每次loop 刷新的时候 会等待0.5秒 从而达到响多次 与响的时间控制
*/
}
void callWhile() {//判断是否整点并让蜂鸣器响
int second1 = getOther(getTime, 58);
int second2 = getOther(getTime, 59);
if ((timeShi1 == 0 && timeShi2 <= 9) || (timeShi1 == 2 && timeShi2 > 1) ) {
return;
} else if (timeFen1 == 0 && timeFen2 == 0 && second1 == 0 && second2 < 2) {
digitalWrite(Call, HIGH);
}
}
}
void changeLight() {//修改亮度
if (timeLight == 6) {
timeLight = 1;
}
timeLight += 1;
tm1637.set(timeLight);
setTime();
}
void setTime() {//设置显示模块上的时间
getTime = http_post();
timeShi1 = getOther(getTime, 54);
timeShi2 = getOther(getTime, 55);
timeFen1 = getOther(getTime, 56);
timeFen2 = getOther(getTime, 57);
tm1637.display(0, timeShi1);
tm1637.display(1, timeShi2);
tm1637.display(2, timeFen1);
tm1637.display(3, timeFen2);
Serial.print(timeShi1);
Serial.print(timeShi2);
Serial.print(timeFen1);
Serial.println(timeFen2);
}
String http_post() {//网络请求api时间数据
WiFiClient client;
HTTPClient http;
http.begin(api1);
int httpCode = http.POST(" ");
if (httpCode == HTTP_CODE_OK) {
return http.getString();
}
http.end();
}
/*
{"sysTime2":"2021-10-19 15:23:55","sysTime1":"20211019152355"}
下标
年:46——49
月:50——51
日:52 53
时:54 55
分:56 57
秒:58 59
*/
int getOther(String b2, int index) {//根据上面 对获取的api进行数据拆分
return b2.charAt(index) - 48;
}