Cervino,
I’m not sure how many ESP32’s your project is using or what the end goal is.
But maybe you should look into using the ESP-NOW protocol. With this protocol, it is very easy to exchange data between all connected ESP32’s. It is fully automatic and will detect instantly when an ESP comes/goes on/off line.
For example, I use ESP-NOW in my Aquarium controller app, and I need only to connect to the Main controller using Bluetooth Classic.
After that any ESP32’s the go on/off line are automatically detected by the First connected ESP, which then can send data back and forth to any or all other ESP32’s. The Main controller then can send any updated information back to the App, for user interaction and display.
Here is a link that I used to get started using the ESP-NOW protocol:
https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/
Just a side note:
The demos show how to get the MAC Address of each of the ESP32’s. You can avoid doing this and make it automatic by simply adding a few lines in your code to set the device to your own unique Mac Address on startup. Then in you know what address each board will always have.
You can do it like this:
#include <esp_now.h>
#include <WiFi.h>
#include <esp_wifi.h>
uint8_t Main_Adr[] = {0x20, 0xAE, 0xA4, 0x20, 0x0D, 0x10};
uint8_t Device1_Adr[] = {0x20, 0xAE, 0xA4, 0x20, 0x0D, 0x11};
uint8_t Device2_Adr[] = {0x20, 0xAE, 0xA4, 0x20, 0x0D, 0x12};
uint8_t Device3_Adr[] = {0x20, 0xAE, 0xA4, 0x20, 0x0D, 0x13};
Then in your setup:
If this is the Main Controller set it to the Main_Adr[]
Like this:
void setup() {
Serial.begin(115200);
btSerial.begin(9600);
WiFi.mode(WIFI_STA);
// Set this address as the Main Controller
esp_wifi_set_mac(ESP_IF_WIFI_STA, &Main_Adr[0]);
if (esp_now_init() != 0) {ESP.restart();}
// Setup peers for sending data to
esp_now_peer_info_t peerInfo;
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add the peers
memcpy(peerInfo.peer_addr, Device1_Adr, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {ESP.restart();}
memcpy(peerInfo.peer_addr, Device2_Adr, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {ESP.restart();}
memcpy(peerInfo.peer_addr, Device3_Adr, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {ESP.restart();}
}
And for your other ESP32’s your Device1, 2 and 3
You would us the same code above, only set THIS ADDRESS to which ever device it is:
// Set this address as the Device1
esp_wifi_set_mac(ESP_IF_WIFI_STA, & Device1_Adr[0]);
if (esp_now_init() != 0) {ESP.restart();}
Then add as many peers, as you need for sending data to.
To send data back to the Main controller add it as a peer:
memcpy(peerInfo.peer_addr, Main_Adr _Adr, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {ESP.restart();}
To send data to Device2, then add it and so on.
memcpy(peerInfo.peer_addr, Device2_Adr, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK) {ESP.restart();}
Hope that helps,
Mike.