Multiple Esp32 ble client (one at a time) send data to server

I want to send data from multiple esp32 (one at a time) to one esp32. I saw the ble examples but i want an esp32 ble server and multiple clients that send data to server (one at a time). In example the server send data to the client. What should i do?

The ESP32 has another possability to exchange data wireless,
which is called ESP-NOW. With ESP-NOW all ESP32-microcontrollers can exchange data between each other including broadcasting. So you yourself would have to code all the details about server and clients.

here is a demo-code

// WARNING !! Trying to adapt this ESP32-code using ESP-NOW to a ESP8266 is a big hassle 
// as the ESP8266-ESP-NOW-library works very differently using other functions etc.
// for coding with an ESP8266 start with a code that is written for ESP8266 DON'T try to adapt an ESP32-code


//WiFiLib and Esp-NowLib espnowlib 
#include <WiFi.h>    // ESP32 needs "WiFi.h"     ESP8266 needs "ESP8266WiFi.h"
#include <esp_now.h> // ESP32 needs "esp_now.h"  ESP8266 needs "espnow.h" do you recognize the difference?

#define CHANNEL 0

boolean gb_SerialOutput_enabled = true;

using MacAdr = uint8_t[6];

// the code must know all receivers MAC-adresses that THIS boards wants to send data to
MacAdr ESP_NOW_MAC_adrOfRecv1  { 0x24, 0x0A, 0xC4, 0x06, 0xC3, 0x64 };
MacAdr ESP_NOW_MAC_adrOfRecv2  { 0x24, 0x0A, 0xC4, 0x02, 0xBC, 0x20 };
MacAdr ESP_NOW_MAC_adrOfRecv3  { 0x24, 0x6F, 0x28, 0x22, 0x62, 0xFC };

MacAdr SendersOwnMacAdress     { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
void SetupOwnMacAdress(){
  memcpy (SendersOwnMacAdress, ESP_NOW_MAC_adrOfRecv3, sizeof(SendersOwnMacAdress) );
}

boolean New_ESP_DataReceived = false;

esp_now_peer_info_t peerInfo;

void RegisterPeer(const MacAdr &MyMac_Adress_array) {
  memcpy(peerInfo.peer_addr, MyMac_Adress_array, sizeof(peerInfo.peer_addr) );
  peerInfo.channel = 0;  
  peerInfo.encrypt = false;

  if (esp_now_add_peer(&peerInfo) != ESP_OK)
  { if (gb_SerialOutput_enabled)
      { Serial.println("Failed to add peer"); }
    return;
  }  
}

//nbt nonblockingtimer 
boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - expireTime >= TimePeriod )
  {
    expireTime = currentMillis; // set new expireTime
    return true;                // more time than TimePeriod) has elapsed since last time if-condition was true
  } 
  else return false;            // not expired
}

unsigned long BlinkTimer = 0;
const int     OnBoardLED = 2;

unsigned long SendDataTimer = 0;

// pslib pstringlib
#include <PString.h> // the use of PString avoids code-malfunction like Strings can do
char    TestESP_CmdStr_AoC[64];
PString TestESP_CmdStr_PS(TestESP_CmdStr_AoC, sizeof(TestESP_CmdStr_AoC) );

// pfndt
void PrintFileNameDateTime() {
  Serial.print("Code running comes from file ");  Serial.println(__FILE__);
  Serial.print("compiled ");  Serial.print(__DATE__);  Serial.print(" ");  Serial.println(__TIME__);
}

// pma pwma
void PrintWiFiMacAdress() {
  char MacAdr_AoC[18];  //suffix _AoC for easier remembering variable-type is ArrayOfChar
  char HexByteDigits[3];

  for (uint8_t i = 0; i < 18; i = i + 1){
    MacAdr_AoC[i] = WiFi.macAddress()[i];
  }
  MacAdr_AoC[17] = 0; // zero to terminate the string
  Serial.print("ESP Board Wifi.macAddress:  ");
  Serial.println(MacAdr_AoC);

  Serial.println();
  Serial.println("copy the line below and replace the '#' with variablename of your choice");
  Serial.println();
  Serial.print("uint8_t #[] = { ");
  for (uint8_t i = 0; i < 16; i = i + 3)
  {
    HexByteDigits[0] = MacAdr_AoC[i];
    HexByteDigits[1] = MacAdr_AoC[i + 1];
    HexByteDigits[2] = 0; // zero for terminating the string
    Serial.print("0x");
    Serial.print(HexByteDigits);
    if (i < 14) Serial.print(", ");
  }
  Serial.println(" };");
  Serial.println();
}

// espnowmsg espnowbytes enbytes espstruc
// Structure example to send data. Must match the receiver structure
typedef struct MyESP_NOW_Data_type {
  char  MyESP_NOW_SenderID_AoC[16];
  char  MyESP_NOW_StatusMsg_AoC[64];
  int   MyESP_NOW_Int;
  float MyESP_NOW_Float;
} MyESP_Data_type;

