ESP32 arduino下用preferences库实现将SSID 密码 IP网关TCP服务器和端口等数据存入结构体并存入flash中,开机时自动读取并连接TCP服务器
时间: 2024-03-17 14:41:43 浏览: 313
好的,这是一个比较具体的问题,我来一步一步地回答。
首先,你需要定义一个结构体来存储需要保存的数据,比如:
```c++
struct WifiConfig {
char ssid[32];
char password[64];
IPAddress ip;
IPAddress gateway;
uint16_t port;
};
```
这里的 `WifiConfig` 结构体包含了需要保存的 SSID、密码、IP、网关和 TCP 服务器端口等信息。
接下来,你需要使用 `Preferences` 库来将数据存入 Flash 中,代码如下:
```c++
#include <Preferences.h>
Preferences preferences;
void saveWifiConfig(WifiConfig wifiConfig) {
preferences.begin("wifi_config");
preferences.putString("ssid", wifiConfig.ssid);
preferences.putString("password", wifiConfig.password);
preferences.putBytes("ip", wifiConfig.ip, sizeof(IPAddress));
preferences.putBytes("gateway", wifiConfig.gateway, sizeof(IPAddress));
preferences.putUInt("port", wifiConfig.port);
preferences.end();
}
WifiConfig loadWifiConfig() {
preferences.begin("wifi_config");
WifiConfig wifiConfig;
strcpy(wifiConfig.ssid, preferences.getString("ssid", "").c_str());
strcpy(wifiConfig.password, preferences.getString("password", "").c_str());
preferences.getBytes("ip", wifiConfig.ip, sizeof(IPAddress));
preferences.getBytes("gateway", wifiConfig.gateway, sizeof(IPAddress));
wifiConfig.port = preferences.getUInt("port", 0);
preferences.end();
return wifiConfig;
}
```
这里使用了 `Preferences` 库的 `putString()`、`putBytes()`、`putUInt()`、`getString()`、`getBytes()` 和 `getUInt()` 方法将数据存入和读取出 Flash。需要注意的是,在 `putBytes()` 和 `getBytes()` 中,需要指定要保存的字节数,而在 `putUInt()` 和 `getUInt()` 中,需要指定要保存的整数类型。
最后,在开机时,你可以通过调用 `loadWifiConfig()` 函数将之前保存的数据读取出来,并连接 TCP 服务器,代码如下:
```c++
void setup() {
WifiConfig wifiConfig = loadWifiConfig();
WiFi.begin(wifiConfig.ssid, wifiConfig.password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
}
WiFi.config(wifiConfig.ip, wifiConfig.gateway);
WiFiClient client;
client.connect(wifiConfig.ip, wifiConfig.port);
}
```
这里使用了 `WiFi` 库连接 WiFi 和 TCP 服务器,需要注意的是,在连接 WiFi 和 TCP 服务器前,需要先调用 `WiFi.config()` 方法设置 IP 和网关。
阅读全文