Hi,
I am trying to use esp_now to send data. I created a flag variable to start and stop the data transfer. It works fine during initialization but throws an error(Error sending data) when the flag is resetted. I tried to reinitialize the esp_now in the callback function, but did not work. Code attached below
#include <Arduino.h>
#include <esp_now.h>
#include <WiFi.h>
// REPLACE WITH YOUR RECEIVER MAC Address
uint8_t broadcastAddress[] = {0x08, 0x3A, 0xF2, 0xA9, 0xB9, 0xC8};
// Structure example to send data
// Must match the receiver structure
typedef struct struct_message
{
// char a[30];
float battery_voltage;
float shunt_voltage;
int time;
} struct_message;
// Create a struct_message called myData
struct_message myData;
static bool flag = true;
esp_now_peer_info_t peerInfo;
// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *incomingdata, int len)
{
Serial.print("Command received ");
memcpy(&flag, incomingdata, sizeof(incomingdata));
Serial.println(flag);
if (flag)
{
if (esp_now_init() != ESP_OK)
{
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_send_cb(OnDataSent);
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
}
}
void setup()
{
// Init Serial Monitor
Serial.begin(115200);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK)
{
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK)
{
Serial.println("Failed to add peer");
return;
}
esp_now_register_recv_cb(OnDataRecv);
}
void loop()
{
if (flag)
{
// Set values to send
myData.battery_voltage = analogRead(35);
myData.shunt_voltage = analogRead(32);
myData.time = millis();
delay(500);
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&myData, sizeof(myData));
if (result == ESP_OK)
{
Serial.println("Sent with success");
}
else
{
Serial.println("Error sending the data");
}
delay(1000);
}
}```
Kindly point out whats wrong in the code. Thanks