92 lines
2 KiB
C++
92 lines
2 KiB
C++
#include <esp_now.h>
|
|
#include <WiFi.h>
|
|
|
|
// Receiver MAC Address
|
|
uint8_t broadcastAddress[] = {0x34, 0xCD, 0xB0, 0xD0, 0x76, 0x40};
|
|
|
|
// Data to send, dose not matter in this code as any data will make the receiver blink
|
|
typedef struct struct_message {
|
|
char a[16];
|
|
} struct_message;
|
|
|
|
struct_message myData;
|
|
|
|
esp_now_peer_info_t peerInfo;
|
|
|
|
#define LEDPIN 0
|
|
#define REEDSENSORPIN 4
|
|
|
|
// callback when data is sent
|
|
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
|
|
Serial.print("\r\nLast Packet Send Status:\t");
|
|
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
|
|
}
|
|
|
|
void setup() {
|
|
pinMode(REEDSENSORPIN, INPUT);
|
|
pinMode(LEDPIN, OUTPUT);
|
|
|
|
Serial.begin(115200);
|
|
Serial.println("Hello World!");
|
|
|
|
WiFi.mode(WIFI_STA);
|
|
|
|
// Init ESP-NOW
|
|
if (esp_now_init() != ESP_OK) {
|
|
Serial.println("Error initializing ESP-NOW");
|
|
return;
|
|
}
|
|
|
|
esp_now_register_send_cb(OnDataSent);
|
|
|
|
// Register peer
|
|
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
|
|
peerInfo.channel = 0;
|
|
peerInfo.encrypt = false;
|
|
|
|
// Add peer
|
|
if (esp_now_add_peer(&peerInfo) != ESP_OK){
|
|
Serial.println("Failed to add peer");
|
|
return;
|
|
}
|
|
|
|
// 2xShort
|
|
digitalWrite(LEDPIN, 1);
|
|
delay(50);
|
|
digitalWrite(LEDPIN, 0);
|
|
delay(50);
|
|
digitalWrite(LEDPIN, 1);
|
|
delay(50);
|
|
digitalWrite(LEDPIN, 0);
|
|
delay(50);
|
|
// Long
|
|
digitalWrite(LEDPIN, 1);
|
|
delay(200);
|
|
digitalWrite(LEDPIN, 0);
|
|
delay(100);
|
|
// Normal
|
|
digitalWrite(LEDPIN, 1);
|
|
delay(100);
|
|
digitalWrite(LEDPIN, 0);
|
|
delay(100);
|
|
}
|
|
|
|
void loop() {
|
|
// Set values to send
|
|
strcpy(myData.a, "Heartbeat");
|
|
|
|
if (!digitalRead(REEDSENSORPIN)) {
|
|
digitalWrite(LEDPIN, 1);
|
|
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
|
|
if (result == ESP_OK) {
|
|
Serial.println("Sent with success");
|
|
}
|
|
else {
|
|
Serial.println("Error sending the data");
|
|
}
|
|
} else {
|
|
digitalWrite(LEDPIN, 0);
|
|
}
|
|
|
|
delay(300);
|
|
}
|