找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 2827|回复: 0
收起左侧

【零知ESP8266教程】快速入门18 ESP8266HTTPClient库 获取天气请求

[复制链接]
ID:349555 发表于 2019-10-31 11:47 | 显示全部楼层 |阅读模式

上次我们一起学习用ESP8266开发板创建一个热点,即发送射频信号,就像自己的智能手机可以打开热点,使得他人连接,我们智能手机的角色就是向外发送射频信号,然而,用自己的手机去连接WiFi,那手机充当的角色就是接收射频信号的啦。。

同理,零知ESP8266开发板是WiFi模块,既然有发送信号的功能(创建热点),当然也有接收信号的功能。这次的分享我们来让ESP8266开发板接收信息,一起开始实现吧。
一、硬件
电脑,windows系统
零知ESP8266开发板
micro-usb线
二、
(1)软件库:
本示例使用零知-ESP8266来获取天气信息,首先需要安装库:

0.0.jpg

也可以在GitHub下载,注意要下载5.~版本

(2)解压,然后打开零知开源软件,界面如下:

0.png

(3)安装到库

1.png

2.png

3.png

也可以解压直接复制到你lingzhi_library存放的位置

这样就完成安装了,届时要记得刷新一下,关闭软件。

三、
重新打开零知开源软件,然后烧录以下代码:

  1. <font color="rgb(77, 77, 77)"><font face="&quot;"><font style="font-size: 16px">/**
  2. * Demo:
  3. *    演示Http请求天气接口信息
  4. * @author 云上上云
  5. * @date 2019/06/01
  6. */
  7. #include <ESP8266WiFi.h>
  8. #include <ArduinoJson.h>
  9. #include <ESP8266HTTPClient.h>

  10. //以下三个定义为调试定义
  11. #define DebugBegin(baud_rate)    Serial.begin(baud_rate)
  12. #define DebugPrintln(message)    Serial.println(message)
  13. #define DebugPrint(message)    Serial.print(message)

  14. const char* AP_SSID     = "**********";         //  **********-- 使用时请修改为当前你的 wifi ssid
  15. const char* AP_PSK = "**********";         //  **********-- 使用时请修改为当前你的 wifi 密码
  16. const char* HOST = "http://api点seniverse<font color="rgb(77, 77, 77)"><font face="&quot;">点</font></font>com";
  17. const char* APIKEY = "wcmquevztdy1jpca";        //API KEY
  18. const char* CITY = "shenzhen";
  19. const char* LANGUAGE = "zh-Hans";//zh-Hans 简体中文  会显示乱码

  20. const unsigned long BAUD_RATE = 115200;                   // serial connection speed
  21. const unsigned long HTTP_TIMEOUT = 5000;               // max respone time from server

  22. // 我们要从此网页中提取的数据的类型
  23. struct WeatherData {
  24.   char city[16];//城市名称
  25.   char weather[32];//天气介绍(多云...)
  26.   char temp[16];//温度
  27.   char udate[32];//更新时间
  28. };

  29. HTTPClient http;
  30. String GetUrl;
  31. String response;
  32. WeatherData weatherData;

  33. void setup() {
  34.   // put your setup code here, to run once:
  35.   WiFi.mode(WIFI_STA);     //设置esp8266 工作模式
  36.   DebugBegin(BAUD_RATE);
  37.   DebugPrint("Connecting to ");//
  38.   DebugPrintln(AP_SSID);
  39.   WiFi.begin(AP_SSID, AP_PSK);   //连接wifi
  40.   WiFi.setAutoConnect(true);
  41.   while (WiFi.status() != WL_CONNECTED) {
  42.     //这个函数是wifi连接状态,返回wifi链接状态
  43.     delay(500);
  44.     DebugPrint(".");
  45.   }
  46.   DebugPrintln("");
  47.   DebugPrintln("WiFi connected");
  48.   DebugPrintln("IP address: " + WiFi.localIP());

  49.   //拼接get请求url  
  50.   GetUrl = String(HOST) + "/v3/weather/now.json?key=";
  51.   GetUrl += APIKEY;
  52.   GetUrl += "&location=";
  53.   GetUrl += CITY;
  54.   GetUrl += "&language=";
  55.   GetUrl += LANGUAGE;
  56.   //设置超时
  57.   http.setTimeout(HTTP_TIMEOUT);
  58.   //设置请求url
  59.   http.begin(GetUrl);
  60.   //以下为设置一些头  其实没什么用 最重要是后端服务器支持
  61.   http.setUserAgent("esp8266");//用户代理版本
  62.   http.setAuthorization("esp8266","yssy");//用户校验信息
  63. }

  64. void loop() {
  65.   //心知天气  发送http  get请求
  66.   int httpCode = http.GET();
  67.   if (httpCode > 0) {
  68.       Serial.printf("[HTTP] GET... code: %d\n", httpCode);
  69.       //判断请求是否成功
  70.       if (httpCode == HTTP_CODE_OK) {
  71.         //读取响应内容
  72.         response = http.getString();
  73.         DebugPrintln("Get the data from Internet!");
  74.         DebugPrintln(response);
  75.         //解析响应内容
  76.         if (parseUserData(response, &weatherData)) {
  77.           //打印响应内容
  78.           printUserData(&weatherData);
  79.         }
  80.       }
  81.   } else {
  82.       Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  83.   }
  84.   http.end();
  85.   delay(1000);//每1s调用一次
  86. }

  87. /**
  88. * @Desc 解析数据 Json解析
  89. * 数据格式如下:
  90. * {
  91. *    "results": [
  92. *        {
  93. *            "location": {
  94. *                "id": "WX4FBXXFKE4F",
  95. *                "name": "北京",
  96. *                "country": "CN",
  97. *                "path": "北京,北京,中国",
  98. *                "timezone": "Asia/Shanghai",
  99. *                "timezone_offset": "+08:00"
  100. *            },
  101. *            "now": {
  102. *                "text": "多云",
  103. *                "code": "4",
  104. *                "temperature": "23"
  105. *            },
  106. *            "last_update": "2017-09-13T09:51:00+08:00"
  107. *        }
  108. *    ]
  109. *}
  110. */
  111. bool parseUserData(String content, struct WeatherData* weatherData) {
  112. //    -- 根据我们需要解析的数据来计算JSON缓冲区最佳大小
  113. //   如果你使用StaticJsonBuffer时才需要
  114. //    const size_t BUFFER_SIZE = 1024;
  115. //   在堆栈上分配一个临时内存池
  116. //    StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  117. //    -- 如果堆栈的内存池太大,使用 DynamicJsonBuffer jsonBuffer 代替
  118.   DynamicJsonBuffer jsonBuffer;

  119.   JsonObject& root = jsonBuffer.parseObject(content);

  120.   if (!root.success()) {
  121.     DebugPrintln("JSON parsing failed!");
  122.     return false;
  123.   }

  124.   //复制我们感兴趣的字符串
  125.   strcpy(weatherData->city, root["results"][0]["location"]["name"]);
  126.   strcpy(weatherData->weather, root["results"][0]["now"]["text"]);
  127.   strcpy(weatherData->temp, root["results"][0]["now"]["temperature"]);
  128.   strcpy(weatherData->udate, root["results"][0]["last_update"]);
  129.   //  -- 这不是强制复制,你可以使用指针,因为他们是指向“内容”缓冲区内,所以你需要确保
  130.   //   当你读取字符串时它仍在内存中
  131.   return true;
  132. }

  133. // 打印从JSON中提取的数据
  134. void printUserData(const struct WeatherData* weatherData) {
  135.   DebugPrintln("Print parsed data :");
  136.   DebugPrint("City : ");
  137.   DebugPrint(weatherData->city);
  138.   DebugPrint(", \t");
  139.   DebugPrint("Weather : ");
  140.   DebugPrint(weatherData->weather);
  141.   DebugPrint(",\t");
  142.   DebugPrint("Temp : ");
  143.   DebugPrint(weatherData->temp);
  144.   DebugPrint(" C");
  145.   DebugPrint(",\t");
  146.   DebugPrint("Last Updata : ");
  147.   DebugPrint(weatherData->udate);
  148.   DebugPrintln("\r\n");
  149. }</font></font></font>
复制代码


2、验证,上传程序。

四、点击“调试”,就可看到结果啦,如下图:

4.png


回复

使用道具 举报

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

本版积分规则

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

Powered by 单片机教程网

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