接点の情報を無線でリレーに送る。(M5NanoC6)(ブロードキャスト)(ESP-NOW)


x 過去ログを見よ
x パケロスしても気にするな!!
x USBシリアルのロスしても気にするな!!




目的
接点の状態をリレーに無線で送る
何が楽しいのか、無線で遊ぶ事が楽しいです。
いろいろ、ネットで出ていた、接点どうちゃらこうちゃらが
最新のWiFiを使って解決
応用例としては、お店のドアが開いたらベルを鳴らす等

ホストNanoC6(マイクロスイッチ)
スレーブStampS3(リレー)


結果


![o_coq561.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/840352/e1d67f64-e602-392c-8a84-c42965371fc7.jpeg)

![o_coq562.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/840352/8b5a02d4-4c26-f52d-f8be-ae22f3886fd7.jpeg)

![o_coq563.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/840352/2baca6b7-6e0b-adf5-cd0a-6ff8c3b12b80.jpeg)

![o_coq564.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/840352/e9fce519-6728-df08-a3c0-d2bcfa5fccb4.jpeg)


プログラム

ホストNanoC6(マイクロスイッチ)

```c++


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

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

#include "MacAddress.h"

#include "Arduino.h"
#include "utility/Button_Class.hpp"


//定義1
using namespace m5;

Button_Class BtnS;

//定義2
/* 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(uint8_t channel, wifi_interface_t iface, const uint8_t *lmk) : ESP_NOW_Peer(ESP_NOW.BROADCAST_ADDR, channel, iface, lmk) {}
    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 */

uint32_t msg_count = 0;

//ブロードキャスト オブジェクトの定義
// Create a broadcast peer object
//ESP_NOW_Broadcast_Peer broadcast_peer(ESPNOW_WIFI_CHANNEL, WIFI_IF_STA, NULL);
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 */

#define CP (uint8_t *)


//初期化
void setup() {

  NanoC6.begin(); //SW

  pinMode(1, INPUT); //Grover GPIO1
  
  pinMode(M5NANO_C6_BLUE_LED_PIN, OUTPUT);
  digitalWrite(M5NANO_C6_BLUE_LED_PIN, LOW);

  //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

  //テストメッセージを送る debug
  delay(5);
  broadcast_peer.send_message(CP"T", 1+1);
  delay(5);
  broadcast_peer.send_message(CP"T", 1+1);
  delay(5);
  broadcast_peer.send_message(CP"T", 1+1);
  delay(5);

}//setup


//メインループ
void loop() {
  // Broadcast a message to all devices within the network
  static char data[32];

  //ボタンの状態の更新
  delay(5);//連続送信防止用
  //NanoC6.update();
  uint32_t ms = millis();
  BtnS.setRawState(ms, digitalRead(1)); //Grover GPIO1


  //ボタンを離した時
  if (BtnS.wasReleased()) {
    broadcast_peer.send_message(CP"R", 1+1);
    digitalWrite(M5NANO_C6_BLUE_LED_PIN, LOW);
  }//endif

  //ボタンを押し続けた時
  if (BtnS.wasHold()) {
    broadcast_peer.send_message(CP"H", 1+1);
  }//endif

  //ボタンを押した時
  if (BtnS.wasPressed()) {
    broadcast_peer.send_message(CP"P", 1+1);
    digitalWrite(M5NANO_C6_BLUE_LED_PIN, HIGH);
  }//endif

}//loop


```

スレーブStampS3(リレー)


```c++


//ESP32_NOW_s_Relay2_M5SatmpS3_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"

/* Definitions */

#define ESPNOW_WIFI_CHANNEL 1

/* 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) {


    //ブザーの処理
    int a = data[0];
    if(a == 'P'){
      digitalWrite(15, HIGH);
    }else if( a == 'R'){
      digitalWrite(15, LOW);
    }//endif

    
    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_addr));
    log_v("Igorning the message");
  }
}

/* Main */

void setup() {

  
  Serial.begin(115200);

  for(int i=0;i<16;i++){
    Serial.print(".");
    delay(1000);
  }//for
  Serial.println();



  pinMode(15, OUTPUT);//ブザーのポート設定
  digitalWrite(15, LOW);//ブザーのオフ


//  while (!Serial) {
//    delay(10);
//  }

  //WiFiの初期化
  // Initialize the Wi-Fi module
  WiFi.mode(WIFI_STA);
  WiFi.setChannel(ESPNOW_WIFI_CHANNEL);
  while (!WiFi.STA.started()) {
    delay(100);
  }

  //アドレスと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);

  //ブロードキャストの初期化
  // 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(); //リセット
  }

  //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...");
}

void loop() {
  delay(1000);//ダミー
}




```