找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 5242|回复: 4
打印 上一主题 下一主题
收起左侧

简易太空人时钟Arduino代码 带天气显示

  [复制链接]
跳转到指定楼层
楼主
ID:428407 发表于 2021-12-5 19:15 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
ESP8266的屏幕显示
  1. /*
  2. * ***********************************************
  3. * 简易太空人时钟代码

  4. * 2021.04.19 修正空气质量AQI状态显示错误的bug
  5. * 欢迎随意传播修改,但请保留本段注释,且不要用于商业目的
  6. *
  7. * 目前已经发现有人在鱼加备注倒卖,我就不点名了。另外有
  8. * 人反馈旋转的小人有卡顿,因为左上角有一
  9. * 个实时滚动屏要预留时间做切换,性能原因特意为之。不然左
  10. * 上角没有动画效果。如谁有更好的办法欢迎修改后分享出来,
  11. * ***********************************************
  12. * 程序硬件介绍 esp8266 nodemcu + LCD屏幕(ST7789)
  13. *
  14. * 自动根据当前IP获取相应天气
  15. * 代码凑合着看
  16. * 时间部分使用NTP同步阿里云服务器时间
  17. * 天气部分从中国天气网上扒下来的,具体是否能长期使用无法确定
  18. *
  19. * 屏幕使用的中景园1.54寸240分辨率全彩屏幕,7、8、10针脚的屏应该都可以,具体请自己参考引脚定义
  20. *
  21. */
  22. #include <ArduinoJson.h>

  23. #include <TimeLib.h>
  24. #include <ESP8266WiFi.h>
  25. #include <WiFiUdp.h>
  26. #include <ESP8266HTTPClient.h>
  27. #include "font/ZdyLwFont_20.h"
  28. #include "font/FxLED_32.h"

  29. #include "img/pangzi/i0.h"
  30. #include "img/pangzi/i1.h"
  31. #include "img/pangzi/i2.h"
  32. #include "img/pangzi/i3.h"
  33. #include "img/pangzi/i4.h"
  34. #include "img/pangzi/i5.h"
  35. #include "img/pangzi/i6.h"
  36. #include "img/pangzi/i7.h"
  37. #include "img/pangzi/i8.h"
  38. #include "img/pangzi/i9.h"

  39. #include "img/temperature.h"
  40. #include "img/humidity.h"
  41. #include "img/watch_top.h"
  42. #include "img/watch_bottom.h"

  43. #include <TFT_eSPI.h>
  44. #include <SPI.h>
  45. int count=0;
  46. bool WIFI_Status = true;

  47. TFT_eSPI tft = TFT_eSPI();  // 引脚请自行配置tft_espi库中的 User_Setup.h文件
  48. TFT_eSprite clk = TFT_eSprite(&tft);


  49. #include <TJpg_Decoder.h>

  50. uint32_t targetTime = 0;   
  51. byte omm = 99;
  52. boolean initial = 1;
  53. byte xcolon = 0;
  54. unsigned int colour = 0;

  55. uint16_t bgColor = 0xFFFF;
  56. String cityCode = "101040100";  //天气城市代码

  57. //NTP服务器
  58. static const char ntpServerName[] = "ntp6.aliyun";
  59. const int timeZone = 8;     //东八区


  60. WiFiUDP Udp;
  61. unsigned int localPort = 8000;

  62. time_t getNtpTime();
  63. void digitalClockDisplay();
  64. void printDigits(int digits);
  65. String num2str(int digits);
  66. void sendNTPpacket(IPAddress &address);


  67. bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap)
  68. {
  69.   if ( y >= tft.height() ) return 0;
  70.   tft.pushImage(x, y, w, h, bitmap);
  71.   // Return 1 to decode next block
  72.   return 1;
  73. }

  74. byte loadNum = 6;
  75. void loading(byte delayTime){
  76.   clk.setColorDepth(8);
  77.   
  78.   clk.createSprite(200, 50);
  79.   clk.fillSprite(0x0000);

  80.   clk.drawRoundRect(0,0,200,16,8,0xFFFF);
  81.   clk.fillRoundRect(3,3,loadNum,10,5,0xFFFF);
  82.   clk.setTextDatum(CC_DATUM);
  83.   clk.setTextColor(TFT_GREEN, 0x0000);
  84.   clk.drawString("Connecting to WiFi",100,40,2);
  85.   clk.pushSprite(20,110);
  86.   clk.deleteSprite();
  87.   loadNum += 1;
  88.   if(loadNum>=194){
  89.     loadNum = 194;
  90.   }
  91.   delay(delayTime);
  92. }
  93. void smartConfig()
  94. {
  95.   WiFi.mode(WIFI_STA);
  96.   Serial.println("\r\nWait for Smartconfig...");
  97.   WiFi.beginSmartConfig();//等待手机端发出的用户名与密码
  98.   while (1)
  99.   {
  100.     Serial.print(".");
  101.     digitalWrite(LED_BUILTIN, HIGH);  
  102.     delay(1000);                     
  103.     digitalWrite(LED_BUILTIN, LOW);   
  104.     delay(1000);                     
  105.     if (WiFi.smartConfigDone())//退出等待
  106.     {
  107.       Serial.println("SmartConfig Success");
  108.       Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
  109.       Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
  110.       break;
  111.     }
  112.   }
  113. }
  114. void setup()
  115. {
  116.   Serial.begin(9600);
  117.   delay(10);
  118.   pinMode(LED_BUILTIN, OUTPUT);
  119.   Serial.println();
  120.   Serial.println();
  121.   Serial.println("connecting to");
  122.   smartConfig();  //微信智能配网
  123.   Serial.println("\r\n正在连接");
  124.   delay(500);
  125.   Serial.println("");
  126.   Serial.println("wifi connected");  
  127.   while(WiFi.status()!=WL_CONNECTED)
  128.   {
  129.       if(WIFI_Status)
  130.       {
  131.           Serial.print(".");
  132.           digitalWrite(LED_BUILTIN, HIGH);  
  133.           delay(500);                       
  134.           digitalWrite(LED_BUILTIN, LOW);   
  135.           delay(500);                 
  136.           count++;
  137.           if(count>=5)//5s
  138.           {
  139.               WIFI_Status = false;
  140.               Serial.println("WiFi连接失败,请用手机进行配网");
  141.           }
  142.       }
  143.       else
  144.       {
  145.           smartConfig();  //微信智能配网
  146.       }
  147.    }
  148.    Serial.println("连接成功");  
  149.   
  150.   
  151.   tft.init();
  152.   tft.setRotation(0);
  153.   tft.fillScreen(0x0000);
  154.   tft.setTextColor(TFT_BLACK, bgColor);

  155.   targetTime = millis() + 1000;

  156.   Serial.print("正在连接WIFI ");
  157.   //Serial.println(ssid);
  158. // WiFi.begin(ssid, pass);

  159.   while (WiFi.status() != WL_CONNECTED) {
  160.     for(byte n=0;n<10;n++){ //每500毫秒检测一次状态
  161.       loading(50);
  162.     }
  163.   }
  164.   while(loadNum < 194){ //让动画走完
  165.     loading(1);
  166.   }

  167.   Serial.print("本地IP: ");
  168.   Serial.println(WiFi.localIP());
  169.   //Serial.println("启动UDP");
  170.   Udp.begin(localPort);
  171.   //Serial.print("端口号: ");
  172.   //Serial.println(Udp.localPort());
  173.   //Serial.println("等待同步...");
  174.   setSyncProvider(getNtpTime);
  175.   setSyncInterval(300);

  176.   
  177.   TJpgDec.setJpgScale(1);
  178.   TJpgDec.setSwapBytes(true);
  179.   TJpgDec.setCallback(tft_output);

  180.   TJpgDec.drawJpg(0,0,watchtop, sizeof(watchtop));
  181.   TJpgDec.drawJpg(0,220,watchbottom, sizeof(watchbottom));

  182.   
  183.   //绘制一个视口
  184.   tft.setViewport(0, 20, 240, 200);
  185.   tft.fillScreen(0x0000);
  186.   tft.fillRoundRect(0,0,240,200,5,bgColor);//实心圆角矩形
  187.   //tft.resetViewport();

  188.   //绘制线框
  189.   tft.drawFastHLine(0,34,240,TFT_BLACK);
  190.   
  191.   tft.drawFastVLine(150,0,34,TFT_BLACK);
  192.   
  193.   tft.drawFastHLine(0,166,240,TFT_BLACK);
  194.   
  195.   tft.drawFastVLine(60,166,34,TFT_BLACK);
  196.   tft.drawFastVLine(160,166,34,TFT_BLACK);

  197.   getCityCode();  //获取城市代码
  198.   
  199.   TJpgDec.drawJpg(161,171,temperature, sizeof(temperature));  //温度图标
  200.   TJpgDec.drawJpg(159,130,humidity, sizeof(humidity));  //湿度图标
  201.   
  202. }

  203. time_t prevDisplay = 0; // 显示时间
  204. unsigned long weaterTime = 0;

  205. void loop(){
  206.   
  207.   if (now() != prevDisplay) {
  208.     prevDisplay = now();
  209.     digitalClockDisplay();
  210.   }

  211.   
  212.   if(millis() - weaterTime > 300000){ //5分钟更新一次天气
  213.     weaterTime = millis();
  214.     getCityWeater();
  215.   }
  216.   scrollBanner();
  217.   imgAnim();
  218. }

  219. // 发送HTTP请求并且将服务器响应通过串口输出
  220. void getCityCode(){
  221. String URL = "ip/?_="+String(now());
  222.   //创建 HTTPClient 对象
  223.   HTTPClient httpClient;

  224.   //配置请求地址。此处也可以不使用端口号和PATH而单纯的
  225.   httpClient.begin(URL);
  226.   
  227.   //设置请求头中的User-Agent
  228.   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");
  229.   httpClient.addHeader("Referer", "");

  230.   //启动连接并发送HTTP请求
  231.   int httpCode = httpClient.GET();
  232.   Serial.print("Send GET request to URL: ");
  233.   Serial.println(URL);
  234.   
  235.   //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
  236.   if (httpCode == HTTP_CODE_OK) {
  237.     String str = httpClient.getString();
  238.    
  239.     int aa = str.indexOf("id=");
  240.     if(aa>-1){
  241.        //cityCode = str.substring(aa+4,aa+4+9).toInt();
  242.        cityCode = str.substring(aa+4,aa+4+9);
  243.        Serial.println(cityCode);
  244.        getCityWeater();
  245.     }else{
  246.       Serial.println("获取城市代码失败");  
  247.     }
  248.    
  249.    
  250.   } else {
  251.     Serial.println("请求城市代码错误:");
  252.     Serial.println(httpCode);
  253.   }

  254.   //关闭ESP8266与服务器连接
  255.   httpClient.end();
  256. }



  257. // 获取城市天气
  258. void getCityWeater(){
  259. String URL = "/weather_index/" + cityCode + ".html?_="+String(now());
  260.   //创建 HTTPClient 对象
  261.   HTTPClient httpClient;
  262.   
  263.   httpClient.begin(URL);
  264.   
  265.   //设置请求头中的User-Agent
  266.   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");
  267.   httpClient.addHeader("Referer", "");

  268.   //启动连接并发送HTTP请求
  269.   int httpCode = httpClient.GET();
  270.   Serial.println("正在获取天气数据");
  271.   Serial.println(URL);
  272.   
  273.   //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
  274.   if (httpCode == HTTP_CODE_OK) {

  275.     String str = httpClient.getString();
  276.     int indexStart = str.indexOf("weatherinfo\":");
  277.     int indexEnd = str.indexOf("};var alarmDZ");

  278.     String jsonCityDZ = str.substring(indexStart+13,indexEnd);
  279.     Serial.println(jsonCityDZ);

  280.     indexStart = str.indexOf("dataSK =");
  281.     indexEnd = str.indexOf(";var dataZS");
  282.     String jsonDataSK = str.substring(indexStart+8,indexEnd);
  283.     Serial.println(jsonDataSK);

  284.    
  285.     indexStart = str.indexOf("\"f\":[");
  286.     indexEnd = str.indexOf(",{\"fa");
  287.     String jsonFC = str.substring(indexStart+5,indexEnd);
  288.     Serial.println(jsonFC);
  289.    
  290.     weaterData(&jsonCityDZ,&jsonDataSK,&jsonFC);
  291.     Serial.println("获取成功");
  292.    
  293.   } else {
  294.     Serial.println("请求城市天气错误:");
  295.     Serial.print(httpCode);
  296.   }

  297.   //关闭ESP8266与服务器连接
  298.   httpClient.end();
  299. }


  300. String scrollText[6];
  301. //int scrollTextWidth = 0;
  302. //天气信息写到屏幕上
  303. void weaterData(String *cityDZ,String *dataSK,String *dataFC){
  304.   
  305.   DynamicJsonDocument doc(1024);
  306.   deserializeJson(doc, *dataSK);
  307.   JsonObject sk = doc.as<JsonObject>();

  308.   //TFT_eSprite clkb = TFT_eSprite(&tft);
  309.   
  310.   /***绘制相关文字***/
  311.   clk.setColorDepth(8);
  312.   clk.loadFont(ZdyLwFont_20);
  313.   
  314.   //温度
  315.   clk.createSprite(54, 32);
  316.   clk.fillSprite(bgColor);
  317.   clk.setTextDatum(CC_DATUM);
  318.   clk.setTextColor(TFT_BLACK, bgColor);
  319.   clk.drawString(sk["temp"].as<String>()+"℃",27,16);
  320.   clk.pushSprite(185,168);
  321.   clk.deleteSprite();

  322.   //城市名称
  323.   clk.createSprite(88, 32);
  324.   clk.fillSprite(bgColor);
  325.   clk.setTextDatum(CC_DATUM);
  326.   clk.setTextColor(TFT_BLACK, bgColor);
  327.   clk.drawString(sk["cityname"].as<String>(),44,16);
  328.   clk.pushSprite(151,1);
  329.   clk.deleteSprite();
  330.   
  331.   //PM2.5空气指数
  332.   uint16_t pm25BgColor = tft.color565(156,202,127);//优
  333.   String aqiTxt = "优";
  334.   int pm25V = sk["aqi"];
  335.   if(pm25V>200){
  336.     pm25BgColor = tft.color565(136,11,32);//重度
  337.     aqiTxt = "重度";
  338.   }else if(pm25V>150){
  339.     pm25BgColor = tft.color565(186,55,121);//中度
  340.     aqiTxt = "中度";
  341.   }else if(pm25V>100){
  342.     pm25BgColor = tft.color565(242,159,57);//轻
  343.     aqiTxt = "轻度";
  344.   }else if(pm25V>50){
  345.     pm25BgColor = tft.color565(247,219,100);//良
  346.     aqiTxt = "良";
  347.   }
  348.   clk.createSprite(50, 24);
  349.   clk.fillSprite(bgColor);
  350.   clk.fillRoundRect(0,0,50,24,4,pm25BgColor);
  351.   clk.setTextDatum(CC_DATUM);
  352.   clk.setTextColor(0xFFFF);
  353.   clk.drawString(aqiTxt,25,13);
  354.   clk.pushSprite(5,130);
  355.   clk.deleteSprite();

  356.   //湿度
  357.   clk.createSprite(56, 24);
  358.   clk.fillSprite(bgColor);
  359.   clk.setTextDatum(CC_DATUM);
  360.   clk.setTextColor(TFT_BLACK, bgColor);
  361.   clk.drawString(sk["SD"].as<String>(),28,13);
  362.   //clk.drawString("100%",28,13);
  363.   clk.pushSprite(180,130);
  364.   clk.deleteSprite();

  365.   
  366.   scrollText[0] = "实时天气 "+sk["weather"].as<String>();
  367.   scrollText[1] = "空气质量 "+aqiTxt;
  368.   scrollText[2] = "风向 "+sk["WD"].as<String>()+sk["WS"].as<String>();
  369.   
  370.   //左上角滚动字幕
  371.   //解析第二段JSON
  372.   deserializeJson(doc, *cityDZ);
  373.   JsonObject dz = doc.as<JsonObject>();
  374.   //Serial.println(sk["ws"].as<String>());
  375.   //横向滚动方式
  376.   //String aa = "今日天气:" + dz["weather"].as<String>() + ",温度:最低" + dz["tempn"].as<String>() + ",最高" + dz["temp"].as<String>() + " 空气质量:" + aqiTxt + ",风向:" + dz["wd"].as<String>() + dz["ws"].as<String>();
  377.   //scrollTextWidth = clk.textWidth(scrollText);
  378.   //Serial.println(aa);
  379.   scrollText[3] = "今日"+dz["weather"].as<String>();
  380.   
  381.   deserializeJson(doc, *dataFC);
  382.   JsonObject fc = doc.as<JsonObject>();
  383.   
  384.   scrollText[4] = "最低温度"+fc["fd"].as<String>()+"℃";
  385.   scrollText[5] = "最高温度"+fc["fc"].as<String>()+"℃";
  386.   
  387.   //Serial.println(scrollText[0]);
  388.   
  389.   clk.unloadFont();

  390. }

  391. int currentIndex = 0;
  392. int prevTime = 0;
  393. TFT_eSprite clkb = TFT_eSprite(&tft);

  394. void scrollBanner(){
  395.   if(millis() - prevTime > 2500){ //2.5秒切换一次

  396.     if(scrollText[currentIndex]){
  397.   
  398.       clkb.setColorDepth(8);
  399.       clkb.loadFont(ZdyLwFont_20);
  400.       
  401.       for(int pos = 24; pos>0 ; pos--){
  402.         scrollTxt(pos);
  403.       }
  404.       
  405.       clkb.deleteSprite();
  406.       clkb.unloadFont();
  407.   
  408.       if(currentIndex>=5){
  409.         currentIndex = 0;  //回第一个
  410.       }else{
  411.         currentIndex += 1;  //准备切换到下一个  
  412.       }
  413.       //Serial.println(currentIndex);
  414.       
  415.     }
  416.     prevTime = millis();
  417.   }
  418. }

  419. void scrollTxt(int pos){
  420.     clkb.createSprite(148, 24);
  421.     clkb.fillSprite(bgColor);
  422.     clkb.setTextWrap(false);
  423.     clkb.setTextDatum(CC_DATUM);
  424.     clkb.setTextColor(TFT_BLACK, bgColor);
  425.     clkb.drawString(scrollText[currentIndex],74,pos+12);
  426.     clkb.pushSprite(2,4);
  427. }

  428. void imgAnim(){
  429.   int x=80,y=94,dt=30;//瘦子版dt=10毫秒 胖子30较为合适

  430.   TJpgDec.drawJpg(x,y,i0, sizeof(i0));
  431.   delay(dt);
  432.   TJpgDec.drawJpg(x,y,i1, sizeof(i1));
  433.   delay(dt);
  434.   TJpgDec.drawJpg(x,y,i2, sizeof(i2));
  435.   delay(dt);
  436.   TJpgDec.drawJpg(x,y,i3, sizeof(i3));
  437.   delay(dt);  
  438.   TJpgDec.drawJpg(x,y,i4, sizeof(i4));
  439.   delay(dt);  
  440.   TJpgDec.drawJpg(x,y,i5, sizeof(i5));
  441.   delay(dt);  
  442.   TJpgDec.drawJpg(x,y,i6, sizeof(i6));
  443.   delay(dt);  
  444.   TJpgDec.drawJpg(x,y,i7, sizeof(i7));
  445.   delay(dt);  
  446.   TJpgDec.drawJpg(x,y,i8, sizeof(i8));
  447.   delay(dt);  
  448.   TJpgDec.drawJpg(x,y,i9, sizeof(i9));
  449.   delay(dt);  

  450. }

  451. void digitalClockDisplay()
  452. {
  453.   
  454.   clk.setColorDepth(8);

  455.   /***中间时间区***/
  456.   //时分
  457.   clk.createSprite(140, 48);
  458.   clk.fillSprite(bgColor);
  459.   //clk.loadFont(FxLED_48);
  460.   clk.setTextDatum(CC_DATUM);
  461.   clk.setTextColor(TFT_BLACK, bgColor);
  462.   clk.drawString(hourMinute(),70,24,7); //绘制时和分
  463.   //clk.unloadFont();
  464.   clk.pushSprite(28,40);
  465.   clk.deleteSprite();
  466.   
  467.   //秒
  468.   clk.createSprite(40, 32);
  469.   clk.fillSprite(bgColor);
  470.   
  471.   clk.loadFont(FxLED_32);
  472.   clk.setTextDatum(CC_DATUM);
  473.   clk.setTextColor(TFT_BLACK, bgColor);
  474.   clk.drawString(num2str(second()),20,16);
  475.   
  476.   clk.unloadFont();
  477.   clk.pushSprite(170,60);
  478.   clk.deleteSprite();
  479.   /***中间时间区***/

  480.   /***底部***/
  481.   clk.loadFont(ZdyLwFont_20);
  482.   clk.createSprite(58, 32);
  483.   clk.fillSprite(bgColor);

  484.   //星期
  485.   clk.setTextDatum(CC_DATUM);
  486.   clk.setTextColor(TFT_BLACK, bgColor);
  487.   clk.drawString(week(),29,16);
  488.   clk.pushSprite(1,168);
  489.   clk.deleteSprite();
  490.   
  491.   //月日
  492.   clk.createSprite(98, 32);
  493.   clk.fillSprite(bgColor);
  494.   clk.setTextDatum(CC_DATUM);
  495.   clk.setTextColor(TFT_BLACK, bgColor);  
  496.   clk.drawString(monthDay(),49,16);
  497.   clk.pushSprite(61,168);
  498.   clk.deleteSprite();
  499.   
  500.   
  501.   clk.unloadFont();
  502.   /***底部***/
  503. }

  504. //星期
  505. String week(){
  506.   String wk[7] = {"日","一","二","三","四","五","六"};
  507.   String s = "周" + wk[weekday()-1];
  508.   return s;
  509. }

  510. //月日
  511. String monthDay(){
  512.   String s = String(month());
  513.   s = s + "月" + day() + "日";
  514.   return s;
  515. }
  516. //时分
  517. String hourMinute(){
  518.   String s = num2str(hour());
  519.   s = s + ":" + num2str(minute());
  520.   return s;
  521. }

  522. String num2str(int digits)
  523. {
  524.   String s = "";
  525.   if (digits < 10)
  526.     s = s + "0";
  527.   s = s + digits;
  528.   return s;
  529. }

  530. void printDigits(int digits)
  531. {
  532.   Serial.print(":");
  533.   if (digits < 10)
  534.     Serial.print('0');
  535.   Serial.print(digits);
  536. }

  537. /*-------- NTP code ----------*/

  538. const int NTP_PACKET_SIZE = 48; // NTP时间在消息的前48字节中
  539. byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

  540. time_t getNtpTime()
  541. {
  542.   IPAddress ntpServerIP; // NTP server's ip address

  543.   while (Udp.parsePacket() > 0) ; // discard any previously received packets
  544.   //Serial.println("Transmit NTP Request");
  545.   // get a random server from the pool
  546.   WiFi.hostByName(ntpServerName, ntpServerIP);
  547.   //Serial.print(ntpServerName);
  548.   //Serial.print(": ");
  549.   //Serial.println(ntpServerIP);
  550.   sendNTPpacket(ntpServerIP);
  551.   uint32_t beginWait = millis();
  552.   while (millis() - beginWait < 1500) {
  553.     int size = Udp.parsePacket();
  554.     if (size >= NTP_PACKET_SIZE) {
  555.       Serial.println("Receive NTP Response");
  556.       Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
  557.       unsigned long secsSince1900;
  558.       // convert four bytes starting at location 40 to a long integer
  559.       secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
  560.       secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  561.       secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  562.       secsSince1900 |= (unsigned long)packetBuffer[43];
  563.       //Serial.println(secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR);
  564.       return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  565.     }
  566.   }
  567.   Serial.println("No NTP Response :-(");
  568.   return 0; // 无法获取时间时返回0
  569. }

  570. // 向NTP服务器发送请求
  571. void sendNTPpacket(IPAddress &address)
  572. {
  573.   // set all bytes in the buffer to 0
  574.   memset(packetBuffer, 0, NTP_PACKET_SIZE);
  575.   // Initialize values needed to form NTP request
  576.   // (see URL above for details on the packets)
  577.   packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  578.   packetBuffer[1] = 0;     // Stratum, or type of clock
  579.   packetBuffer[2] = 6;     // Polling Interval
  580.   packetBuffer[3] = 0xEC;  // Peer Clock Precision
  581.   // 8 bytes of zero for Root Delay & Root Dispersion
  582.   packetBuffer[12] = 49;
  583.   packetBuffer[13] = 0x4E;
  584.   packetBuffer[14] = 49;
  585.   packetBuffer[15] = 52;
  586.   // all NTP fields have been given values, now
  587.   // you can send a packet requesting a timestamp:
  588.   Udp.beginPacket(address, 123); //NTP requests are to port 123
  589.   Udp.write(packetBuffer, NTP_PACKET_SIZE);
  590.   Udp.endPacket();
  591. }
