当前位置:   article > 正文

基于ESP8266的太空人智能时钟_esp8266太空人天气时钟

esp8266太空人天气时钟

目录

一、实例简介

二、原理图与PCB制作 

三、全部代码

 四、效果演示

一、实例简介

   常常没有时间观念的我,渴望桌面有一个时间表来提醒我什么时间点该做什么事,(淘宝普遍都很贵)于是就想起本学期学的TFT彩屏,通过ESP8266WIFI来进行联网以获取网上的数据。比如(天气城市代码,NTP同步阿里云服务器获取时间)

二、原理图与PCB制作

三、全部代码

我安装的都是这些库,可以运行成功。(如果安装不成功就用降级大法)

里面需要修改里面的ssid和password为你的WIFI名称和密码即可

  1. wifiMulti.addAP("ssid", "password"); // 修改里面的ssid和password为你的WIFI名称和密码即可
  2. wifiMulti.addAP("ssid2", "password2"); //这里可以设置多个常用wifi,会自动连接信号最强的
  3. wifiMulti.addAP("ssid3", "password3");

 以下是全部代码:

  1. #include <ArduinoJson.h>
  2. #include <ESP8266WiFiMulti.h>
  3. #include <TimeLib.h>
  4. #include <ESP8266WiFi.h>
  5. #include <WiFiUdp.h>
  6. #include <ESP8266HTTPClient.h>
  7. ESP8266WiFiMulti wifiMulti;
  8. #include "font/ZdyLwFont_20.h"
  9. #include "font/FxLED_32.h"
  10. #include "img/pangzi/i0.h"
  11. #include "img/pangzi/i1.h"
  12. #include "img/pangzi/i2.h"
  13. #include "img/pangzi/i3.h"
  14. #include "img/pangzi/i4.h"
  15. #include "img/pangzi/i5.h"
  16. #include "img/pangzi/i6.h"
  17. #include "img/pangzi/i7.h"
  18. #include "img/pangzi/i8.h"
  19. #include "img/pangzi/i9.h"
  20. #include "img/temperature.h"
  21. #include "img/humidity.h"
  22. #include "img/watch_top.h"
  23. #include "img/watch_bottom.h"
  24. #include <TFT_eSPI.h>
  25. #include <SPI.h>
  26. TFT_eSPI tft = TFT_eSPI(); // 引脚请自行配置tft_espi库中的 User_Setup.h文件
  27. TFT_eSprite clk = TFT_eSprite(&tft);
  28. #include <TJpg_Decoder.h>
  29. uint32_t targetTime = 0;
  30. byte omm = 99;
  31. boolean initial = 1;
  32. byte xcolon = 0;
  33. unsigned int colour = 0;
  34. uint16_t bgColor = 0xFFFF;
  35. String cityCode = "101280601"; //天气城市代码 深圳代码https://blog.csdn.net/iechenyb/article/details/78652461
  36. //NTP服务器
  37. static const char ntpServerName[] = "ntp6.aliyun.com";
  38. const int timeZone = 8; //东八区
  39. WiFiUDP Udp;
  40. unsigned int localPort = 8000;
  41. time_t getNtpTime();
  42. void digitalClockDisplay();
  43. void printDigits(int digits);
  44. String num2str(int digits);
  45. void sendNTPpacket(IPAddress &address);
  46. bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap)
  47. {
  48. if ( y >= tft.height() ) return 0;
  49. tft.pushImage(x, y, w, h, bitmap);
  50. // Return 1 to decode next block
  51. return 1;
  52. }
  53. byte loadNum = 6;
  54. void loading(byte delayTime){
  55. clk.setColorDepth(8);
  56. clk.createSprite(200, 50);
  57. clk.fillSprite(0x0000);
  58. clk.drawRoundRect(0,0,200,16,8,0xFFFF);
  59. clk.fillRoundRect(3,3,loadNum,10,5,0xFFFF);
  60. clk.setTextDatum(CC_DATUM);
  61. clk.setTextColor(TFT_GREEN, 0x0000);
  62. clk.drawString("Connecting to WiFi",100,40,2);
  63. clk.pushSprite(20,110);
  64. clk.deleteSprite();
  65. loadNum += 1;
  66. if(loadNum>=194){
  67. loadNum = 194;
  68. }
  69. delay(delayTime);
  70. }
  71. void setup()
  72. {
  73. Serial.begin(9600);
  74. wifiMulti.addAP("ssid", "password"); // 修改里面的ssid和password为你的WIFI名称和密码即可
  75. wifiMulti.addAP("ssid2", "password2"); //这里可以设置多个常用wifi,会自动连接信号最强的
  76. wifiMulti.addAP("ssid3", "password3");
  77. tft.init();
  78. tft.setRotation(3); //旋转屏幕 参数为:0, 1, 2, 3 分别代表 0°,90°,180°,270°,可设置4为镜像。
  79. tft.fillScreen(0x0000);
  80. tft.setTextColor(TFT_BLACK, bgColor);
  81. targetTime = millis() + 1000;
  82. Serial.print("正在连接WIFI ");
  83. Serial.println(WiFi.SSID());
  84. while (wifiMulti.run() != WL_CONNECTED) {
  85. for(byte n=0;n<10;n++){ //500毫秒检测一次状态
  86. loading(50);
  87. }
  88. }
  89. while(loadNum < 194){ //让动画走完
  90. loading(1);
  91. }
  92. Serial.print("本地IP: ");
  93. Serial.println(WiFi.localIP());
  94. //Serial.println("启动UDP");
  95. Udp.begin(localPort);
  96. //Serial.print("端口号: ");
  97. //Serial.println(Udp.localPort());
  98. //Serial.println("等待同步...");
  99. setSyncProvider(getNtpTime);
  100. setSyncInterval(300);
  101. TJpgDec.setJpgScale(1);
  102. TJpgDec.setSwapBytes(true);
  103. TJpgDec.setCallback(tft_output);
  104. TJpgDec.drawJpg(0,0,watchtop, sizeof(watchtop));
  105. TJpgDec.drawJpg(0,220,watchbottom, sizeof(watchbottom));
  106. //绘制一个视口
  107. tft.setViewport(0, 20, 240, 200);
  108. tft.fillScreen(0x0000);
  109. tft.fillRoundRect(0,0,240,200,5,bgColor);//实心圆角矩形
  110. //tft.resetViewport();
  111. //绘制线框
  112. tft.drawFastHLine(0,34,240,TFT_BLACK);
  113. tft.drawFastVLine(150,0,34,TFT_BLACK);
  114. tft.drawFastHLine(0,166,240,TFT_BLACK);
  115. tft.drawFastVLine(60,166,34,TFT_BLACK);
  116. tft.drawFastVLine(160,166,34,TFT_BLACK);
  117. getCityCode(); //获取城市代码
  118. TJpgDec.drawJpg(161,171,temperature, sizeof(temperature)); //温度图标
  119. TJpgDec.drawJpg(159,130,humidity, sizeof(humidity)); //湿度图标
  120. }
  121. time_t prevDisplay = 0; // 显示时间
  122. unsigned long weaterTime = 0;
  123. void loop(){
  124. if (now() != prevDisplay) {
  125. prevDisplay = now();
  126. digitalClockDisplay();
  127. }
  128. if(millis() - weaterTime > 300000){ //5分钟更新一次天气
  129. weaterTime = millis();
  130. getCityWeater();
  131. }
  132. scrollBanner();
  133. imgAnim();
  134. }
  135. // 发送HTTP请求并且将服务器响应通过串口输出
  136. void getCityCode(){
  137. String URL = "http://wgeo.weather.com.cn/ip/?_="+String(now());
  138. WiFiClient client;
  139. //创建 HTTPClient 对象
  140. HTTPClient httpClient;
  141. httpClient.begin(client,URL);
  142. //设置请求头中的User-Agent
  143. httpClient.setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
  144. httpClient.addHeader("Referer", "http://www.weather.com.cn/");
  145. //启动连接并发送HTTP请求
  146. int httpCode = httpClient.GET();
  147. Serial.print("Send GET request to URL: ");
  148. Serial.println(URL);
  149. //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
  150. if (httpCode == HTTP_CODE_OK) {
  151. String str = httpClient.getString();
  152. int aa = str.indexOf("id=");
  153. if(aa>-1){
  154. //cityCode = str.substring(aa+4,aa+4+9).toInt();
  155. cityCode = str.substring(aa+4,aa+4+9);
  156. Serial.println(cityCode);
  157. getCityWeater();
  158. }else{
  159. Serial.println("获取城市代码失败");
  160. }
  161. } else {
  162. Serial.println("请求城市代码错误:");
  163. Serial.println(httpCode);
  164. }
  165. //关闭ESP8266与服务器连接
  166. httpClient.end();
  167. }
  168. // 获取城市天气
  169. void getCityWeater(){
  170. String URL = "http://d1.weather.com.cn/weather_index/" + cityCode + ".html?_="+String(now());
  171. WiFiClient client; //创建 HTTPClient 对象
  172. HTTPClient httpClient;
  173. httpClient.begin(client,URL);
  174. //设置请求头中的User-Agent
  175. httpClient.setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
  176. httpClient.addHeader("Referer", "http://www.weather.com.cn/");
  177. //启动连接并发送HTTP请求
  178. int httpCode = httpClient.GET();
  179. Serial.println("正在获取天气数据");
  180. Serial.println(URL);
  181. //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
  182. if (httpCode == HTTP_CODE_OK) {
  183. String str = httpClient.getString();
  184. int indexStart = str.indexOf("weatherinfo\":");
  185. int indexEnd = str.indexOf("};var alarmDZ");
  186. String jsonCityDZ = str.substring(indexStart+13,indexEnd);
  187. Serial.println(jsonCityDZ);
  188. indexStart = str.indexOf("dataSK =");
  189. indexEnd = str.indexOf(";var dataZS");
  190. String jsonDataSK = str.substring(indexStart+8,indexEnd);
  191. Serial.println(jsonDataSK);
  192. indexStart = str.indexOf("\"f\":[");
  193. indexEnd = str.indexOf(",{\"fa");
  194. String jsonFC = str.substring(indexStart+5,indexEnd);
  195. Serial.println(jsonFC);
  196. weaterData(&jsonCityDZ,&jsonDataSK,&jsonFC);
  197. Serial.println("获取成功");
  198. } else {
  199. Serial.println("请求城市天气错误:");
  200. Serial.print(httpCode);
  201. }
  202. //关闭ESP8266与服务器连接
  203. httpClient.end();
  204. }
  205. String scrollText[6];
  206. //int scrollTextWidth = 0;
  207. //天气信息写到屏幕上
  208. void weaterData(String *cityDZ,String *dataSK,String *dataFC){
  209. DynamicJsonDocument doc(512);
  210. deserializeJson(doc, *dataSK);
  211. JsonObject sk = doc.as<JsonObject>();
  212. //TFT_eSprite clkb = TFT_eSprite(&tft);
  213. /***绘制相关文字***/
  214. clk.setColorDepth(8);
  215. clk.loadFont(ZdyLwFont_20);
  216. //温度
  217. clk.createSprite(54, 32);
  218. clk.fillSprite(bgColor);
  219. clk.setTextDatum(CC_DATUM);
  220. clk.setTextColor(TFT_BLACK, bgColor);
  221. clk.drawString(sk["temp"].as<String>()+"℃",27,16);
  222. clk.pushSprite(185,168);
  223. clk.deleteSprite();
  224. //城市名称
  225. clk.createSprite(88, 32);
  226. clk.fillSprite(bgColor);
  227. clk.setTextDatum(CC_DATUM);
  228. clk.setTextColor(TFT_BLACK, bgColor);
  229. clk.drawString(sk["cityname"].as<String>(),44,16);
  230. clk.pushSprite(151,1);
  231. clk.deleteSprite();
  232. //PM2.5空气指数
  233. uint16_t pm25BgColor = tft.color565(156,202,127);//
  234. String aqiTxt = "优";
  235. int pm25V = sk["aqi"];
  236. if(pm25V>200){
  237. pm25BgColor = tft.color565(136,11,32);//重度
  238. aqiTxt = "重度";
  239. }else if(pm25V>150){
  240. pm25BgColor = tft.color565(186,55,121);//中度
  241. aqiTxt = "中度";
  242. }else if(pm25V>100){
  243. pm25BgColor = tft.color565(242,159,57);//
  244. aqiTxt = "轻度";
  245. }else if(pm25V>50){
  246. pm25BgColor = tft.color565(247,219,100);//
  247. aqiTxt = "良";
  248. }
  249. clk.createSprite(50, 24);
  250. clk.fillSprite(bgColor);
  251. clk.fillRoundRect(0,0,50,24,4,pm25BgColor);
  252. clk.setTextDatum(CC_DATUM);
  253. clk.setTextColor(0xFFFF);
  254. clk.drawString(aqiTxt,25,13);
  255. clk.pushSprite(5,130);
  256. clk.deleteSprite();
  257. //湿度
  258. clk.createSprite(56, 24);
  259. clk.fillSprite(bgColor);
  260. clk.setTextDatum(CC_DATUM);
  261. clk.setTextColor(TFT_BLACK, bgColor);
  262. clk.drawString(sk["SD"].as<String>(),28,13);
  263. //clk.drawString("100%",28,13);
  264. clk.pushSprite(180,130);
  265. clk.deleteSprite();
  266. scrollText[0] = "实时天气 "+sk["weather"].as<String>();
  267. scrollText[1] = "空气质量 "+aqiTxt;
  268. scrollText[2] = "风向 "+sk["WD"].as<String>()+sk["WS"].as<String>();
  269. //左上角滚动字幕
  270. //解析第二段JSON
  271. deserializeJson(doc, *cityDZ);
  272. JsonObject dz = doc.as<JsonObject>();
  273. //Serial.println(sk["ws"].as<String>());
  274. //横向滚动方式
  275. //String aa = "今日天气:" + dz["weather"].as<String>() + ",温度:最低" + dz["tempn"].as<String>() + ",最高" + dz["temp"].as<String>() + " 空气质量:" + aqiTxt + ",风向:" + dz["wd"].as<String>() + dz["ws"].as<String>();
  276. //scrollTextWidth = clk.textWidth(scrollText);
  277. //Serial.println(aa);
  278. scrollText[3] = "今日"+dz["weather"].as<String>();
  279. deserializeJson(doc, *dataFC);
  280. JsonObject fc = doc.as<JsonObject>();
  281. scrollText[4] = "最低温度"+fc["fd"].as<String>()+"℃";
  282. scrollText[5] = "最高温度"+fc["fc"].as<String>()+"℃";
  283. //Serial.println(scrollText[0]);
  284. clk.unloadFont();
  285. }
  286. int currentIndex = 0;
  287. int prevTime = 0;
  288. TFT_eSprite clkb = TFT_eSprite(&tft);
  289. void scrollBanner(){
  290. if(millis() - prevTime > 2500){ //2.5秒切换一次
  291. if(scrollText[currentIndex]){
  292. clkb.setColorDepth(8);
  293. clkb.loadFont(ZdyLwFont_20);
  294. for(int pos = 24; pos>0 ; pos--){
  295. scrollTxt(pos);
  296. }
  297. clkb.deleteSprite();
  298. clkb.unloadFont();
  299. if(currentIndex>=5){
  300. currentIndex = 0; //回第一个
  301. }else{
  302. currentIndex += 1; //准备切换到下一个
  303. }
  304. //Serial.println(currentIndex);
  305. }
  306. prevTime = millis();
  307. }
  308. }
  309. void scrollTxt(int pos){
  310. clkb.createSprite(148, 24);
  311. clkb.fillSprite(bgColor);
  312. clkb.setTextWrap(false);
  313. clkb.setTextDatum(CC_DATUM);
  314. clkb.setTextColor(TFT_BLACK, bgColor);
  315. clkb.drawString(scrollText[currentIndex],74,pos+12);
  316. clkb.pushSprite(2,4);
  317. }
  318. void imgAnim(){
  319. int x=80,y=94,dt=30;//瘦子版dt=10毫秒 胖子30较为合适
  320. TJpgDec.drawJpg(x,y,i0, sizeof(i0));
  321. delay(dt);
  322. TJpgDec.drawJpg(x,y,i1, sizeof(i1));
  323. delay(dt);
  324. TJpgDec.drawJpg(x,y,i2, sizeof(i2));
  325. delay(dt);
  326. TJpgDec.drawJpg(x,y,i3, sizeof(i3));
  327. delay(dt);
  328. TJpgDec.drawJpg(x,y,i4, sizeof(i4));
  329. delay(dt);
  330. TJpgDec.drawJpg(x,y,i5, sizeof(i5));
  331. delay(dt);
  332. TJpgDec.drawJpg(x,y,i6, sizeof(i6));
  333. delay(dt);
  334. TJpgDec.drawJpg(x,y,i7, sizeof(i7));
  335. delay(dt);
  336. TJpgDec.drawJpg(x,y,i8, sizeof(i8));
  337. delay(dt);
  338. TJpgDec.drawJpg(x,y,i9, sizeof(i9));
  339. delay(dt);
  340. }
  341. void digitalClockDisplay()
  342. {
  343. clk.setColorDepth(8);
  344. /***中间时间区***/
  345. //时分
  346. clk.createSprite(140, 48);
  347. clk.fillSprite(bgColor);
  348. //clk.loadFont(FxLED_48);
  349. clk.setTextDatum(CC_DATUM);
  350. clk.setTextColor(TFT_BLACK, bgColor);
  351. clk.drawString(hourMinute(),70,24,7); //绘制时和分
  352. //clk.unloadFont();
  353. clk.pushSprite(28,40);
  354. clk.deleteSprite();
  355. //
  356. clk.createSprite(40, 32);
  357. clk.fillSprite(bgColor);
  358. clk.loadFont(FxLED_32);
  359. clk.setTextDatum(CC_DATUM);
  360. clk.setTextColor(TFT_BLACK, bgColor);
  361. clk.drawString(num2str(second()),20,16);
  362. clk.unloadFont();
  363. clk.pushSprite(170,60);
  364. clk.deleteSprite();
  365. /***中间时间区***/
  366. /***底部***/
  367. clk.loadFont(ZdyLwFont_20);
  368. clk.createSprite(58, 32);
  369. clk.fillSprite(bgColor);
  370. //星期
  371. clk.setTextDatum(CC_DATUM);
  372. clk.setTextColor(TFT_BLACK, bgColor);
  373. clk.drawString(week(),29,16);
  374. clk.pushSprite(1,168);
  375. clk.deleteSprite();
  376. //月日
  377. clk.createSprite(98, 32);
  378. clk.fillSprite(bgColor);
  379. clk.setTextDatum(CC_DATUM);
  380. clk.setTextColor(TFT_BLACK, bgColor);
  381. clk.drawString(monthDay(),49,16);
  382. clk.pushSprite(61,168);
  383. clk.deleteSprite();
  384. clk.unloadFont();
  385. /***底部***/
  386. }
  387. //星期
  388. String week(){
  389. String wk[7] = {"日","一","二","三","四","五","六"};
  390. String s = "周" + wk[weekday()-1];
  391. return s;
  392. }
  393. //月日
  394. String monthDay(){
  395. String s = String(month());
  396. s = s + "月" + day() + "日";
  397. return s;
  398. }
  399. //时分
  400. String hourMinute(){
  401. String s = num2str(hour());
  402. s = s + ":" + num2str(minute());
  403. return s;
  404. }
  405. String num2str(int digits)
  406. {
  407. String s = "";
  408. if (digits < 10)
  409. s = s + "0";
  410. s = s + digits;
  411. return s;
  412. }
  413. void printDigits(int digits)
  414. {
  415. Serial.print(":");
  416. if (digits < 10)
  417. Serial.print('0');
  418. Serial.print(digits);
  419. }
  420. /*-------- NTP code ----------*/
  421. const int NTP_PACKET_SIZE = 48; // NTP时间在消息的前48字节中
  422. byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
  423. time_t getNtpTime()
  424. {
  425. IPAddress ntpServerIP; // NTP server's ip address
  426. while (Udp.parsePacket() > 0) ; // discard any previously received packets
  427. //Serial.println("Transmit NTP Request");
  428. // get a random server from the pool
  429. WiFi.hostByName(ntpServerName, ntpServerIP);
  430. //Serial.print(ntpServerName);
  431. //Serial.print(": ");
  432. //Serial.println(ntpServerIP);
  433. sendNTPpacket(ntpServerIP);
  434. uint32_t beginWait = millis();
  435. while (millis() - beginWait < 1500) {
  436. int size = Udp.parsePacket();
  437. if (size >= NTP_PACKET_SIZE) {
  438. Serial.println("Receive NTP Response");
  439. Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
  440. unsigned long secsSince1900;
  441. // convert four bytes starting at location 40 to a long integer
  442. secsSince1900 = (unsigned long)packetBuffer[40] << 24;
  443. secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  444. secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  445. secsSince1900 |= (unsigned long)packetBuffer[43];
  446. //Serial.println(secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR);
  447. return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  448. }
  449. }
  450. Serial.println("No NTP Response :-(");
  451. return 0; // 无法获取时间时返回0
  452. }
  453. // 向NTP服务器发送请求
  454. void sendNTPpacket(IPAddress &address)
  455. {
  456. // set all bytes in the buffer to 0
  457. memset(packetBuffer, 0, NTP_PACKET_SIZE);
  458. // Initialize values needed to form NTP request
  459. // (see URL above for details on the packets)
  460. packetBuffer[0] = 0b11100011; // LI, Version, Mode
  461. packetBuffer[1] = 0; // Stratum, or type of clock
  462. packetBuffer[2] = 6; // Polling Interval
  463. packetBuffer[3] = 0xEC; // Peer Clock Precision
  464. // 8 bytes of zero for Root Delay & Root Dispersion
  465. packetBuffer[12] = 49;
  466. packetBuffer[13] = 0x4E;
  467. packetBuffer[14] = 49;
  468. packetBuffer[15] = 52;
  469. // all NTP fields have been given values, now
  470. // you can send a packet requesting a timestamp:
  471. Udp.beginPacket(address, 123); //NTP requests are to port 123
  472. Udp.write(packetBuffer, NTP_PACKET_SIZE);
  473. Udp.endPacket();
  474. }

 四、效果演示

太空人智能时钟效果演示

 

申明:该程序是基于该文章修改的。(15条消息) 用esp8266做太空人表盘,arduinoIDE编辑_创客协会的阿蛋°的博客-CSDN博客_esp8266太空人手表

申明:本原理图是参考【征集令】ESP8266天气时钟 - 嘉立创EDA开源硬件平台 (oshwhub.com)复刻出来的。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号