给我一份ESP32连接RS485型气象多要素百叶箱数据上传本地数据库的代码并用中文注释
时间: 2024-05-16 12:16:32 浏览: 185
以下是ESP32连接RS485型气象多要素百叶箱数据上传本地数据库的代码,并且已加上中文注释:
```c++
// 引入必要的库
#include <SoftwareSerial.h>
#include <ModbusMaster.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <SPIFFS.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiAP.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiType.h>
#include <WiFiUdp.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Ticker.h>
#include <time.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <Preferences.h>
#include <HTTPUpdate.h>
#include <WiFiClientSecure.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
// 定义RS485通信所需的引脚
#define RXD2 16
#define TXD2 17
// 定义Modbus参数
#define DEVICE_ADDRESS 1
#define REGISTER_START_ADDRESS 0x00
#define REGISTER_QUANTITY 0x14
// 定义WiFi参数
#define WIFI_SSID "your-ssid"
#define WIFI_PASSWORD "your-password"
// 定义数据库参数
#define DB_HOST "your-db-host"
#define DB_PORT 3306
#define DB_USER "your-db-user"
#define DB_PASSWORD "your-db-password"
#define DB_NAME "your-db-name"
// 实例化ModbusMaster对象和SoftwareSerial对象
ModbusMaster node(1);
SoftwareSerial RS485(RXD2, TXD2);
// 实例化BME280对象和OneWire对象
Adafruit_BME280 bme;
OneWire oneWire(18);
// 实例化DallasTemperature对象
DallasTemperature sensors(&oneWire);
// 定义变量
float temperature;
float pressure;
float humidity;
float wind_direction;
float wind_speed;
float rain;
String current_time;
String ntp_server = "cn.ntp.org.cn";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, ntp_server.c_str(), 8 * 3600, 60000);
IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(114, 114, 114, 114);
bool isConnected = false;
// 实例化Ticker对象
Ticker timer;
// 实例化Preferences对象
Preferences preferences;
// 实例化WiFiClient对象和MySQL_Connection对象
WiFiClient client;
MySQL_Connection conn((Client *)&client);
void setup() {
Serial.begin(115200);
// 设置RS485通信的波特率
RS485.begin(9600, SWSERIAL_8N1, RXD2, TXD2, false, 256);
// 设置WiFi连接
WiFi.mode(WIFI_STA);
WiFi.setSleep(false);
WiFi.config(local_IP, gateway, subnet, dns);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.println("WiFi connected");
// 初始化SPIFFS文件系统
if (!SPIFFS.begin(true)) {
Serial.println("An error has occurred while mounting SPIFFS");
return;
}
// 设置BME280传感器
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
// 设置DallasTemperature传感器
sensors.begin();
// 设置定时器
timer.attach(10, getData);
// 设置NTPClient
timeClient.begin();
timeClient.update();
current_time = timeClient.getFormattedTime();
// 连接数据库
Serial.print("Connecting to database: ");
while (!conn.connect(DB_HOST, DB_PORT, DB_USER, DB_PASSWORD)) {
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.println("Database connected");
// 执行数据库操作
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
char sql[128];
sprintf(sql, "USE %s", DB_NAME);
cur_mem->execute(sql);
delete cur_mem;
}
void loop() {
if (!isConnected) {
Serial.println("WiFi disconnected, reconnecting...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
isConnected = true;
}
if (WiFi.status() == WL_CONNECTED) {
isConnected = false;
}
timeClient.update();
current_time = timeClient.getFormattedTime();
}
void getData() {
// 读取温度、气压和湿度
temperature = bme.readTemperature();
pressure = bme.readPressure() / 100.0F;
humidity = bme.readHumidity();
// 读取风向、风速和降雨量
node.clearResponseBuffer();
node.clearTransmitBuffer();
uint8_t result = node.readHoldingRegisters(REGISTER_START_ADDRESS, REGISTER_QUANTITY);
if (result == node.ku8MBSuccess) {
uint16_t wd = node.getResponseBuffer(0);
uint16_t ws = node.getResponseBuffer(1);
uint16_t rn = node.getResponseBuffer(5);
wind_direction = wd / 10.0;
wind_speed = ws / 10.0;
rain = rn / 10.0;
}
// 读取温度传感器的温度
sensors.requestTemperatures();
float soil_temperature = sensors.getTempCByIndex(0);
// 获取当前时间
timeClient.update();
current_time = timeClient.getFormattedTime();
Serial.println("Temperature: " + String(temperature));
Serial.println("Pressure: " + String(pressure));
Serial.println("Humidity: " + String(humidity));
Serial.println("Wind direction: " + String(wind_direction));
Serial.println("Wind speed: " + String(wind_speed));
Serial.println("Rain: " + String(rain));
Serial.println("Soil temperature: " + String(soil_temperature));
// 将数据插入数据库
if (conn.connected()) {
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
char sql[256];
sprintf(sql, "INSERT INTO data (time, temperature, pressure, humidity, wind_direction, wind_speed, rain, soil_temperature) VALUES ('%s', %f, %f, %f, %f, %f, %f, %f)", current_time.c_str(), temperature, pressure, humidity, wind_direction, wind_speed, rain, soil_temperature);
cur_mem->execute(sql);
delete cur_mem;
}
}
```
注:该代码使用了多个库,需要在IDE中下载并安装这些库,以确保代码的正确运行。
阅读全文