当前位置:   article > 正文

太空人Wifi天气电子时钟(ESP8266+oled 8针0.96寸)_wifi天气时钟程序

wifi天气时钟程序

一、实现效果

 

WeChat_20221109203218

二、开发说明

        几个月前就实现了效果,一直没有整理发布博客。开发工具:visual studio code  平台:platformio。visual studio code 安装以及platformio插件 配置可百度,就是使用platformio插件项目开始下载慢的问题,这个需要在早上(网络不好需更换wifi)下载,这样项目基本都新建成功,我一开始白天新建项目下载esp8266相关的文件都一直卡着不动,后来都是一大早新建项目都成功了,由于屏幕较小,布局改了几次。使用的库:

TFT_eSPI、TJpg_Decoder、ArduinoJson、TimeLib(下载的别人写好的)以及esp8266wifi连接相关。

三、实现过程

(1)TFT_eSPI配置

        引脚请自行配置tft_espi库中的 User_Setup.h文件。在User_Setup.h文件中使用st7735驱动

以及高度、宽度、RGB等配置

 (2)屏幕引脚插线

具体接线对应如下:

TFT屏幕                    nodemcu

GND                             GND

VCC                              3V3

SCL                                 D5

SDA                                 D7

RES                                 D4

DC                                   D3

CS                                    D8

