XIAO ESP32C6、2ボタンの青ボタンの値を無線電送する(ESP-NOW)


いろいろ、注意
----

- 過去ログて、なに？(今までの記事の事)
- アンテナ関連に注意
- 3.2.0
- ESPNOW ESP32-NOW の　事
- ESP32-C6 の　事


結果
----

![image_original(17).jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/840352/72fbf82a-d050-4a87-89f6-6a82494c6666.jpeg)


![Screenshot from 2025-04-15 08-06-42.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/840352/a348222d-9c97-4dfe-8fa8-31a231c9f3a0.png)


プログラム
----

マスター XIAO ESP32C6

```c++



//ESP32_NOW_m_2button_1_XIAO_ESP32C6_1
//1対1に改造する　対応
//ブロードキャスト


//インクルド (ESP-NOW)
#include <Arduino.h>
#include "ESP32_NOW.h"
#include "WiFi.h"
#include <esp_mac.h>  // For the MAC2STR and MACSTR macros


//定義

/* Definitions */
//WiFiチャンネルの指定
#define ESPNOW_WIFI_CHANNEL 1

//クラス
/* Classes */

// Creating a new class that inherits from the ESP_NOW_Peer class is required.

class ESP_NOW_Broadcast_Peer : public ESP_NOW_Peer {
public:
  // Constructor of the class using the broadcast address
  ESP_NOW_Broadcast_Peer(const uint8_t *mac_addr, uint8_t channel, wifi_interface_t iface, const uint8_t *lmk)
    : ESP_NOW_Peer(mac_addr, channel, iface, lmk) {}

  // Destructor of the class
  ~ESP_NOW_Broadcast_Peer() {
    remove();
  }

  // Function to properly initialize the ESP-NOW and register the broadcast peer
  bool begin() {
    if (!ESP_NOW.begin() || !add()) {
      log_e("Failed to initialize ESP-NOW or register the broadcast peer");
      return false;
    }
    return true;
  }

  // Function to send a message to all devices within the network
  bool send_message(const uint8_t *data, size_t len) {
    if (!send(data, len)) {
      log_e("Failed to broadcast message");
      return false;
    }
    return true;
  }
};

/* Global Variables */

//ブロードキャスト オブジェクトの定義
// Create a broadcast peer object
ESP_NOW_Broadcast_Peer broadcast_peer(ESP_NOW.BROADCAST_ADDR, ESPNOW_WIFI_CHANNEL, WIFI_IF_STA, NULL);

//const MacAddress peer_mac({0x48, 0x27, 0xe2, 0xe3, 0xbd, 0x50});
//ESP_NOW_Broadcast_Peer broadcast_peer(  peer_mac  , ESPNOW_WIFI_CHANNEL, WIFI_IF_STA, NULL);


/* Main */


//送信バッファー int(32bit)
//グローバルで定義しているのは、速度低下を防ぐため
uint8_t ac[] = { 0x00, 0x00, 0x00, 0x00 };

//初期化
void setup() {

  //アンテナの設定
  pinMode(WIFI_ENABLE, OUTPUT); // pinMode(3, OUTPUT);
  digitalWrite(WIFI_ENABLE, LOW); // digitalWrite(3, LOW); // Activate RF switch control
  delay(100);
  pinMode(WIFI_ANT_CONFIG, OUTPUT); // pinMode(14, OUTPUT);
  digitalWrite(WIFI_ANT_CONFIG, LOW); // digitalWrite(14, LOW); // Use IN antenna

  pinMode(D9,INPUT); //gpio init

  //WiFiの初期化
  // Initialize the Wi-Fi module
  WiFi.mode(WIFI_STA);
  WiFi.setChannel(ESPNOW_WIFI_CHANNEL);
  delay(3000);  //決め打ちなので、おかしかったら調整してね!

  //ブロードキャストの初期化
  // Register the broadcast peer
  if (!broadcast_peer.begin()) {
    delay(5000);    //瞬リセット防止用
    ESP.restart();  //リセット
  }                 //endif

  //テストメッセージを送る
  broadcast_peer.send_message(ac, 4);delay(5);
  broadcast_peer.send_message(ac, 4);delay(5);
  broadcast_peer.send_message(ac, 4);delay(5);
  
} //setup


//メインループ
void loop() {

  //センサー入力する
  int s;
  if(digitalRead(D9) == 0){s = 1;}else{s = 0;} //センサーの値を反転する

  //int (32bit) を 4byte に分割する処理
  ac[3] = s & 0xff;
  s = s >> 8;
  ac[2] = s & 0xff;
  s = s >> 8;
  ac[1] = s & 0xff;
  s = s >> 8;
  ac[0] = s & 0xff;

  //ESP-NOWのパケット(フレーム)を送信する
  broadcast_peer.send_message(ac, 4);
  delay(300);  //0.3秒待つ

}  //loop



```

スレーブ　M5StampS3

