I have been using ESP-NOW for a while with one to one and one to many options. Now I decided to make a project with multiple 8266 boards and I would like to send different data from multiple boards to one receiver. I would like to separate the different incoming data on the receiver side.
I've read a lot about it, but I got stuck with it. It is working if I send the same data form all of the boards, but it isn't when I send different.
you need to have some means of identifing the different message types, e.g.
typedef struct struct_message {
int type;
float c;
} struct_message;
typedef struct struct_message2 {
int type;
String s;
} struct_message2;
// Create a struct_message called myData
struct_message myData;
struct_message2 myData2;
the structures start with an int called type which will be used to identify the message type, e.g. containing a float or a string
the transmitter would set up the type and the data float (type 0) or string (type 1), e.g.
void loop() {
if ((millis() - lastTime) > timerDelay) {
static int type = 0;
if(type == 0) {
// Set values to send
myData.type = type;
myData.c = 1.2 + random(1,20);
type=1;
// Send message via ESP-NOW
esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
}
else {
myData2.type = type;
Serial.print("Enter a string ? ");
myData2.s = Serial.readStringUntil('\n'); // <<<< read string
type=0;
// Send message via ESP-NOW
esp_now_send(broadcastAddress, (uint8_t *) &myData2, sizeof(myData2));
}
lastTime = millis();
}
}
and the receiver when it received a message would look at the type and then extract data either float (type 0) or string (type 1)
// Callback function that will be executed when data is received
void OnDataRecv(uint8_t * mac, uint8_t *incomingData, uint8_t len) {
Serial.print("Bytes received: ");
Serial.println(len);
int type;
memcpy(&type, incomingData, sizeof(int));
Serial.print("type: ");
Serial.println(type);
if(type == 0){
memcpy(&myData, incomingData, sizeof(myData));
Serial.print("Float: ");
Serial.println(myData.c);
Serial.println();
}
else {
memcpy(&myData2, incomingData, sizeof(myData2));
Serial.print("String: ");
Serial.println(myData2.s);
Serial.println();
}
}
the transmitter alternates sending a float (type 0) then a string (type 1) etc etc in loop()
here is a run of the receiver