BLK                                  可以不接(控制屏幕背光)

   (3)利用python将太空人gif转为多个图片以及数据文件

 最终使用space.h文件引入适合的帧数据,不能都引入,都引入就大了。

  1. from PIL import Image
  2. import sys
  3. import os
  4. from io import BytesIO
  5. import binascii
  6. import traceback
  7. curdir = "./"
  8. os.chdir(curdir)
  9. def processImage(in_file, saveImg=True):
  10. try:
  11. im = Image.open(in_file)
  12. except IOError:
  13. print("Cant load", in_file)
  14. sys.exit(1)
  15. # 截取文件名
  16. filename = in_file.split('.')[0]
  17. i = 0
  18. mypalette = im.getpalette()
  19. arr_name_all = '' # 存取数组
  20. arr_size_all = '' # 存储数组容量
  21. try:
  22. with open(filename + '.h', 'w', encoding='utf-8') as f: # 写入文件
  23. f.write('#include <pgmspace.h> \n\n')
  24. while 1:
  25. print('.', end="")
  26. im.putpalette(mypalette)
  27. new_im = Image.new("RGB", im.size)
  28. new_im.paste(im)
  29. # 缩放图像,
  30. width = new_im.size[0] # 获取原始图像宽度
  31. height = new_im.size[1] # 获取原始图像高度
  32. new_height = 82 # 等比例缩放后的图像高度,根据实际需要调整
  33. # print(width, " ", height)
  34. if height > new_height:
  35. ratio = round(new_height / height, 3) # 缩放系数
  36. new_im = new_im.resize((int(width * ratio), int(height * ratio)), Image.ANTIALIAS)
  37. # 获取图像字节流,转16进制格式
  38. img_byte = BytesIO() # 获取字节流
  39. new_im.save(img_byte, format='jpeg')
  40. # print(img_byte.getvalue())
  41. # 16进制字符串
  42. img_hex = binascii.hexlify(img_byte.getvalue()).decode('utf-8')
  43. arr_name = filename + '_' + str(i)
  44. arr_size = 0 # 记录数组长度
  45. arr_name_all += arr_name + ','
  46. # 将ac --> 0xac
  47. f.write('const uint8_t ' + arr_name + '[] PROGMEM = { \n') # 写前
  48. for index, x in zip(range(len(img_hex)), range(0, len(img_hex), 2)):
  49. temp_hex = '0x' + img_hex[x:x + 2] + ', '
  50. # 30个数据换行
  51. if (index + 1) % 30 == 0:
  52. temp_hex += '\n'
  53. f.write(temp_hex) # 写入文件
  54. arr_size += 1
  55. f.write('\n};\n\n') # 写结尾
  56. i += 1
  57. arr_size_all += str(arr_size) + ','
  58. # 保存一帧帧图像
  59. if saveImg:
  60. if not os.path.exists('./out_img'):
  61. os.mkdir('./out_img')
  62. if not os.path.exists('./out_img/' + filename):
  63. os.mkdir('./out_img/' + filename)
  64. new_im.save('./out_img/' + filename + '/' + str(i) + '.jpg')
  65. try:
  66. im.seek(im.tell() + 1)
  67. except EOFError:
  68. # 动图读取结束
  69. f.write('const uint8_t *' + filename + '[' + str(i) + '] PROGMEM { ' + arr_name_all + '};\n')
  70. f.write('const uint32_t ' + filename + '_size[' + str(i) + '] PROGMEM { ' + arr_size_all + '};')
  71. print("成功保存文件为:" + filename + '.h')
  72. break
  73. except EOFError as e:
  74. print(e.args)
  75. print(traceback.format_exc())
  76. pass # end of sequence
  77. if __name__ == '__main__':
  78. processImage("space.gif", True)
  79. # im=Image.open("foo0.bmp")
  80. # print ("img info:",im.format,im.size)

 (4)使用processing 软件制作字体

        使用processing打开Create_font.pde文件(https://processing.org/ 下载processing软件,并且安装)。只需修改几个地方就可以,如下所示:

 

        每个汉字对应的unicode码值可以通过在线转换工具获取,然后将转换后的/u替换为0x即可。完成修改后,点击运行,弹出对话框显示自定义库中的所有字符,同时在FontFiles文件夹中生成一个.vlw格式的文件,存放我们制作出来的字库文件。通过https://tomeko.net/online_tools/file_to_hex.php?lang=zh,将vlw文件转换成Arduin使用的字库文件xxxFont.h

 将生成的16进制数据按照下列各式存放在自定义的.h格式文件中

  1. #include <pgmspace.h>
  2. const uint8_t font_10[] PROGMEM = {
  3. 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00,
  4. 0x00, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x52, 0xA0, 0x00, 0x00, 0x00, 0x1F,
  5. 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x02,
  6. ...
  7. 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0xB9, 0x00, 0x00, 0x00, 0x26,
  8. 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x07,
  9. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x96, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x29,
  10. };

    (5)  完整代码

  1. #include <TFT_eSPI.h>
  2. #include <Arduino.h>
  3. #include <ESP8266WiFi.h>
  4. #include <ESP8266WiFiMulti.h>
  5. #include <ESP8266HTTPClient.h>
  6. #include <TJpg_Decoder.h>
  7. #include <WiFiUdp.h>
  8. #include <TimeLib.h>
  9. #include <ArduinoJson.h>
  10. // #include <NTPClient.h>
  11. #include "img/space.h" // 太空人
  12. #include "font/date_18.h" // 时间
  13. #include "font/time_20.h" // 日期
  14. TFT_eSPI tft = TFT_eSPI(); // 引脚请自行配置tft_espi库中的 User_Setup.h文件
  15. TFT_eSprite clk = TFT_eSprite(&tft);
  16. WiFiClient espClient;
  17. ESP8266WiFiMulti wifis;
  18. WiFiUDP Udp;
  19. // NTP Servers:
  20. // static const char ntpServerName[] = "cn.ntp.org.cn";
  21. static const char ntpServerName[] = "ntp1.aliyun.com";
  22. const int timeZone = 8; // 时区
  23. unsigned int localPort = 1337; // local port to listen for UDP packets
  24. unsigned long weatherTime = 0;
  25. struct WeatherData
  26. {
  27. char city[16]; //城市名称
  28. char weather[32]; //天气介绍(多云...)
  29. char temp[16]; //温度
  30. char udate[32]; //更新时间
  31. };
  32. WeatherData weatherData;
  33. void sendNTPpacket(IPAddress &address);
  34. time_t getNtpTime();
  35. void getCityWeater();
  36. /**********************************************
  37. * 加载进度条
  38. *
  39. ***********************************************/
  40. int loadNum = 1; // 进度条长度 初始1
  41. int maxLoad = 147; // 进度条最大长度
  42. void loading(int num)
  43. {
  44. clk.setColorDepth(8);
  45. clk.createSprite(160, 80); // 创建布局大小 宽x高 0.96寸ttf 80x160 tft.int() 后设置方向
  46. tft.setRotation(1);
  47. clk.fillSprite(TFT_BLACK); // 布局背景颜色
  48. clk.drawRoundRect(5, 40, 150, 16, 6, TFT_WHITE); // 画进度条外边 (x方向5, y方向40, 长度150(左右边距5,总长度160), 高度16 , 圆角6 , 白色)
  49. clk.fillRoundRect(7, 42, loadNum, 12, 5, TFT_WHITE); // 画进度条填充 (x方向7, y方向42, 长度loadNum, 高度12 , 圆角5 , 白色)设置的坐标位置和长度在外边内
  50. clk.setTextColor(TFT_GREEN, TFT_BLACK); // 设置字体颜色背景
  51. clk.drawCentreString("Connecting to WiFi", 80, 20, 1); // 设置字体居中显示
  52. clk.pushSprite(0, 0); // 布局坐标
  53. clk.deleteSprite();
  54. if (loadNum < maxLoad) // 值小于最大值 +1
  55. loadNum += 1;
  56. delay(1);
  57. if (loadNum < num) // 值小于设定值 继续执行
  58. loading(num);
  59. }
  60. // wifi连接
  61. void wifiConnect()
  62. {
  63. Serial.print("Connecting");
  64. // while (WiFi.status() != WL_CONNECTED)
  65. while (wifis.run() != WL_CONNECTED)
  66. {
  67. digitalWrite(D0, LOW);
  68. delay(250);
  69. Serial.print(".");
  70. digitalWrite(D0, HIGH);
  71. delay(250);
  72. }
  73. Serial.println();
  74. Serial.print("Connected, IP address: ");
  75. Serial.println(WiFi.localIP());
  76. }
  77. /**************************
  78. * 太空人动画
  79. * x x轴,默认0
  80. * y y轴,默认0
  81. * dt 延时,默认60ms
  82. *
  83. * ***********************/
  84. void spaceAnimation(int x = 0, int y = 30, int dt = 60)
  85. {
  86. // TJpgDec.setJpgScale(2);
  87. TJpgDec.drawJpg(x, y, space_0, sizeof(space_0));
  88. delay(dt);
  89. TJpgDec.drawJpg(x, y, space_4, sizeof(space_4));
  90. delay(dt);
  91. TJpgDec.drawJpg(x, y, space_8, sizeof(space_8));
  92. delay(dt);
  93. TJpgDec.drawJpg(x, y, space_12, sizeof(space_12));
  94. delay(dt);
  95. TJpgDec.drawJpg(x, y, space_16, sizeof(space_16));
  96. delay(dt);
  97. TJpgDec.drawJpg(x, y, space_20, sizeof(space_20));
  98. delay(dt);
  99. TJpgDec.drawJpg(x, y, space_24, sizeof(space_24));
  100. delay(dt);
  101. TJpgDec.drawJpg(x, y, space_28, sizeof(space_28));
  102. delay(dt);
  103. TJpgDec.drawJpg(x, y, space_32, sizeof(space_32));
  104. delay(dt);
  105. TJpgDec.drawJpg(x, y, space_36, sizeof(space_36));
  106. delay(dt);
  107. TJpgDec.drawJpg(x, y, space_40, sizeof(space_40));
  108. delay(dt);
  109. TJpgDec.drawJpg(x, y, space_44, sizeof(space_44));
  110. delay(dt);
  111. TJpgDec.drawJpg(x, y, space_47, sizeof(space_47));
  112. delay(dt);
  113. }
  114. bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap)
  115. {
  116. if (y >= tft.height())
  117. return 0;
  118. tft.pushImage(x, y, w, h, bitmap);
  119. // Return 1 to decode next block
  120. return 1;
  121. }
  122. void digitalClockDisplay()
  123. {
  124. clk.setColorDepth(8);
  125. /***中间时间区***/
  126. byte xpos = 20;
  127. byte ypos = 4;
  128. //时分
  129. clk.createSprite(90, 32);
  130. clk.fillSprite(TFT_WHITE);
  131. clk.loadFont(TIME_32);
  132. clk.setTextColor(TFT_BLACK, TFT_WHITE);
  133. int hh = hour();
  134. if (hh < 10)
  135. xpos += clk.drawString("0", xpos, ypos);
  136. xpos += clk.drawNumber(hh, xpos, ypos);
  137. xpos += clk.drawString(":", xpos, ypos);
  138. int mm = minute();
  139. if (mm < 10)
  140. xpos += clk.drawString("0", xpos, ypos);
  141. clk.drawNumber(mm, xpos, ypos); //绘制时和分
  142. clk.unloadFont();
  143. clk.pushSprite(31, 25);
  144. clk.deleteSprite();
  145. //秒
  146. clk.createSprite(40, 20);
  147. clk.fillSprite(TFT_WHITE);
  148. clk.loadFont(TIME_20);
  149. clk.setTextColor(TFT_BLACK, TFT_WHITE);
  150. int seconds = second();
  151. String secondStr = (seconds < 10 ? "0" : "") + String(seconds);
  152. clk.drawString(secondStr, 5, 0);
  153. clk.unloadFont();
  154. clk.pushSprite(120, 36);
  155. clk.deleteSprite();
  156. /***中间时间区***/
  157. /***顶部***/
  158. clk.loadFont(DATE_18);
  159. String weeks[7] = {"日", "一", "二", "三", "四", "五", "六"};
  160. String week = " 周" + weeks[weekday() - 1];
  161. //年月日 星期
  162. clk.createSprite(160, 22);
  163. clk.fillSprite(TFT_WHITE);
  164. clk.setTextColor(TFT_BLACK, TFT_WHITE);
  165. String str = String(year()) + "年" + String(month()) + "月" + String(day()) + "日" + week;
  166. clk.drawString(str, 2, 4);
  167. clk.unloadFont();
  168. clk.pushSprite(0, 0);
  169. clk.deleteSprite();
  170. /***顶部***/
  171. }
  172. void setup()
  173. {
  174. Serial.begin(9600);
  175. tft.init();
  176. tft.setRotation(1); // 屏幕旋转方向0-3 镜像 4-7
  177. tft.fillScreen(TFT_BLACK);
  178. pinMode(D0, OUTPUT);
  179. digitalWrite(D0, HIGH);
  180. // wifi 配置 可添加多个
  181. wifis.addAP("wifi名称", "密码");
  182. wifis.addAP("wifi名称", "密码");
  183. loading(60); // 进度条加载到60
  184. if (wifis.run() == WL_CONNECTED)
  185. {
  186. Serial.println("connected wifi");
  187. loading(100); //进度条加载完成
  188. Udp.begin(localPort);
  189. setSyncProvider(getNtpTime);
  190. setSyncInterval(300);
  191. loading(maxLoad); //进度条加载完成
  192. tft.fillScreen(TFT_WHITE);
  193. TJpgDec.setJpgScale(1);
  194. TJpgDec.setSwapBytes(true);
  195. TJpgDec.setCallback(tft_output);
  196. tft.drawLine(30, 22, 30, 80, TFT_BLACK);
  197. tft.drawFastHLine(0, 22, 160, TFT_BLACK);
  198. tft.drawFastHLine(30, 57, 130, TFT_BLACK);
  199. weatherTime = millis();
  200. getCityWeater();
  201. }
  202. else
  203. {
  204. }
  205. }
  206. void loop()
  207. {
  208. digitalClockDisplay();
  209. if (millis() - weatherTime > 300000)
  210. { // 5分钟更新一次天气
  211. weatherTime = millis();
  212. getCityWeater();
  213. }
  214. spaceAnimation();
  215. // scale.power_up();
  216. }
  217. /*-------- NTP code ----------*/
  218. const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
  219. byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming & outgoing packets
  220. time_t getNtpTime()
  221. {
  222. IPAddress ntpServerIP; // NTP server's ip address
  223. while (Udp.parsePacket() > 0)
  224. ; // discard any previously received packets
  225. Serial.println("Transmit NTP Request");
  226. // get a random server from the pool
  227. WiFi.hostByName(ntpServerName, ntpServerIP);
  228. Serial.print(ntpServerName);
  229. Serial.print(": ");
  230. Serial.println(ntpServerIP);
  231. sendNTPpacket(ntpServerIP);
  232. uint32_t beginWait = millis();
  233. while (millis() - beginWait < 1500)
  234. {
  235. int size = Udp.parsePacket();
  236. if (size >= NTP_PACKET_SIZE)
  237. {
  238. Serial.println("Receive NTP Response");
  239. Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
  240. unsigned long secsSince1900;
  241. // convert four bytes starting at location 40 to a long integer
  242. secsSince1900 = (unsigned long)packetBuffer[40] << 24;
  243. secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  244. secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  245. secsSince1900 |= (unsigned long)packetBuffer[43];
  246. return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  247. }
  248. }
  249. Serial.println("No NTP Response :-(");
  250. return 0; // return 0 if unable to get the time
  251. }
  252. // send an NTP request to the time server at the given address
  253. void sendNTPpacket(IPAddress &address)
  254. {
  255. // set all bytes in the buffer to 0
  256. memset(packetBuffer, 0, NTP_PACKET_SIZE);
  257. // Initialize values needed to form NTP request
  258. // (see URL above for details on the packets)
  259. packetBuffer[0] = 0b11100011; // LI, Version, Mode
  260. packetBuffer[1] = 0; // Stratum, or type of clock
  261. packetBuffer[2] = 6; // Polling Interval
  262. packetBuffer[3] = 0xEC; // Peer Clock Precision
  263. // 8 bytes of zero for Root Delay & Root Dispersion
  264. packetBuffer[12] = 49;
  265. packetBuffer[13] = 0x4E;
  266. packetBuffer[14] = 49;
  267. packetBuffer[15] = 52;
  268. // all NTP fields have been given values, now
  269. // you can send a packet requesting a timestamp:
  270. Udp.beginPacket(address, 123); // NTP requests are to port 123
  271. Udp.write(packetBuffer, NTP_PACKET_SIZE);
  272. Udp.endPacket();
  273. }
  274. bool parseUserData(String content, struct WeatherData *weatherData)
  275. {
  276. // -- 根据我们需要解析的数据来计算JSON缓冲区最佳大小
  277. // 如果你使用StaticJsonBuffer时才需要
  278. // const size_t BUFFER_SIZE = 1024;
  279. // 在堆栈上分配一个临时内存池
  280. // StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  281. // -- 如果堆栈的内存池太大,使用 DynamicJsonBuffer jsonBuffer 代替
  282. DynamicJsonDocument doc(1024);
  283. auto error = deserializeJson(doc, content);
  284. if (error)
  285. {
  286. Serial.print(F("deserializeJson() failed with code "));
  287. Serial.println(error.c_str());
  288. return false;
  289. }
  290. JsonObject obj = doc.as<JsonObject>();
  291. //复制我们感兴趣的字符串
  292. strcpy(weatherData->city, obj["results"][0]["location"]["name"]);
  293. strcpy(weatherData->weather, obj["results"][0]["now"]["text"]);
  294. strcpy(weatherData->temp, obj["results"][0]["now"]["temperature"]);
  295. strcpy(weatherData->udate, obj["results"][0]["last_update"]);
  296. // -- 这不是强制复制,你可以使用指针,因为他们是指向“内容”缓冲区内,所以你需要确保
  297. // 当你读取字符串时它仍在内存中
  298. return true;
  299. }
  300. // 获取城市天气
  301. void getCityWeater()
  302. {
  303. //创建 HTTPClient 对象
  304. HTTPClient httpClient;
  305. // https 请求报400
  306. httpClient.begin(espClient, "api.seniverse.com", 80, "/v3/weather/now.json?key=Sy_3POubsgptOeUau&location=wenzhou&language=zh-Hans&unit=c", false);
  307. //启动连接并发送HTTP请求
  308. int httpCode = httpClient.GET();
  309. Serial.print("request weather data:");
  310. //如果服务器响应OK则显示
  311. if (httpCode == HTTP_CODE_OK)
  312. {
  313. Serial.println("request weather data success");
  314. String response = httpClient.getString();
  315. if (parseUserData(response, &weatherData))
  316. { //解析响应内容
  317. clk.createSprite(125, 22);
  318. clk.loadFont(WEATHER_16);
  319. clk.fillSprite(TFT_WHITE);
  320. clk.setTextColor(TFT_BLACK, TFT_WHITE);
  321. byte xpos = 3, ypos = 2;
  322. xpos += clk.drawString(weatherData.city, xpos, ypos);
  323. xpos += 4;
  324. xpos += clk.drawString(weatherData.weather, xpos, ypos);
  325. xpos += 5;
  326. clk.setTextColor(TFT_RED, TFT_WHITE);
  327. String temp = String(weatherData.temp) + "℃";
  328. xpos += clk.drawString(temp, xpos, ypos);
  329. clk.pushSprite(31, 62);
  330. clk.deleteSprite();
  331. }
  332. }
  333. else
  334. {
  335. Serial.print("request weather data fail:");
  336. Serial.println(httpCode);
  337. }
  338. httpClient.end(); //关闭ESP8266与服务器连接
  339. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/553460
推荐阅读
相关标签
  

闽ICP备14008679号