Created
August 6, 2022 00:26
-
-
Save hollyhockberry/8b227992be71e39bb6dcdc4948d79617 to your computer and use it in GitHub Desktop.
Sample: ESP-NOW broadcast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ESP-NOW broadcast sender | |
#include <Arduino.h> | |
#include <esp_now.h> | |
#include <WiFi.h> | |
// タクトスイッチのピン | |
constexpr uint8_t SW_PIN = G39; | |
constexpr uint8_t CHANNEL = 1; | |
constexpr uint8_t BROADCAST[] = { | |
0xff, 0xff, 0xff, 0xff, 0xff, 0xff | |
}; | |
void sendCallback(const uint8_t *mac_addr, esp_now_send_status_t status) { | |
Serial.printf("sent: peer=%02X:%02X:%02X:%02X:%02X:%02X, status=%d\r\n", | |
mac_addr[0], mac_addr[1], mac_addr[2], | |
mac_addr[3], mac_addr[4], mac_addr[5], | |
status); | |
} | |
void setup() { | |
Serial.begin(115200); | |
::pinMode(SW_PIN, INPUT_PULLDOWN); | |
WiFi.mode(WIFI_STA); | |
WiFi.disconnect(); | |
if (::esp_now_init() != ESP_OK) { | |
// failed! | |
::esp_restart(); | |
} | |
esp_now_peer_info_t info = {}; | |
::memcpy(info.peer_addr, BROADCAST, 6); | |
info.channel = CHANNEL; | |
info.encrypt = false; | |
if (::esp_now_add_peer(&info) != ESP_OK) { | |
// failed! | |
::esp_restart(); | |
} | |
// 無くても動くよ | |
::esp_now_register_send_cb(sendCallback); | |
} | |
void loop() { | |
if (::digitalRead(SW_PIN) != LOW) return; | |
static uint8_t v = 0; | |
Serial.printf("send: value = %d\r\n", v); | |
::esp_now_send(BROADCAST, &v, 1); | |
v++; | |
// wait for release. | |
while (::digitalRead(G39) == LOW) { | |
::delay(1); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ESP-NOW receiver | |
#include <Arduino.h> | |
#include <esp_now.h> | |
#include <WiFi.h> | |
void recvCallback(const uint8_t *mac_addr, const uint8_t *data, int data_len) { | |
Serial.printf("recv: peer=%02X:%02X:%02X:%02X:%02X:%02X, data=", | |
mac_addr[0], mac_addr[1], mac_addr[2], | |
mac_addr[3], mac_addr[4], mac_addr[5]); | |
for (auto i = 0; i < data_len; ++i) Serial.printf("%02X", data[i]); | |
Serial.println(); | |
} | |
void setup() { | |
Serial.begin(115200); | |
WiFi.mode(WIFI_STA); | |
WiFi.disconnect(); | |
if (::esp_now_init() != ESP_OK) { | |
::esp_restart(); | |
} | |
::esp_now_register_recv_cb(recvCallback); | |
} | |
void loop() { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment