基于ESP32-S2实现本地气象台/温度计
本项目使用Arduino开发环境,使用基于ESP32-S2-Mini-1模块的音频处理平台和板载OLED屏幕(ssd1306),设计了一个本地气象台/温度计。
标签
嵌入式系统
Arduino
测试
显示
网络与通信
ESP32-S2
2022寒假在家练
esp32小白
更新2022-03-01
金陵科技学院
955

开发板介绍

本次使用的开发板使用的是乐鑫的ESP32-S2-Mini-1模块,功能强大,具有丰富的外设接口,应用广泛芯片搭载了Xtensa® 32 位LX7 单核处理器,带有37个可编程GPIO口工作频率高达 240 MHz

功能实现

我完成的是项目6   制作一个本地气象台/温度计

  • 利用OLED显示
  • 显示当前本地的时间、温度和气象信息

按键操作

在第一个界面按下第二个、三个、四个键能够切换到第二个、三个、四个页面,再按下的一个键又会回到第一个页面。

代码实现框图

FtmiBuKQwoTUPkOki5PGMRr04Q6m

板卡设置

本次arduino开发环境搭建,我使用的是vscode编辑器代替arduino IDE。先在电脑上安装好arduino IDE,再在vscode的插件管理中搜索“arduino”,下载arduino插件。后在vscode的arduino configuration页面加入arduino安装目录,以配置好工具链。FkmZCn0lk-aKsyrMmOQ3mIOvLeLj

arduino自带板卡中没有esp32-s2板卡,所以要将官方板卡链接加入arduino设置。

https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

FrH607i8q-ab14PXqnAWp42oIy0C

在板卡参数设置界面按如下设置,在Partition Scheme中选择No OTA(2MB APP/2MB SPIFFS),否则可能会出现内存不足而报错。

Fh1i9NoTHUYMZxoSB8iqvzjabsTr

注:麻烦测试工程师把手机热点打开,WiFi账号改为 ssid,密码改为 password,即可连接WiFi

烧录

FvjffJ7fELR31UdJZnx_DD0Pp8Ho

代码分析

setup()入口函数下,首先初始化串口,初始化u8g2库,使能UTF8字符打印,初始化按键引脚,连接WiFi,WiFi连接期间在屏幕上显示几行字符和硬禾学堂和乐鑫的logo,增加高级感。

void setup() {
    Serial.begin(115200);
    u8g2.begin();
    u8g2.enableUTF8Print();

    // 初始化按键引脚
    pinMode(button_1,INPUT);
    pinMode(button_2,INPUT);
    pinMode(button_3,INPUT);
    pinMode(button_4,INPUT);

    WiFi.begin(ssid, password);
    Serial.println("Connecting");
    while(WiFi.status() != WL_CONNECTED) {// 未连接时
        u8g2.setFont(u8g2_font_micro_mr);
        u8g2.setCursor(0,6);
        u8g2.print("Initializing...");
        u8g2.sendBuffer();
        delay(1000);
        u8g2.setCursor(0,12);
        u8g2.print("Initialized successfully");
        u8g2.sendBuffer();
        delay(1000);
        u8g2.setCursor(0,18);
        u8g2.print("Loading...");
        u8g2.sendBuffer();
        delay(100);
        u8g2.drawXBMP(9 ,21 ,logo0_width ,logo0_height ,logo0_bits);
        u8g2.setFont(u8g2_font_wqy12_t_gb2312);
        u8g2.setCursor(9,63);
        u8g2.print("硬禾学堂");
        u8g2.drawXBMP(73 ,30 ,logo1_width ,logo1_height ,logo1_bits);
        delay(1000);
        u8g2.sendBuffer();
    }
    u8g2.clearBuffer();
    Serial.println("Connected");

    //init and get the time
    configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

    // update_ip_location();
    // printLocalInfo();

}

连接WiFi

ESP32-S2模块常被用做WiFi模块接入网络,所以WiFi连接方面较为成熟,也很简单。

#include <WiFi.h>

// WiFi账号密码
const char* ssid = "ssid";
const char* password = "password";

void setup(){
    WiFi.begin(ssid, password);
    Serial.println("Connecting");
}

校时

