我有一个包含 espcam 和 esp32 的项目,我需要使用 ESPNOW 将数据从 espcam 传输到 esp32。我发现我需要在两个处理器上拥有相同的通道。我改成同一个通道,数据发送成功,但是空了。
代码:
发件人(espcam):
uint8_t broadcastAddress1[] = {assume its the right one here :)}; //Enter your Receiver board MAC Address
String mess;
typedef struct test_struct {
int a;
} test_struct;
test_struct test;
esp_now_peer_info_t peerInfo;
// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
char macStr[18];
Serial.print("Packet to: ");
// Copies the sender mac address to a string
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
Serial.print(macStr);
Serial.print(" send status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
//ESPNOW
WiFi.mode(WIFI_STA);
WiFi.printDiag(Serial); // Uncomment to verify channel number before
esp_wifi_set_promiscuous(true);
esp_wifi_set_channel(3, WIFI_SECOND_CHAN_NONE);
esp_wifi_set_promiscuous(false);
WiFi.printDiag(Serial); // Uncomment to verify channel change after
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_send_cb(OnDataSent);
// register peer
peerInfo.channel = 0;
peerInfo.encrypt = false;
// register first peer
memcpy(peerInfo.peer_addr, broadcastAddress1, 6);
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
//ESPNOW
esp_err_t result = esp_now_send(0, (uint8_t *) &test, sizeof(test_struct));
test.a = 5;
Serial.println(test.a);
delay(1);
if (result == ESP_OK) {
Serial.println("Sent with success");
}
else {
Serial.println("Error sending the data");
}
delay(2000);
接收器(esp32):
typedef struct test_struct {
int a;
} test_struct;
//Create a struct_message called myData
test_struct myData;
//callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&myData, incomingData, sizeof(myData));
Serial.print("Bytes received: ");
Serial.println(len);
Serial.print("a: ");
Serial.println(myData.a);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(myData.a);
}
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.printDiag(Serial); // Uncomment to verify channel number before
esp_wifi_set_promiscuous(true);
esp_wifi_set_channel(3, WIFI_SECOND_CHAN_NONE);
esp_wifi_set_promiscuous(false);
WiFi.printDiag(Serial); // Uncomment to verify channel change after
Serial.println(WiFi.channel());
//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 recv CB to
// get recv packer info
esp_now_register_recv_cb(OnDataRecv);
我尝试将频道更改为正确的频道,这有助于在它们之间建立连接,但数据仍然为空。
看来您仅在发送数据后才将结构体变量
test
的属性a
设置为5
。
确保在发送之前将有效负载初始化为您想要的内容。