いまさらになっちゃいますが、3台接続の部分をやってみたのでとりあえず。ちょっと勘違いがあってえらく時間かかっちゃいました...
1台をWifiのAPで、通信上のサーバにします。
これに対して、他の2台がWiFiで接続し、UDPで適宜データを送信します。
サーバ側では、どちらの子機からデータを受け取ったかはIPアドレス情報で判別出来ます。
手持ちの基板の関係で、ESP32とESP8266を混ぜて/入れ替えて実験しました。
ESP8266をAP/Serverにしたとき、やたらにUDPの取りこぼしがあるのが気になりますが、ESP32をAP/Serverにしたときは見ている範囲では取りこぼしは見えなかったので、ESP32で使っている範囲では大丈夫なのではないか、と思います。
Arduino
1// 共通ヘッダ
2const unsigned int UDP_PORT = 55555;
3
4const char* SSID = "ESP32-WiFi"; // SSID
5const char* PASS = "esp32wifi"; // password
6
7const IPAddress SERVERIP(192, 168, 20, 254); // サーバのIP 他の機器と重ならないこと
8const IPAddress SUBMASK(255, 255, 255, 0); // subnetmask
9
10const IPAddress CLIENTIP_1(192,168,20,1); // 子機1のIP
11const IPAddress CLIENTIP_2(192,168,20,2); // 子機2のIP
Arduino
1// AP/Server
2// ESP32シンボルはESP32ライブラリで定義される
3ifdef ESP32
4#include <WiFi.h>
5#else
6#include <ESP8266WiFi.h>
7#include <Wifiudp.h>
8#endif
9#include "addr.h"
10
11WiFiUDP Udp;
12
13IPAddress myIP;
14
15//WiFiをアクセスポイントとしてオープン
16void wifiInit(String ssid, String pass, IPAddress ip, IPAddress subMask) {
17 WiFi.softAP(SSID, PASS);
18 delay(100);//安定化
19 WiFi.softAPConfig( ip, ip, subMask);
20 delay(100);
21 myIP = WiFi.softAPIP();
22 Udp.begin(UDP_PORT);
23}
24
25void setup() {
26 wifiInit(SSID, PASS, SERVERIP, SUBMASK);
27
28 Serial.begin(115200);
29 /* 各種情報を表示 */
30 Serial.print("SSID: ");
31 Serial.println(SSID);
32 Serial.print("AP IP address: ");
33 Serial.println(myIP);
34}
35
36void loop() {
37 if (Udp.parsePacket())//UDP受信あり?
38 {
39 char rd[4] = {0};
40 Udp.read(rd, 4);
41 IPAddress rmt = Udp.remoteIP();
42 Udp.flush();//残データがあったら捨てる
43 Serial.print(rd);
44 Serial.print(" from ");
45 Serial.println(rmt);
46 }
47}
Arduino
1// 子機側
2// 2台めはCLIENTIP_2にする
3#define CLIENT CLIENTIP_1
4#ifdef ESP32
5#include <WiFi.h>
6#else
7#include <ESP8266WiFi.h>
8#include <WifiUDP.h>
9#endif
10#include "addr.h"
11
12WiFiUDP Udp;
13
14IPAddress myIP;
15void wifiInit(const char* ssid, const char* pass, IPAddress ip) {
16 delay(100);
17 WiFi.mode(WIFI_STA);
18 WiFi.begin(ssid, pass);
19
20 WiFi.config(ip, SERVERIP, SUBMASK);
21 do {
22 delay(100);
23 } while (WiFi.status() != WL_CONNECTED);
24 delay(100);
25 myIP = WiFi.localIP();
26}
27
28void setup() {
29 Serial.begin(115200);
30 Serial.println("\nWiFi Connecting");
31 wifiInit(SSID, PASS, CLIENT);
32 Serial.print("Connected.\nI AM ");
33 Serial.println(myIP);
34
35 Udp.begin(UDP_PORT);
36}
37
38void loop() {
39 char buf[16];
40 if (WiFi.status() == WL_CONNECTED) {
41 if (Udp.beginPacket(SERVERIP, UDP_PORT) != 0) {
42 sprintf(buf, "%03d", (int)(millis() % 1000));
43 Udp.write((uint8_t*)buf, 4);
44 Udp.endPacket();
45 Serial.print("Send: ");
46 Serial.println(buf);
47 }
48 } else {
49 Serial.println("Disconnected");
50 }
51 delay(501);
52}