用esp8266与esp01s用espnow通讯的代码
时间: 2024-03-22 09:37:15 浏览: 19
以下是使用ESP8266和ESP-01S利用ESP-NOW进行通信的示例代码:
发送数据的ESP8266代码:
```c++
#include <ESP8266WiFi.h>
#include <espnow.h>
// Replace with the MAC address of the receiving ESP-01S module
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
// Callback function that will be executed when data is sent
void OnDataSent(uint8_t *mac_addr, uint8_t status) {
Serial.print("Packet sent to: ");
for (int i = 0; i < 6; i++) {
Serial.print(mac_addr[i], HEX);
if (i != 5) {
Serial.print(":");
}
}
Serial.print(" Status: ");
Serial.println(status);
}
void setup() {
Serial.begin(115200);
// Initialize ESP-NOW
if (esp_now_init() != 0) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Register the callback function
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_register_send_cb(OnDataSent);
// Add the receiving ESP-01S module as a peer
esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0);
}
void loop() {
// Send data to the receiving ESP-01S module
String message = "Hello from ESP8266!";
uint8_t data[message.length() + 1];
message.getBytes(data, message.length() + 1);
esp_now_send(broadcastAddress, data, message.length() + 1);
delay(1000);
}
```
接收数据的ESP-01S代码:
```c++
#include <ESP8266WiFi.h>
#include <espnow.h>
// Replace with the MAC address of the receiving ESP8266 module
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
void OnDataReceived(uint8_t *mac_addr, uint8_t *data, uint8_t len) {
Serial.print("Data received from: ");
for (int i = 0; i < 6; i++) {
Serial.print(mac_addr[i], HEX);
if (i != 5) {
Serial.print(":");
}
}
Serial.print(" Data: ");
Serial.write(data, len);
Serial.println();
}
void setup() {
Serial.begin(115200);
// Initialize ESP-NOW
if (esp_now_init() != 0) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Register the callback function
esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
esp_now_register_recv_cb(OnDataReceived);
// Add the sending ESP8266 module as a peer
esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_CONTROLLER, 1, NULL, 0);
}
void loop() {
// Do nothing
}
```
在以上代码中,需要将发送ESP8266和接收ESP-01S的MAC地址替换为实际的地址。此外,还需要在发送ESP8266中将数据转换为字节数组,并在接收ESP-01S中使用Serial.write()函数来打印接收到的数据。