ESP32 ESPNOW 功能测试

ESP32 的 ESPNOW 给我们提供了一个方便的让 ESP32 无线互联通讯的方法。这次测试的是:一个 DFRobot 的 FireBeetle ESP32 和 ESP32S3 通过 ESPNOW 互联。

代码要点:

  1. 发送方需要知道接收方的 MAC,每一个ESP32都内置了一个独一无二的MAC;
  2. 通讯成功后,接收方能够得知发送方的 MAC;
  3. 简单起见,通过    esp_wifi_set_mac函数直接指定当前 ESP32 的 MAC,这样就不用专门查询了;
  4. 通过IDPIN区分两块板子,就是说测试的时候,一块板子这个引脚悬空,另外一个拉低
#include <esp_now.h>
#include <WiFi.h>
#include "MacAddress.h"
#include "WiFi.h"
#include "esp_wifi.h"

#define IDPIN 48

//  发射器地址(当前是发射) ESP32 A 的 MAC 地址
uint8_t AddressA[] = {'L', 'A', 'B', '-', 'Z', 'S'};
//  接收器地址 ESP32 B 的 MAC 地址
uint8_t AddressB[] = {'L', 'A', 'B', '-', 'Z', 'R'};

// 数据结构
typedef struct {
  char data[250];
} esp_now_message_t;

esp_now_message_t message;

void onDataReceive(const esp_now_recv_info *mac, const uint8_t *incomingData, int len) {
  esp_now_message_t receivedMessage;
  memcpy(&receivedMessage, incomingData, sizeof(receivedMessage));
  if (digitalRead(IDPIN) == HIGH) {
    Serial.print("Received from ESP32 B: ");
  } else {
    Serial.print("Received from ESP32 A: ");
  }
  Serial.println(receivedMessage.data);
}

void setup() {
  pinMode(IDPIN, INPUT_PULLUP);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  if (digitalRead(IDPIN) == HIGH) {
    // 设定本机 MAC 为 AddressA
    esp_wifi_set_mac(WIFI_IF_STA, &AddressA[0]);
  } else {
    // 设定本机 MAC 为 AddressB
    esp_wifi_set_mac(WIFI_IF_STA, &AddressB[0]);
  }

  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  esp_now_peer_info_t peerInfo;
  if (digitalRead(IDPIN) == HIGH) {
    memcpy(peerInfo.peer_addr, AddressB, 6);
  } else {
    memcpy(peerInfo.peer_addr, AddressA, 6);
  }
  peerInfo.channel = 1;
  peerInfo.ifidx = WIFI_IF_STA;
  peerInfo.encrypt = false;

  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }

  esp_now_register_recv_cb(onDataReceive);
}

void loop() {
  if (Serial.available()) {
    int len = Serial.readBytesUntil('\n', message.data, sizeof(message.data));
    message.data[len] = '\0'; // 确保字符串以 null 结尾

    esp_err_t result;
    if (digitalRead(IDPIN) == HIGH) {
       result = esp_now_send(AddressB, (uint8_t *)&message, sizeof(message));
    } else {
       result = esp_now_send(AddressA, (uint8_t *)&message, sizeof(message));
    }

    if (result == ESP_OK) {
      if (digitalRead(IDPIN) == HIGH) {
        Serial.println("Sent to ESP32 B successfully");
      } else {
        Serial.println("Sent to ESP32 A successfully");
      }
    } else {
      Serial.println("Error sending the data");
    }
  }
}

工作的视频在 【ESP32和ESP32S3通过ESPNOW通信演示】

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注