接入网络后,从互联网获取时间,在屏幕上显示。如果获取时间出错,则串口打印"Failed to obtain time",重新获取时间;否则说明时间正确,设置时区为“CST-8”,在屏幕上显示年月日时分秒具体时间,并把整个获取时间并显示的代码放入loop循环,重复刷屏显示秒的动态显示。

// 时间变量定义
const char* ntpServer = "edu.ntp.org.cn";
const long  gmtOffset_sec = 8*60*60;//东八区,UTC计时
const int   daylightOffset_sec = 8*60*60;//东八区,UTC计时

//init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

struct tm timeinfo;   //定义获取网络时间结构体 tm 变量 timeinfo
if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");

u8g2.setFont(u8g2_font_freedoomr25_tn);
u8g2.setCursor(5,47);
u8g2.print(&timeinfo,"%H:%M");
u8g2.setFont(u8g2_font_freedoomr10_tu);
u8g2.print(&timeinfo,"%S");

获取网络天气部分

本次获取天气使用的是高德地图API,每日免费访问量多达30万次,而且可以通过IP定位,可以实现在不同的城市实时更新相应的天气信息。

struct tm timeinfo;   //定义获取网络时间结构体 tm 变量 timeinfo
if(!getLocalTime(&timeinfo)){
        Serial.println("Failed to obtain time");
return;
}
// Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");

u8g2.setFont(u8g2_font_freedoomr25_tn);
u8g2.setCursor(5,47);
u8g2.print(&timeinfo,"%H:%M");
u8g2.setFont(u8g2_font_freedoomr10_tu);
u8g2.print(&timeinfo,"%S");

解析JSON数据

使用Arduino_JSON库来解析从高德API获取的数据,用httpGETRequest()函数将数据存入变量jsonBuffer中,再用JSON.parse()函数将jsonBuffer中的数据转化为对应数组,方便提取信息。

// json变量定义
const char* province0;
const char* city0;
const char* weather0;
const char* weather1;
const char* weather2;
const char* weather3;
String temperature0;
String temperature1;
String temperature2;
String temperature3;
const char* winddirection0;
const char* winddirection1;
const char* winddirection2;
const char* winddirection3;
const char* date0;
const char* date1;
const char* date2;
const char* date3;
const char* date01;
const char* date11;
const char* date21;
const char* date31;
char date02[5]={'0'};
char date12[5]={'0'};
char date22[5]={'0'};
char date32[5]={'0'};
int week_num;
int flag = 0;
JSONVar myObject;
String city_code,key = "*******************************";
String jsonBuffer;
String ip_jsonBuffer;

String httpGETRequest(const char* serverName) 
{
    WiFiClient client;
    HTTPClient http;

    http.begin(client, serverName);

    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);
    }
    // Free resources
    http.end();

    return payload;
}

String serverPath = "http://restapi.amap.com/v3/weather/weatherInfo?city=" + city_code + "&key=" + key + "&extensions=all";

jsonBuffer = httpGETRequest(serverPath.c_str());

myObject = JSON.parse(jsonBuffer);

if (JSON.typeof(myObject) == "undefined")
{
    Serial.println("Parsing input failed!");
    return;
}
// 获取省份
province0 = myObject["forecasts"][0]["province"];
// 获取城市
city0 = myObject["forecasts"][0]["city"];
// 获取今日天气
weather0 = myObject["forecasts"][0]["casts"][0]["dayweather"];
// 获取今日温度
const char* temp0 = myObject["forecasts"][0]["casts"][0]["daytemp"];
String temp01 = temp0;
temperature0 = temp01 + "  C";
// 获取今日风向
winddirection0 = myObject["forecasts"][0]["casts"][0]["daywind"];
// 获取今日日期
date0 = myObject["forecasts"][0]["reporttime"];
date01 = &date0[5];
for(int k=0;k<5;k++){
    date02[k] = date01[k];
}

// 获取明日天气
weather1 = myObject["forecasts"][0]["casts"][1]["dayweather"];
// 获取明日温度
const char* temp1 = myObject["forecasts"][0]["casts"][1]["daytemp"];
String temp11 = temp1;
temperature1 = temp11 + "  C";
// 获取明日风向
winddirection1 = myObject["forecasts"][0]["casts"][1]["daywind"];
// 获取明日日期
date1 = myObject["forecasts"][0]["casts"][1]["date"];
date11 = &date1[5];

