问题解决了吗?更多 ESP-NOW 的参考示例参见:
https://github.com/espressif/esp-now
由于 ESP-NOW 必须和 Wi-Fi (sta or softap)处于相同的信道,你需要先设置信道与 使用 ESP-NOW 发包,参考如下:
Code: Select all
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/timers.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_now.h"
static const char *TAG = "espnow_example";
static uint8_t s_example_broadcast_mac[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
/* WiFi should start before using ESPNOW */
static void example_wifi_init(void)
{
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK( esp_wifi_start());
}
void app_main(void)
{
nvs_flash_init();
example_wifi_init();
/* Initialize ESPNOW and register sending and receiving callback function. */
ESP_ERROR_CHECK( esp_now_init() );
/* Set primary master key. */
ESP_ERROR_CHECK( esp_now_set_pmk((uint8_t *)CONFIG_ESPNOW_PMK) );
/* Add broadcast peer information to peer list. */
esp_now_peer_info_t *peer = malloc(sizeof(esp_now_peer_info_t));
memset(peer, 0, sizeof(esp_now_peer_info_t));
peer->channel = CONFIG_ESPNOW_CHANNEL;
peer->ifidx = WIFI_IF_STA;
peer->encrypt = false;
memcpy(peer->peer_addr, s_example_broadcast_mac, ESP_NOW_ETH_ALEN);
ESP_ERROR_CHECK( esp_now_add_peer(peer) );
esp_wifi_config_espnow_rate(ESP_IF_WIFI_STA, WIFI_PHY_RATE_1M_L);
uint8_t data = {0};
uint32_t timestamp_start = esp_log_timestamp();
for(int i= 0; i < 10000; ) {
if( esp_now_send(s_example_broadcast_mac, &data, sizeof(uint8_t))!= ESP_OK) {
vTaskDelay(1);
continue;
}
++i;
}
ESP_LOGI(TAG, "Time spent: %d, Frame rate: %d", esp_log_timestamp() - timestamp_start,
10000 * 1000 / (esp_log_timestamp() - timestamp_start));
free(peer);
}