esp32 arduino 支持eeprom保存配置参数

完整代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#include <WiFi.h>
#include <WiFiUdp.h>
#include "WString.h"
#include "EEPROM.h"
 
void sendSerial1(String str, bool addline = true);
typedef void(*funcSlice)();
 
#define ROM_STRING_SIZE   16
#define ROM_INT_SIZE      4
 
enum TaskType
{
  TaskTypeLed,
  TaskTypeParse,
  TaskTypeSerialRecv,
  TaskTypeUDPRecv,
  TaskTypeCount
};
 
enum Status
{
  LedStatusOff = HIGH,
  LedStatusOn = LOW
};
 
enum AddrEEProm
{
  AddressSSID,
  AddressPassword = AddressSSID + ROM_STRING_SIZE,
  AddressPeerHost = AddressPassword + ROM_STRING_SIZE,
  AddressPeerPort = AddressPeerHost + ROM_STRING_SIZE,
  AddressCount = AddressPeerPort + ROM_INT_SIZE
};
 
struct GlobalParam
{
  uint32_t chipId;
  uint32_t uruntimemsec;
  uint32_t uledPin;
  uint32_t uledValue;
  uint16_t uUdpPort;
  bool bLedBlink;
  bool wifiConnected;
 
  String udpPeerHost;
  uint16_t udpPeerPort;
 
  String strCache;
  String strWifissid;
  String strWifiPassword;
};
 
struct ProgramBlock
{
  uint32_t runLast;
  uint32_t runSlice;
  funcSlice func;
};
 
int pinsda = GPIO_ID_PIN(0);
int pinscl = GPIO_ID_PIN(4);
ProgramBlock pb[TaskTypeCount] = {0};
GlobalParam param = {0};
//The udp library class
WiFiUDP udp;
EEPROMClass romflash("rom", AddressCount);
 
void showUsage()
{
  Serial.println("============== menu ==============");
  Serial.println("?: help menu");
  Serial.println("s: status info");
  sendSerial1("reboot: reboot device");
  sendSerial1("ssid=xxxx:save wifi ssid");
  sendSerial1("password=xxxx:save wifi password"); 
  sendSerial1("remhost=xxxx:save udp peer host"); 
  sendSerial1("remport=xxxx:save udp peer port"); 
  Serial.println("==================================");
}
 
void showStatus()
{
    Serial.println("=============== status =============");
    Serial.printf("chip Id:%d\n", param.chipId);
    Serial.print("wifi connected:");
    Serial.println(param.wifiConnected);
    Serial.print("local ip:");
    Serial.println(WiFi.localIP());
    // Serial.printf("has run time(misecs):%d\n", param.uruntimemsec);
    Serial.print("led blink:");
    Serial.println(param.bLedBlink);
    String str;
    str = "ssid:" + param.strWifissid;
    sendSerial1(str);
 
    str = "password:" + param.strWifiPassword;
    sendSerial1(str);
 
    str = "has run:" + timeFormat();
    sendSerial1(str);
 
    Serial.printf("udp listen port:%d\n", param.uUdpPort);
    Serial.print("udp peer host:");
    Serial.println(param.udpPeerHost);
    Serial.printf("udp peer port:%d\n", param.udpPeerPort);
    Serial.println("====================================");
}
 
String timeFormat()
{
  int secs = param.uruntimemsec / 1000;
  int nday = 24*3600;
  String str;
  int day = secs / (nday);
  if(day > 0)
  {
    str += day;
    str += "d ";
  }
  int hor = secs % nday;
  int h = hor/3600;
  if(h){
    str += h;
    str += "h ";
  }
  hor = hor % 3600;
  int m = hor /60;
  if(m)
  {
    str += m;
    str += "m ";
  }
  int s = hor % 60;
  if(s)
  {
    str += s;
    str += "s";
  }
  str += "(";
  str += secs;
  str += "secs)";
  return str;
}
 
void initUDP()
{
  param.uUdpPort = 10888;
  udp.begin(param.uUdpPort);
}
 
void initEEPRom()
{
    char buf[ROM_STRING_SIZE] = {0};
    if(!romflash.begin(romflash.length()))
    {
      sendSerial1("failed to init eeprom wifissid");
    }else {
      memset(buf, 0, ROM_STRING_SIZE);
      int ret = romflash.readString(AddressSSID, buf, ROM_STRING_SIZE);
      param.strWifissid = buf;
 
      memset(buf, 0, ROM_STRING_SIZE);
      ret = romflash.readString(AddressPassword, buf, ROM_STRING_SIZE);
      param.strWifiPassword = buf;
 
      memset(buf, 0, ROM_STRING_SIZE);
      ret = romflash.readString(AddressPeerHost, buf, ROM_STRING_SIZE);
      param.udpPeerHost = buf;
 
      param.udpPeerPort = romflash.readInt(AddressPeerPort);
    }
}
 
void sendUDP(String str)
{
  udp.beginPacket(param.udpPeerHost.c_str(), param.udpPeerPort);
    udp.println(str);
    udp.endPacket();
}
 
void sendSerial1(String str, bool addline)
{
  if(addline)
  {
      Serial.println(str);
  }else {
      Serial.print(str);
  }
     
}
 
