如头图所示,如果绑两根绳,也可以称之为手表。
本例子使用的硬件如下:
- tm1637:4位数码管1块
- NodeMCU:esp8266开发板一枚
- microUSB:电源线1条
- 杜邦线:4根
需要的软件,就是arduino了。在arduino的首选项加入如下:
https://arduino.esp8266.com/stable/package_esp8266com_index.json
以获得对esp8266的支持。
打开开发板管理器,搜索esp8266并安装。
安装后,在开发板里就可以选择NodeMCU1.0(ESP-12E Module)了。
然后打开库管理器,搜索tm1637(4位数码管驱动),按照下图所示,点击安装。
然后,继续安装wifimanager
wifimanager的作用是,用来配网。
硬件连接
tm1637的CLK对应nodeMCU的D0 (gpio 16)
tm1637的DIO对应nodeMCU的D4 (gpio 2)
之后,源码在这里:
#include <ESP8266WiFi.h>
#include <time.h>
#include <TM1637Display.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
// NTP Config
int timezone = 8 * 3600;
int dst = 0;
// Module connection pins (Digital Pins)
#define CLK D0 //gpio 16
#define DIO D4 //gpio 2
#define TEST_DELAY 2000
const uint8_t SEG_CONN[] = {
SEG_A | SEG_D | SEG_E | SEG_F, // C
SEG_C | SEG_D | SEG_E | SEG_G, // o
SEG_C | SEG_E | SEG_G, // n
SEG_C | SEG_E | SEG_G // n
};
const uint8_t SEG_PASS[] = {
SEG_A | SEG_B | SEG_E | SEG_F | SEG_G, // P
SEG_A | SEG_B | SEG_C | SEG_E | SEG_F | SEG_G, // A
SEG_A | SEG_C | SEG_D | SEG_F | SEG_G, // S
SEG_A | SEG_C | SEG_D | SEG_F | SEG_G // S
};
const uint8_t SEG_FAIL[] = {
SEG_A | SEG_E | SEG_F | SEG_G, // F
SEG_A | SEG_B | SEG_C | SEG_E | SEG_F | SEG_G, // A
SEG_F | SEG_G, // I
SEG_D | SEG_F | SEG_G // L
};
const uint8_t SEG_DONE[] = {
SEG_B | SEG_C | SEG_D | SEG_E | SEG_G, // d
SEG_A | SEG_B | SEG_C | SEG_D | SEG_E | SEG_F, // O
SEG_C | SEG_E | SEG_G, // n
SEG_A | SEG_D | SEG_E | SEG_F | SEG_G // E
};
TM1637Display display(CLK, DIO);
String lastTimeStr;
unsigned long lastShowColon = 0;
bool showColon = false;
bool hourcheck=false;
void setup()
{
display.setBrightness(0x01);// 0x01~0x0e
WiFiManager wifiManager;
wifiManager.autoConnect("ClockAP");
display.setSegments(SEG_CONN);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
display.setSegments(SEG_PASS);
delay(1000);
// Get time from NTP server
configTime(timezone, dst, "ntp.ku.ac.th", "fw.eng.ku.ac.th", "ilm.live.rmutt.ac.th");
while (!time(nullptr))
{
delay(500);
}
display.setSegments(SEG_DONE);
delay(1000);
}
void loop()
{
uint8_t hour;
bool hourcheck;
time_t now = time(nullptr);
struct tm* p_tm = localtime(&now);
hour=p_tm->tm_hour;
if(hour<1)
{
hourcheck=true;
}
else
{
hourcheck=false;
}
if((p_tm->tm_sec % 2) == 0)
{
display.showNumberDecEx(hour*100+p_tm->tm_min,0x40 ,hourcheck);
}
else
{
display.showNumberDecEx(hour*100+p_tm->tm_min,0x00, hourcheck );
}
}
烧录后,重新上电,你会搜索到一个名为的ClockAP的热点。该热点无密码,直接连接就好。连接后,输入192.168.4.1,会得到如下界面:
点击config wifi,输入你路由器的热点和密码,进行配置。
之后点击save按钮保存。
这个时候,会出现如下界面。
因为esp8266已经去连接你设置的热点了,所以它自己的热点就不开放了。这个时候,你的电子时钟,应该已经显示时间了(如果你硬件没问题并且连接都正确)。
最后,源代码在:
hello-esp8266/arduino-tm1637-clockgithub.com如果你懒得使用arduino编译,可以直接使用烧录工具烧录二进制,直接在release下载二进制就好了。
https://github.com/hello-esp8266/arduino-tm1637-clock/releasesgithub.com如有任何问题,欢迎留言。