I'm using the Arduino IDE to program ESP8266 to communicate with each other using ESP-NOW.
If I call esp_now_send with the broadcast MAC address (FF:FF:FF:FF:FF:FF), the message is sent and the slave receives it clearly.
If I call esp_now_send with a specific slave MAC address (i.e. unicast) it fails every time with a sendStatus of 1.
What am I doing wrong?
Complete example code:
#define IS_CONTROLLER
#define UART_BAUD 9600
#include <ESP8266WiFi.h>
#include <espnow.h>
uint8_t broadcast_mac[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint8_t slave_mac[] = {0xBC, 0xFF, 0x4D, 0x18, 0xE4, 0xD8};
#ifdef IS_CONTROLLER
char broadcast_payload[] = "broadcast message";
char payload[] = "unicast message";
void onDataSent(uint8_t *mac, uint8_t sendStatus) {
if (sendStatus == 0)
Serial.println("SUCCESS");
else {
Serial.print("FAILED (status ");
Serial.print(sendStatus);
Serial.println(")");
}
Serial.println();
}
#else
void onDataReceived(uint8_t *mac, uint8_t *incomingData, uint8_t len) {
Serial.print("MESSAGE RECEIVED: ");
Serial.println((char*)incomingData);
Serial.println();
}
#endif
void send_message(uint8_t *mac, char *message) {
esp_now_send(mac, (uint8_t*)message, strlen(message)+1);
}
void setup() {
Serial.begin(UART_BAUD);
WiFi.mode(WIFI_AP);
WiFi.disconnect();
if (esp_now_init() != 0) {
Serial.println("Error initializing ESP-NOW");
return;
}
#ifdef IS_CONTROLLER
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_register_send_cb(onDataSent);
esp_now_add_peer(slave_mac, ESP_NOW_ROLE_SLAVE, 0, nullptr, 0);
#else
esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
esp_now_register_recv_cb(onDataReceived);
#endif
}
bool broadcasting = false;
void loop() {
#ifdef IS_CONTROLLER
Serial.println("CONTROLLER");
#else
Serial.println("SLAVE");
#endif
Serial.print("MAC ADDRESS: ");
Serial.println(WiFi.macAddress());
#ifdef IS_CONTROLLER
Serial.print(broadcasting ? "BROADCASTING MESSAGE ... " : "SENDING MESSAGE ... ");
send_message(broadcasting ? broadcast_mac : slave_mac, broadcasting ? broadcast_payload : payload);
broadcasting = !broadcasting;
#endif
delay(2000);
}
(Comment out IS_CONTROLLER when flashing the slave device.)
EDIT: If I change the Slave to use WIFI_STA mode, it works properly. But if the Slave uses WIFI_AP, unicast always fails – while broadcast still works. What gives?
wifi_set_macaddr(SOFTAP_IF, slave_mac);in the setup().wifi_set_macaddr(as shown in your linked code) and it just doesn't take.WiFi.softAPmacAddress()always returns the same result, even after I try to change it.