espnow 写二段代码 分别是发送端和接收端 控制led 开关
时间: 2024-05-08 17:15:22 浏览: 66
发送端:
```
#include <esp_now.h>
#include <WiFi.h>
//定义发送数据结构体
typedef struct dataPacket {
int ledState; //LED状态,0为关闭,1为打开
} DataPacket;
DataPacket data;
// 定义发送函数
void sendData() {
//设置MAC地址
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
//发送数据
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &data, sizeof(DataPacket));
if (result == ESP_OK) {
Serial.println("Sent with success");
} else {
Serial.println("Error sending the data");
}
}
void setup() {
Serial.begin(115200);
//初始化ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
//设置回调函数
esp_now_register_send_cb([](uint8_t *mac, esp_now_send_status_t status) {
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Send success" : "Send failure");
});
//设置对方设备MAC地址
uint8_t peerAddress[] = {0x5C, 0xCF, 0x7F, 0x24, 0x7C, 0x84};
//添加对方设备
esp_now_peer_info_t peerInfo;
memcpy(peerInfo.peer_addr, peerAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
return;
}
}
void loop() {
//发送数据
data.ledState = 1; //打开LED
sendData();
delay(1000);
data.ledState = 0; //关闭LED
sendData();
delay(1000);
}
```
接收端:
```
#include <esp_now.h>
#include <WiFi.h>
//定义接收数据结构体
typedef struct dataPacket {
int ledState; //LED状态,0为关闭,1为打开
} DataPacket;
DataPacket data;
//定义回调函数
void OnDataRecv(const uint8_t *mac, const uint8_t *data, int len) {
memcpy(&data, data, sizeof(DataPacket));
if (data.ledState == 1) {
digitalWrite(LED_BUILTIN, HIGH); //打开LED
} else {
digitalWrite(LED_BUILTIN, LOW); //关闭LED
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
//初始化ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
//设置回调函数
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
//等待数据接收
delay(100);
}
```
阅读全文