void WiFiEvent(WiFiEvent_t event){
    switch(event) {
      case SYSTEM_EVENT_STA_GOT_IP:
          //When connected set
          Serial.print("WiFi connected! IP address: ");
          Serial.println(WiFi.localIP()); 
          //initializes the UDP state
          //This initializes the transfer buffer
          // udp.begin(WiFi.localIP(),udpPort);
          param.wifiConnected = true;
          pb[TaskTypeLed].runSlice = 1000;
          param.bLedBlink = true;
          initUDP();
          break;
      case SYSTEM_EVENT_STA_DISCONNECTED:
          Serial.println("WiFi lost connection");
          param.wifiConnected = false;
          pb[TaskTypeLed].runSlice = 3000;
          param.bLedBlink = false;
          param.uledValue = LedStatusOff;
          break;
      default: break;
    }
}
 
void connectToWIFI()
{
  WiFi.disconnect(true);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(param.strWifissid.c_str(), param.strWifiPassword.c_str());
}
 
void getChipInfo()
{
  param.chipId = 0;
  for(int i=0; i<17; i=i+8) {
      param.chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
    }
  // Serial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());
    // Serial.printf("This chip has %d cores\n", ESP.getChipCores());
  // Serial.print("Chip ID: ");
  // Serial.println(chipId);
}
 
void taskLed()
{
  if(param.bLedBlink)
  {
    if(LedStatusOff == param.uledValue){
      param.uledValue = LedStatusOn;
    }else{
      param.uledValue = LedStatusOff;
    }
  }
  digitalWrite(param.uledPin, param.uledValue);
}
 
void taskParseData()
{
  while(param.strCache.length())
  {
      int index = param.strCache.indexOf('\n');
      if(index < 0){
        return;
      }
      String strwhole = param.strCache.substring(0, index);
      param.strCache.remove(0, index+1);
      strwhole.trim();
      Serial.printf("whole len:%d ", strwhole.length());
      Serial.println(strwhole);
      // Serial.printf("equal ret:%d\n", ret);
      if(strwhole.equalsIgnoreCase(String('s')))
      {
          showStatus();
      }else if(strwhole.equalsIgnoreCase(String("reboot")))
      {
        ESP.restart();
      }
      else if(strwhole.startsWith("ssid="))
      {
        String ssid = strwhole.substring(5, strwhole.length());
        romflash.writeString(AddressSSID, ssid);
        romflash.commit();
        sendSerial1(ssid);
      }else if(strwhole.startsWith("password="))
      {
          String pwd = strwhole.substring(9, strwhole.length());
          romflash.writeString(AddressPassword, pwd);
          romflash.commit();
          sendSerial1(pwd);
      }else if(strwhole.startsWith("remhost="))
      {
        String ssid = strwhole.substring(8, strwhole.length());
        romflash.writeString(AddressPeerHost, ssid);
        romflash.commit();
        sendSerial1(ssid);
      }else if(strwhole.startsWith("remport="))
      {
        String ssid = strwhole.substring(8, strwhole.length());
        romflash.writeInt(AddressPeerPort, ssid.toInt());
        romflash.commit();
        sendSerial1(ssid);
      }
      else {
          showUsage();
      }
  
}
 
void taskSerialRecv()
  while(Serial.available())
  {
      char nch = Serial.read();
      param.strCache += nch;     
  }
}
 
char buffUdpRecv[255] = {0};
 
void taskUDPRecv()
{
  if(!param.wifiConnected){
    return;
  }
  int len = udp.parsePacket();
  if(len <= 0){
    return;
  }
  // IPAddress phost = udp.remoteIP();
  // uint16_t pport = udp.remotePort();
  // param.udpPeerHost = phost;
  // param.udpPeerPort = pport; 
  udp.read(buffUdpRecv, len);
  buffUdpRecv[len] = '\n';
  buffUdpRecv[len+1] = 0;
  param.strCache += buffUdpRecv;
}
 
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  sendSerial1("system start ...");
 
  initEEPRom();
 
  pb[TaskTypeParse].runLast = 0;
  pb[TaskTypeParse].runSlice = 20;
  pb[TaskTypeParse].func = taskParseData;
 
  pb[TaskTypeLed].runLast = 0;
  pb[TaskTypeLed].runSlice = 1000;
  pb[TaskTypeLed].func = taskLed;
 
  pb[TaskTypeSerialRecv].runLast = 0;
  pb[TaskTypeSerialRecv].runSlice = 40;
  pb[TaskTypeSerialRecv].func = taskSerialRecv;
 
  pb[TaskTypeUDPRecv].runLast = 0;
  pb[TaskTypeUDPRecv].runSlice = 40;
  pb[TaskTypeUDPRecv].func = taskUDPRecv;
 
  getChipInfo();
 
  param.uledPin = GPIO_ID_PIN(22);
  param.uledValue = LedStatusOff;
  pinMode(param.uledPin, OUTPUT);
  taskLed();
  connectToWIFI();
}
 
void loop() {
  // put your main code here, to run repeatedly: 
  param.uruntimemsec = millis();
  for(int t = 0; t < TaskTypeCount; t++)
  {
    if(param.uruntimemsec - pb[t].runLast > pb[t].runSlice)
    {
      pb[t].runLast = param.uruntimemsec;
      pb[t].func();
    }
  }
}

  

posted @   larkin-cn  阅读(567)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示