[原创] 【Beetle ESP32 C6迷你开发板】+通过网络获取天气信息

流水源   2024-5-20 15:08 楼主

ESP32-C6支持很多无线通信协议,下面就通过wifi获取天气信息。

本次获取天气使用的是心知天气服务。使用该服务需要注册心知天气账号,获取个人使用的API KEY。

下面是获取天气的接口:

image.png  

也可以获取3天内的天气(免费版):

image.png  

下面就是代码实现了。首先就是需要WIFI,JSON,和HTTPClient库支持。

#include <WiFi.h>
#include <Arduino_JSON.h>
#include <HTTPClient.h>

const char *ssid = "SSID";  //WIFI名称
const char *pwd  = "PWD";      //WIFI密码
//填入你获得的API Key
String openWeatherMapApiKey = "API KEY";

//String http_api_str = "https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c" //now
//返回例子
//{"results":[
//{"location":{"id":"WX4FBXXFKE4F","name":"北京","country":"CN","path":"北京,北京,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},
//"now":{"text":"晴","code":"0","temperature":"22"},"last_update":"2024-05-20T10:22:03+08:00"}
//]}

//3Day    https://api.seniverse.com/v3/weather/daily.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c&start=0&days=3
//返回例子
//{"results":
//[{"location":{"id":"WS0E9D8WN298","name":"广州","country":"CN","path":"广州,广州,广东,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},
//"daily":[
//    {"date":"2024-05-20","text_day":"大雨","code_day":"15","text_night":"雷阵雨","code_night":"11","high":"25","low":"21","rainfall":"29.50","precip":"0.92","wind_direction":"东","wind_direction_degree":"90","wind_speed":"23.4","wind_scale":"4","humidity":"91"},
//    {"date":"2024-05-21","text_day":"雷阵雨","code_day":"11","text_night":"雷阵雨","code_night":"11","high":"27","low":"21","rainfall":"1.29","precip":"0.24","wind_direction":"无持续风向","wind_direction_degree":"","wind_speed":"8.4","wind_scale":"2","humidity":"87"},
//    {"date":"2024-05-22","text_day":"雷阵雨","code_day":"11","text_night":"雷阵雨","code_night":"11","high":"28","low":"24","rainfall":"0.88","precip":"0.22","wind_direction":"无持续风向","wind_direction_degree":"","wind_speed":"3.0","wind_scale":"1","humidity":"91"}],
//"last_update":"2024-05-20T08:00:00+08:00"}
//]}

获取天气服务的JSON数据。 

//获取天气JSON数据
String httpGETRequest(const char* serverName) 
{
    WiFiClient client;
    HTTPClient http;
    //连接网址
    http.begin(client, serverName);
    //发送HTTP站点请求
    int httpResponseCode = http.GET();
    //该数组用于储存获得的数据
    String payload = "{}";
    //将获得的数据放入数组
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      payload = http.getString();
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    //释放资源
    http.end();
    //返回获得的数据用于Json处理
    return payload;
}

初始化连接WIFI热点:


  WiFi.mode(WIFI_MODE_STA);
  Serial.println(WiFi.macAddress());
  WiFi.begin(ssid, pwd);
  while (WiFi.status() != WL_CONNECTED)
  {
      delay(500);
      Serial.print(".");
  }
  Serial.println("WiFi connected!");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