```c++


//ESP32_NOW_s_2button_1_M5StampS3_1
//1対1に改造する　対応
//ブロードキャスト


/*
    ESP-NOW Broadcast Slave
    Lucas Saavedra Vaz - 2024

    This sketch demonstrates how to receive broadcast messages from a master device using the ESP-NOW protocol.

    The master device will broadcast a message every 5 seconds to all devices within the network.

    The slave devices will receive the broadcasted messages. If they are not from a known master, they will be registered as a new master
    using a callback function.
*/


//インクルド
#include <Arduino.h>
#include "ESP32_NOW.h"
#include "WiFi.h"
#include <esp_mac.h>  // For the MAC2STR and MACSTR macros
#include <vector>
#include "MacAddress.h"


//定義

static volatile int s = 0;  //button値

/* Definitions */

#define ESPNOW_WIFI_CHANNEL 1

//プロトタイプ宣言
int acceleration_num();
void acceleration_write(unsigned char *a);
void acceleration_read(unsigned char *a);


//クラス
/* Classes */

// Creating a new class that inherits from the ESP_NOW_Peer class is required.

class ESP_NOW_Peer_Class : public ESP_NOW_Peer {
public:
  // Constructor of the class
  ESP_NOW_Peer_Class(const uint8_t *mac_addr, uint8_t channel, wifi_interface_t iface, const uint8_t *lmk)
    : ESP_NOW_Peer(mac_addr, channel, iface, lmk) {}

  // Destructor of the class
  ~ESP_NOW_Peer_Class() {}

  // Function to register the master peer
  bool add_peer() {
    if (!add()) {
      log_e("Failed to register the broadcast peer");
      return false;
    }
    return true;
  }

  // Function to print the received messages from the master
  void onReceive(const uint8_t *data, size_t len, bool broadcast) {

    //読み込みデータが4バイトの時
    if (len == 4) {

      //読み込みデータをセンサーの値に合成する
      int a = 0;
      a = data[0];
      a = a << 8;
      a = a | data[1];
      a = a << 8;
      a = a | data[2];
      a = a << 8;
      a = a | data[3];

      //センサーの値をセット
      s = a;

    }  //if


    //Serial.printf("Received a message from master " MACSTR " (%s)\n", MAC2STR(addr()), broadcast ? "broadcast" : "unicast");
    //Serial.printf("  Message: %s\n", (char *)data);
  }
};

/* Global Variables */

// List of all the masters. It will be populated when a new master is registered
std::vector<ESP_NOW_Peer_Class> masters;

/* Callbacks */

// Callback called when an unknown peer sends a message
void register_new_master(const esp_now_recv_info_t *info, const uint8_t *data, int len, void *arg) {

  //自分
  const MacAddress peer_mac1({ 0x48, 0x27, 0xe2, 0xe3, 0xbd, 0x50 });
  unsigned char a_add[6] = { 0x48, 0x27, 0xe2, 0xe3, 0xbd, 0x50 };
  //相手
  const MacAddress peer_mac2({ 0x40, 0x4c, 0xca, 0x5a, 0xe3, 0x1c });

  if (memcmp(info->des_addr, ESP_NOW.BROADCAST_ADDR, 6) == 0) {
    //if (memcmp(info->des_addr, a_add, 6) == 0) {
    Serial.printf("Unknown peer " MACSTR " sent a broadcast message\n", MAC2STR(info->src_addr));
    Serial.println("Registering the peer as a master");



    ESP_NOW_Peer_Class new_master(info->src_addr, ESPNOW_WIFI_CHANNEL, WIFI_IF_STA, NULL);

    masters.push_back(new_master);
    if (!masters.back().add_peer()) {
      Serial.println("Failed to register the new master");
      return;
    }
  } else {
    // The slave will only receive broadcast messages
    log_v("Received a unicast message from " MACSTR, MAC2STR(info->src_addrarduino-ide_2.3.5_Linux_64bit.AppImage));
    log_v("Igorning the message");
  }
}


/* Main */

//初期化
void setup() {

  //WiFiの初期化
  // Initialize the Wi-Fi module
  WiFi.mode(WIFI_STA);
  WiFi.setChannel(ESPNOW_WIFI_CHANNEL);

  //シリアルの初期化
  Serial.begin(9600);
  Serial.println("");
  //シリアルの待ちが0.5*9
  //delay(3000);//決め打ちなので、おかしかったら調整してね! wifiの待ち0.5*6
  for (int i = 0; i < (9 + 6); i++) {
    delay(500);  //接続待ち
    Serial.print(".");
  }  //for
  Serial.println("");

  //アドレスとWiFiチャンネルの表示
  Serial.println("ESP-NOW Example - Broadcast Slave");
  Serial.println("Wi-Fi parameters:");
  Serial.println("  Mode: STA");
  Serial.println("  MAC Address: " + WiFi.macAddress());
  Serial.printf("  Channel: %d\n", ESPNOW_WIFI_CHANNEL);

  //ブロードキャストの初期化arduino-ide_2.3.5_Linux_64bit.AppImage
  // Initialize the ESP-NOW protocol
  if (!ESP_NOW.begin()) {
    Serial.println("Failed to initialize ESP-NOW");
    Serial.println("Reeboting in 5 seconds...");
    delay(5000);    //瞬リセット防止用
    ESP.restart();  //リセット
  }                 //endif

  //ESP-NOWのコールバック(割り込み)
  // Register the new peer callback
  ESP_NOW.onNewPeer(register_new_master, NULL);

  //スタートが成功したと表示
  Serial.println("Setup complete. Waiting for a master to broadcast a message...");

}  //setup


//メインループ
void loop() {

  //表示
  Serial.println(s);

  //Serial.printf("Received a message from master " MACSTR " (%s)\n", MAC2STR(addr()), broadcast ? "broadcast" : "unicast");
  //Serial.printf("  Message: %s\n", (char *)data);

  delay(300);  //ダミー 0.3秒待つ

}  //loop



```