MyESP_NOW_Data_type ESP_Data_Received;
MyESP_NOW_Data_type ESP_Data_ToSend;


// Init ESP Now with restart in case something went wrong
void InitESPNow() {
  if (gb_SerialOutput_enabled)
  { if (esp_now_init() == ESP_OK) 
    { Serial.println("ESPNow Init Success"); }
    else 
    { Serial.println("ESPNow Init Failed");
      ESP.restart(); //there was an error try again through restarting the board
    }
  }  
}


void ESP_NOW_Setup() {
  WiFi.mode(WIFI_STA); //Set device in STA mode to begin with
  WiFi.disconnect();   // for strange reasons WiFi.disconnect(); is nescessary to make ESP-NOW work
  if (gb_SerialOutput_enabled)
    { Serial.println("WiFi.mode(WIFI_STA WiFi.disconnect() done");}

  InitESPNow();   // Init ESPNow with a fallback logic
  esp_now_register_send_cb(OnDataSent);
  
  esp_now_register_recv_cb(OnDataRecv);

  RegisterPeer(ESP_NOW_MAC_adrOfRecv1);
  RegisterPeer(ESP_NOW_MAC_adrOfRecv2);
  RegisterPeer(ESP_NOW_MAC_adrOfRecv3);
}


void PrintESP_Status(esp_err_t result) {
  Serial.print("Send Status: ");

  if (result == ESP_OK)
    { Serial.println("sended"); }
  else if (result == ESP_ERR_ESPNOW_NOT_INIT)
    { Serial.println("Master ESPNOW not Init."); }
  else if (result == ESP_ERR_ESPNOW_ARG)
    { Serial.println("Master Invalid Argument"); }
  else if (result == ESP_ERR_ESPNOW_INTERNAL)
    { Serial.println("Master Internal Error");}
  else if (result == ESP_ERR_ESPNOW_NO_MEM)
    { Serial.println("Master ESP_ERR_ESPNOW_NO_MEM"); }
  else if (result == ESP_ERR_ESPNOW_NOT_FOUND)
    { Serial.println("Master Peer not found."); }
  else 
    {Serial.println("Master Not sure what happened"); }
}

void SendData() {
  if (gb_SerialOutput_enabled)
    { Serial.println("sendData() Start");}
  esp_err_t result;  

  if(memcmp(ESP_NOW_MAC_adrOfRecv1, SendersOwnMacAdress, sizeof(SendersOwnMacAdress) ) != 0) { // if MAC-Adess is not the own MAC-Adress
    result = esp_now_send(ESP_NOW_MAC_adrOfRecv1, (uint8_t *) &ESP_Data_ToSend, sizeof(ESP_Data_ToSend));
    // if sending has finished function OnDataSent is called  
  }
  
  if(memcmp(ESP_NOW_MAC_adrOfRecv2, SendersOwnMacAdress, sizeof(SendersOwnMacAdress) ) != 0) {
    result = esp_now_send(ESP_NOW_MAC_adrOfRecv2, (uint8_t *) &ESP_Data_ToSend, sizeof(ESP_Data_ToSend));
    // if sending has finished function OnDataSent is called
  }

  if(memcmp(ESP_NOW_MAC_adrOfRecv3, SendersOwnMacAdress, sizeof(SendersOwnMacAdress) ) != 0) {
    result = esp_now_send(ESP_NOW_MAC_adrOfRecv3, (uint8_t *) &ESP_Data_ToSend, sizeof(ESP_Data_ToSend));
    // if sending has finished function OnDataSent is called  
  }
}


// callback-function that is executed when data was send to another ESP32-board
// parameter status contains info about the success or fail of the transmission
void OnDataSent(const uint8_t *Receivers_mac_addr, esp_now_send_status_t status) {
  char Receivers_macStr[18];
  snprintf(Receivers_macStr, sizeof(Receivers_macStr), "%02x:%02x:%02x:%02x:%02x:%02x",Receivers_mac_addr[0], Receivers_mac_addr[1], Receivers_mac_addr[2], Receivers_mac_addr[3], Receivers_mac_addr[4], Receivers_mac_addr[5]);

  if (gb_SerialOutput_enabled)
  {  
    Serial.print("callback-OnDataSent ");
    Serial.print("ESP32-Board Last Packet Sent to: ");
    Serial.println(Receivers_macStr);
    Serial.print("ESP32-Board1 Last Packet Send Status: ");
    Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Failed");
    Serial.println();
    Serial.println();
  }  
}