定时循环获取天气信息:

  //发送HTTP获取请求
  if ((millis() - lastTime) > timerDelay) 
  {
    timerDelay = 60000;
    //检测WIFI是否已经连接
    if(WiFi.status()== WL_CONNECTED)
    {
      String serverPath = "http://api.seniverse.com/v3/weather/now.json?key=" + openWeatherMapApiKey + "&location=" + city + "&language=en&unit=c";

      Serial.println("=======================================================================");
      //将组合好的URL放入httpGETRequest函数中通过HTTP获取请求以获得文本
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      //将解析的Json对象值储存在Jsonu缓冲区中
      JSONVar myObject = JSON.parse(jsonBuffer);
      //判断解析是否成功
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
      
      Serial.println("=======================================================================");
//      Serial.print("JSON object = ");
//      Serial.println(myObject);
      Serial.print("Weather: ");
      Serial.println(myObject["results"][0]["now"]["text"]);
      Serial.print("Code: ");
      Serial.println(myObject["results"][0]["now"]["code"]);
      Serial.print("Temperature: ");
      Serial.println(myObject["results"][0]["now"]["temperature"]);
      
      Serial.println("=======================================================================");
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }

下面是打印输出的天气信息:

image.png  

整体代码如下:


#include <WiFi.h>
#include <Wire.h>
#include <Arduino_JSON.h>
#include <HTTPClient.h>
#include <RPR-0521RS.h>
#include <shtc3.h>


RPR0521RS rpr0521rs;
SHTC3     d_shtc3;

#define myLED 15 //设置引脚15为LED引脚

const char *ssid = "SSID";  //WIFI名称
const char *pwd  = "PWD";      //WIFI密码
//填入你获得的API Key
String openWeatherMapApiKey = "API KEY";//你的心知天气API KEY

//String http_api_str = "https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c" //now
//返回例子
//{"results":[
//{"location":{"id":"WX4FBXXFKE4F","name":"北京","country":"CN","path":"北京,北京,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},
//"now":{"text":"晴","code":"0","temperature":"22"},"last_update":"2024-05-20T10:22:03+08:00"}
//]}

//3Day    https://api.seniverse.com/v3/weather/daily.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c&start=0&days=3
//返回例子
//{"results":
//[{"location":{"id":"WS0E9D8WN298","name":"广州","country":"CN","path":"广州,广州,广东,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},
//"daily":[
//    {"date":"2024-05-20","text_day":"大雨","code_day":"15","text_night":"雷阵雨","code_night":"11","high":"25","low":"21","rainfall":"29.50","precip":"0.92","wind_direction":"东","wind_direction_degree":"90","wind_speed":"23.4","wind_scale":"4","humidity":"91"},
//    {"date":"2024-05-21","text_day":"雷阵雨","code_day":"11","text_night":"雷阵雨","code_night":"11","high":"27","low":"21","rainfall":"1.29","precip":"0.24","wind_direction":"无持续风向","wind_direction_degree":"","wind_speed":"8.4","wind_scale":"2","humidity":"87"},
//    {"date":"2024-05-22","text_day":"雷阵雨","code_day":"11","text_night":"雷阵雨","code_night":"11","high":"28","low":"24","rainfall":"0.88","precip":"0.22","wind_direction":"无持续风向","wind_direction_degree":"","wind_speed":"3.0","wind_scale":"1","humidity":"91"}],
//"last_update":"2024-05-20T08:00:00+08:00"}
//]}

const char *ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 8 * 3600;
const int daylightOffset_sec = 0;

// 填写城市名以及国家简写
String city = "GuangZhou";
String jsonBuffer;
unsigned long lastTime = 0;
//设置每10分钟获得一次天气数据
unsigned long timerDelay = 10000;

//打印时间
void printLocalTime()
{
    struct tm timeinfo;
    if (!getLocalTime(&timeinfo))
    {
        Serial.println("Failed to obtain time");
        return;
    }
    Serial.println(&timeinfo, "%F %T %A"); // 格式化输出
}

//获取天气JSON数据
String httpGETRequest(const char* serverName) 
{
    WiFiClient client;
    HTTPClient http;
    //连接网址
    http.begin(client, serverName);
    //发送HTTP站点请求
    int httpResponseCode = http.GET();
    //该数组用于储存获得的数据
    String payload = "{}";
    //将获得的数据放入数组
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      payload = http.getString();
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    //释放资源
    http.end();
    //返回获得的数据用于Json处理
    return payload;
}

//====================================================================================================================================================
void setup() 
{
  byte rc;
  pinMode(myLED, OUTPUT);
  digitalWrite(myLED, HIGH);
  Serial.begin(115200);
  Serial.println("******************************** senser test *******************************************");
  //set the resolution to 12 bits (0-4096)
  analogReadResolution(12);
  
  Wire.begin();
  rc = rpr0521rs.init();
  Serial.print(F("RPR-0521RS Init = "));
  Serial.println(rc);

  rc = d_shtc3.Init();
  Serial.print(F("SHTC3 Init = "));
  Serial.println(rc);

  WiFi.mode(WIFI_MODE_STA);
  Serial.println(WiFi.macAddress());
  WiFi.begin(ssid, pwd);
  while (WiFi.status() != WL_CONNECTED)
  {
      delay(500);
      Serial.print(".");
  }
  Serial.println("WiFi connected!");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  // 从网络时间服务器上获取并设置时间
  // 获取成功后芯片会使用RTC时钟保持时间的更新
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();
  lastTime = millis();
}

//====================================================================================================================================================
void loop() 
{
  byte rc;
  byte near_far;
  unsigned short ps_val;
  float als_val;
  int temp;
  int rh;

  digitalWrite(myLED, HIGH);
  delay(100);
  printLocalTime();
  Serial.println("----------------------------------------");
  // read the analog / millivolts value for pin 2:
  int analogValue = analogRead(0);
  int analogVolts = analogReadMilliVolts(0);
  // print out the values you read:
  Serial.print("ADC analog value = ");
  Serial.println(analogValue);
  Serial.print("ADC millivolts value = ");
  Serial.print(analogVolts);
  Serial.println("mV");
  // Please adjust the calculation coefficient according to the actual measurement.
  Serial.print("BAT millivolts value = ");
  Serial.print(analogVolts * 2.1218 + 1000);
  Serial.println("mV");
  Serial.println("----------------------------------------");
  delay(100);
  
  rc = rpr0521rs.get_psalsval(&ps_val, &als_val);
  if (rc == 0) {
    Serial.print(F("RPR-0521RS (Proximity)     = "));
    Serial.print(ps_val);
    near_far = rpr0521rs.check_near_far(ps_val);
    if (near_far == RPR0521RS_NEAR_VAL) {
      Serial.print(F(" Near,"));
    } else {
      Serial.print(F(" Far,"));
    }
    if (als_val != RPR0521RS_ERROR) {
      Serial.print(F("\t (Ambient Light) = "));
      Serial.print(als_val);
      Serial.println(F("[lx]."));
      
    }
  }
  delay(100);
  
  rc = d_shtc3.GetMode1_TempRH(&temp, &rh);
  if (rc == 0) {
    Serial.print(F("SHTC3 Temp = "));
    Serial.print(temp);
    Serial.print("^C,");
    Serial.print(F(" \t RH = "));
    Serial.print(rh);
    Serial.println("%");
    Serial.println();
  }
  
  digitalWrite(myLED, LOW);
  delay(800);

  //发送HTTP获取请求
  if ((millis() - lastTime) > timerDelay) 
  {
    timerDelay = 60000;
    //检测WIFI是否已经连接
    if(WiFi.status()== WL_CONNECTED)
    {
      String serverPath = "http://api.seniverse.com/v3/weather/now.json?key=" + openWeatherMapApiKey + "&location=" + city + "&language=en&unit=c";

      Serial.println("=======================================================================");
      //将组合好的URL放入httpGETRequest函数中通过HTTP获取请求以获得文本
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      //将解析的Json对象值储存在Jsonu缓冲区中
      JSONVar myObject = JSON.parse(jsonBuffer);
      //判断解析是否成功
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
      
      Serial.println("=======================================================================");
//      Serial.print("JSON object = ");
//      Serial.println(myObject);
      Serial.print("Weather: ");
      Serial.println(myObject["results"][0]["now"]["text"]);
      Serial.print("Code: ");
      Serial.println(myObject["results"][0]["now"]["code"]);
      Serial.print("Temperature: ");
      Serial.println(myObject["results"][0]["now"]["temperature"]);
      
//      Serial.print("Pressure: ");
//      //myObject["now"]["pressure"]前为{}前的引号内容,后为读取哪一个引号后数据
//      Serial.println(myObject["now"]["pressure"]);
//      Serial.print("Humidity: ");
//      Serial.println(myObject["now"]["humidity"]);
//      Serial.print("Wind Speed: ");
//      Serial.println(myObject["now"]["wind_speed"]);
      Serial.println("=======================================================================");
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

 

 

 

 

回复评论 (1)

楼主的测试,通过wifi获取天气信息还是比较成功的

点赞  2024-5-21 07:31
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复