esp32 arduino环境 udp serial收发实验

代码如下:

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
#include <WiFi.h>
#include <WiFiUdp.h>
#include "WString.h"
 
typedef void(*funcSlice)();
 
enum TaskType
{
  TaskTypeLed,
  TaskTypeChipInfo,
  TaskTypeSerialRecv,
  TaskTypeUDPRecv,
  TaskTypeCount
};
 
enum Status
{
  LedStatusOff = HIGH,
  LedStatusOn = LOW
};
 
struct GlobalParam
{
  uint32_t chipId;
  uint32_t uruntimemsec;
  uint32_t uledPin;
  uint32_t uledValue;
  uint16_t uUdpPort;
  bool bLedBlink;
  bool wifiConnected;
  IPAddress udpPeerHost;
  uint16_t udpPeerPort;
  String strCache;
};
 
struct ProgramBlock
{
  uint32_t runLast;
  uint32_t runSlice;
  funcSlice func;
};
 
ProgramBlock pb[TaskTypeCount] = {0};
GlobalParam param = {0};
//The udp library class
WiFiUDP udp;
 
void showUsage()
{
  Serial.println("============== menu ==============");
  Serial.println("?: help menu");
  Serial.println("s: status info");
  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);
 
    Serial.printf("udp listen port:%d\n", param.uUdpPort);
    Serial.print("udp peer host:");
    Serial.println(param.udpPeerHost.toString());
    Serial.printf("udp peer port:%d\n", param.udpPeerPort);
    Serial.println("====================================");
}
 
void initUDP()
{
  param.uUdpPort = 10888;
  udp.begin(param.uUdpPort);
  param.udpPeerHost.fromString("192.168.7.225");
  param.udpPeerPort = 11888;
}
 
void sendUDP(String str)
{
  udp.beginPacket(param.udpPeerHost,param.udpPeerPort);
    udp.println(str);
    udp.endPacket();
}
 
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("wifi_ssid", "wifi_password");
}
 
void taskChipInfo()
{
  // Serial.printf("time[%d] run taskChipInfo\n", param.uruntimemsec);
  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()
{
  // Serial.printf("time[%d] run taskLed\n", param.uruntimemsec);
  if(param.bLedBlink)
  {
    if(LedStatusOff == param.uledValue){
      param.uledValue = LedStatusOn;
    }else{
      param.uledValue = LedStatusOff;
    }
  }
  digitalWrite(param.uledPin, param.uledValue);
}
 
void parseData()
{
  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);
      Serial.printf("whole len:%d ", strwhole.length());
      Serial.println(strwhole);
      // Serial.printf("equal ret:%d\n", ret);
      if(strwhole.equals(String('?')))
      {
          showUsage();
      }else if(strwhole.equalsIgnoreCase(String('s')))
      {
          showStatus();
      }
  
}
 
void taskSerialRecv()
  while(Serial.available())
  {
      char nch = Serial.read();
      param.strCache += nch;     
  }
  parseData();
}
 
char buffUdpRecv[255] = {0};
 
void taskUDPRecv()
{
  if(!param.wifiConnected){
    return;
  }
  // Serial.printf("time %d run taskUDPRecv\n", param.uruntimemsec);
  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;
  parseData();
}
 
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
 
  pb[TaskTypeChipInfo].runLast = 0;
  pb[TaskTypeChipInfo].runSlice = 2000;
  pb[TaskTypeChipInfo].func = taskChipInfo;
 
  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;
 
  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  阅读(378)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示