// callback-function that is executed when a ESP-NOW-Message is received
void OnDataRecv(const uint8_t *Senders_mac_addr, const uint8_t *receivedBytes, int NoOfreceivedBytes) {
  memcpy(&ESP_Data_Received, receivedBytes, sizeof(ESP_Data_Received)); // just copy data to structured variable
  New_ESP_DataReceived = true;                                          // and set Flag true
}


void DisplayESP_Data() {
  Serial.println("callback-OnDataRecv ");
  char Senders_macStr[18]; //MAC-Adress of sender
  snprintf(Senders_macStr, sizeof(Senders_macStr), "%02x:%02x:%02x:%02x:%02x:%02x", Senders_mac_addr[0], Senders_mac_addr[1], Senders_mac_addr[2], Senders_mac_addr[3], Senders_mac_addr[4], Senders_mac_addr[5]);
  Serial.print("received from MAC-Adress");
  Serial.println(Senders_macStr);

  Serial.println("receievd data:"); 
  Serial.print("SenderID #");
  Serial.print(ESP_Data_Received.MyESP_NOW_SenderID_AoC);
  Serial.println("#");

  Serial.print("StatusMsg #");
  Serial.print(ESP_Data_Received.MyESP_NOW_StatusMsg_AoC);
  Serial.println("#");
  
  Serial.print("Integer:");
  Serial.print(ESP_Data_Received.MyESP_NOW_Int);
  Serial.println();
  
  Serial.print("Float:");
  Serial.print(ESP_Data_Received.MyESP_NOW_Float);
  Serial.println();

  Serial.println();
  Serial.println();
}


void SetupMessageToSend() {
                                                                                                            //1
  if(memcmp(ESP_NOW_MAC_adrOfRecv1, SendersOwnMacAdress, sizeof(SendersOwnMacAdress) ) == 0) { // if MAC-Adess1 IS the own MAC-Adress
    memcpy(ESP_Data_ToSend.MyESP_NOW_SenderID_AoC,  "ESP32-Board1111",  sizeof(ESP_Data_ToSend.MyESP_NOW_SenderID_AoC) );
    memcpy(ESP_Data_ToSend.MyESP_NOW_StatusMsg_AoC, " I am Board No 1", sizeof(ESP_Data_ToSend.MyESP_NOW_StatusMsg_AoC) );
    ESP_Data_ToSend.MyESP_NOW_Int = ESP_Data_ToSend.MyESP_NOW_Int + 1;
    ESP_Data_ToSend.MyESP_NOW_Float = 111.111; 
  }
                                                                                                            //2 
  if(memcmp(ESP_NOW_MAC_adrOfRecv2, SendersOwnMacAdress, sizeof(SendersOwnMacAdress) ) == 0) { // if MAC-Adess2 IS the own MAC-Adress
    memcpy(ESP_Data_ToSend.MyESP_NOW_SenderID_AoC,  "ESP32-Board2222",  sizeof(ESP_Data_ToSend.MyESP_NOW_SenderID_AoC) );
    memcpy(ESP_Data_ToSend.MyESP_NOW_StatusMsg_AoC, " I am Board No 2", sizeof(ESP_Data_ToSend.MyESP_NOW_StatusMsg_AoC) );
    ESP_Data_ToSend.MyESP_NOW_Int = ESP_Data_ToSend.MyESP_NOW_Int + 2;
    ESP_Data_ToSend.MyESP_NOW_Float = 222.222; 
  }
                                                                                                            //3
  if(memcmp(ESP_NOW_MAC_adrOfRecv3, SendersOwnMacAdress, sizeof(SendersOwnMacAdress) ) == 0) { // if MAC-Adess3 IS the own MAC-Adress
    memcpy(ESP_Data_ToSend.MyESP_NOW_SenderID_AoC,  "ESP32-Board3333",  sizeof(ESP_Data_ToSend.MyESP_NOW_SenderID_AoC) );
    memcpy(ESP_Data_ToSend.MyESP_NOW_StatusMsg_AoC, " I am Board No 3", sizeof(ESP_Data_ToSend.MyESP_NOW_StatusMsg_AoC) );
    ESP_Data_ToSend.MyESP_NOW_Int = ESP_Data_ToSend.MyESP_NOW_Int + 3;
    ESP_Data_ToSend.MyESP_NOW_Float = 333.333; 
  }  
}


void setup() {
  Serial.begin(115200);
  if (gb_SerialOutput_enabled)
    { PrintFileNameDateTime(); }
    
  ESP_NOW_Setup();
  if (gb_SerialOutput_enabled)
    { PrintWiFiMacAdress(); }

  pinMode(OnBoardLED,OUTPUT);
}

void loop()
{
  if ( TimePeriodIsOver(BlinkTimer,500) ) {
    digitalWrite (OnBoardLED, !digitalRead(OnBoardLED) );
  }

  if ( TimePeriodIsOver(SendDataTimer,2000) ) {
    SetupMessageToSend();
    SendData();
  }  
}

best regards Stefan

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.