// 获取后日天气
weather2 = myObject["forecasts"][0]["casts"][2]["dayweather"];
// 获取后日温度
const char* temp2 = myObject["forecasts"][0]["casts"][2]["daytemp"];
String temp21 = temp2;
temperature2 = temp21 + "  C";
// 获取后日风向
winddirection2 = myObject["forecasts"][0]["casts"][2]["daywind"];
// 获取后日日期
date2 = myObject["forecasts"][0]["casts"][2]["date"];
date21 = &date2[5];

// 获取大后日天气
weather3 = myObject["forecasts"][0]["casts"][3]["dayweather"];
// 获取大后日温度
const char* temp3 = myObject["forecasts"][0]["casts"][3]["daytemp"];
String temp31 = temp3;
temperature3 = temp31 + "  C";
// 获取大后日风向
winddirection3 = myObject["forecasts"][0]["casts"][3]["daywind"];
// 获取大后日日期
date3 = myObject["forecasts"][0]["casts"][3]["date"];
date31 = &date3[5];

更新IP定位

通过使用高德API中的IP定位功能获取当地城市编码。

void update_ip_location(){
    String ip_location = "http://restapi.amap.com/v3/ip?key=" + key;

    ip_jsonBuffer = httpGETRequest(ip_location.c_str());

    JSONVar ip_myObject = JSON.parse(ip_jsonBuffer);

    if (JSON.typeof(ip_myObject) == "undefined") 
    {
        Serial.println("Parsing input failed!");
        return;
    }

    city_code = ip_myObject["adcode"];
}

切换页面

通过使用变量flag的不同值来判断当前的页面,在loop循环中重复检测按键状态,按下不同的按键则赋flag以不同的值。

if(digitalRead(button_1)||digitalRead(button_2)||digitalRead(button_3)||digitalRead(button_4) == 0){
    if(digitalRead(button_1) == 0){
        flag = 0;
    }else if(digitalRead(button_2) == 0){
        flag = 1;
    }else if(digitalRead(button_3) == 0){
        flag = 2;
    }else if(digitalRead(button_4) == 0){
        flag = 3;
    }
}

if(flag == 0){
    printLocalInfo();// 每显示一次,i++
}
if(flag == 1){
    printtomorrowInfo();
}
if(flag == 2){
    nexttomorrowInfo();
}
if(flag == 3){
    nextnexttomorrowInfo();
}

存在BUG

1.校时时间有长有短,一次校时不超过可以复位重启,未校时会一直处于校时状态,无法进入其他功能;

2. (现已修复) 之前可能出现屏幕部分内容显示不全、显示乱码、显示跳动等情况,令人头疼。但是我将原本定义在setup()函数中的 将json数据转化为数组的 JSONVar类型的myObject局部变量,定义为全局变量时,问题就解决了,还未能找出原因所在。

JSONVar myObject;
.
.
.
void setup(){
.
.
.
    myObject = JSON.parse(jsonBuffer);
.
.
.
}

结果展示

FqIkgzogCBL4oVoPgcbde8kqlBKLFg-ahx5CknJDlHaWzxn1Grob2h--FsXTAIlRQqOowhpb_p9fY3bIDik0

FkmA4dhyq_vIN8KLFYeYtL0cNzoRFushapZwzQ7huAXJ-tiPAJ9x8n4h

附件下载
weather_station.zip
全部代码,烧录时请将WiFi热点账号改为 ssid,密码改为 password,或在代码宏定义中把WiFi改成自己的
bin_result.zip
二进制代码(可直接烧录)weather_station.ino.bootloader.bin烧录至 0x1000 ;weather_station.ino.partitions.bin烧录至0x8000 ;weather_station.ino.bin烧录至0x10000
团队介绍
一名金陵科技学院信息工程专业的大二学生~
团队成员
esp32小白
评论
0 / 100
查看更多
目录
硬禾服务号
关注最新动态
0512-67862536
info@eetree.cn
江苏省苏州市苏州工业园区新平街388号腾飞创新园A2幢815室
苏州硬禾信息科技有限公司
Copyright © 2023 苏州硬禾信息科技有限公司 All Rights Reserved 苏ICP备19040198号