复制代码

代码下载,仅供参考:
天气一.7z (4.38 MB, 下载次数: 106)
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏6 分享淘帖 顶 踩
回复

使用道具 举报

沙发
ID:988976 发表于 2021-12-7 09:52 | 只看该作者
回去试试,看行不行
回复

使用道具 举报

板凳
ID:934872 发表于 2022-7-28 10:20 | 只看该作者
能用多线程吗
回复

使用道具 举报

地板
ID:313092 发表于 2023-1-3 16:15 | 只看该作者
谢谢楼主分享!另想请教一下:我下载了代码,在编译时出现这个提示:下载package_esp8266com_index.json 时出错  Invalid version '0.3.0.3.80211227' for library in: E:\Arduino\libraries\blinker-library-master  E:\我的桌面\天气一\CLOCK\CLOCK.ino: In function 'void getCityWeater()':  CLOCK:301:19: error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)  E:\我的桌面\天气一\CLOCK\CLOCK.ino: In function 'void getCityCode()':  CLOCK:258:19: error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
回复

使用道具 举报

5#
ID:842962 发表于 2023-2-15 12:31 | 只看该作者
CLOCK:257:19: error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
"SD.h" 对应多个库
已使用: C:\Users\20321\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.1\libraries\SD
未使用:D:\Arduino\libraries\SD
"TimeLib.h" 对应多个库
已使用: C:\Users\20321\Documents\Arduino\libraries\Time-Library
未使用:C:\Users\20321\Documents\Arduino\libraries\Time
exit status 1
call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
这个问题咋解决啊
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表