Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <esp_now.h>
- #include <WiFi.h>
- #define LED_Pin 4
- #define BTN_Pin 15
- bool lock = true;
- bool toggle = false;
- int BTN_State; //--> Variable to hold the button state.
- uint8_t broadcastAddress[] = {
- 0x00,
- 0x00,
- 0x00,
- 0x00,
- 0x00,
- 0x00
- }; //--> REPLACE WITH THE MAC Address of your receiver.
- int LED_State_Send = 0;
- int LED_State_Receive;
- String success;
- typedef struct struct_message {
- int led;
- }
- struct_message_send;
- struct_message send_Data;
- struct_message receive_Data;
- 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");
- if (status == 0) {
- success = "Delivery Success :)";
- } else {
- success = "Delivery Fail :(";
- }
- Serial.println(">>>>>");
- }
- void OnDataRecv(const uint8_t * mac,
- const uint8_t * incomingData, int len) {
- memcpy( & receive_Data, incomingData, sizeof(receive_Data));
- Serial.println();
- Serial.println("<<<<< Receive Data:");
- Serial.print("Bytes received: ");
- Serial.println(len);
- LED_State_Receive = receive_Data.led;
- Serial.print("Receive Data: ");
- Serial.println(LED_State_Receive);
- Serial.println("<<<<<");
- if (LED_State_Recived == true && lock == true) {
- toggle = !toggle;
- lock = false;
- }
- if (LED_State_Recived == low && lock == false) {
- lock = true;
- }
- digitalWrite(LED_Pin, LED_State_Receive);
- }
- void setup() {
- Serial.begin(115200);
- pinMode(LED_Pin, OUTPUT);
- pinMode(BTN_Pin, INPUT);
- WiFi.mode(WIFI_STA);
- if (esp_now_init() != ESP_OK) {
- Serial.println("Error initializing ESP-NOW");
- return;
- }
- esp_now_register_send_cb(OnDataSent);
- esp_now_peer_info_t peerInfo;
- memcpy(peerInfo.peer_addr, broadcastAddress, 6);
- peerInfo.channel = 0;
- peerInfo.encrypt = false;
- if (esp_now_add_peer( & peerInfo) != ESP_OK) {
- Serial.println("Failed to add peer");
- return;
- }
- esp_now_register_recv_cb(OnDataRecv); //--> Register for a callback function that will be called when data is received
- }
- void loop() {
- BTN_State = digitalRead(BTN_Pin); //--> Reads and holds button states.
- if (BTN_State == 1) {
- LED_State_Send = !LED_State_Send;
- send_Data.led = LED_State_Send;
- Serial.println();
- Serial.print(">>>>> ");
- Serial.println("Send data");
- esp_err_t result = esp_now_send(broadcastAddress, (uint8_t * ) & send_Data, sizeof(send_Data));
- if (result == ESP_OK) {
- Serial.println("Sent with success");
- } else {
- Serial.println("Error sending the data");
- }
- while (BTN_State == 1) {
- BTN_State = digitalRead(BTN_Pin);
- delay(10);
- }
- }
- }
Add Comment
Please, Sign In to add comment