83 lines
2.2 KiB
C++
83 lines
2.2 KiB
C++
#include <esp_now.h>
|
|
#include <WiFi.h>
|
|
|
|
// REPLACE WITH THE MAC Address of your receiver - 1C:69:20:E9:13:EC
|
|
uint8_t broadcastAddress[] = {0x1C, 0x69, 0x20, 0xE9, 0x13, 0xEC}; // Replace with actual receiver MAC address
|
|
|
|
// Define variables to be sent
|
|
typedef struct struct_message {
|
|
int x;
|
|
int y;
|
|
bool b;
|
|
} struct_message;
|
|
|
|
// Create a struct_message called myData
|
|
struct_message myData;
|
|
|
|
// Callback when data is sent
|
|
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
|
|
// Serial.print("Last Packet Send Status: ");
|
|
// Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
|
|
}
|
|
|
|
void setup() {
|
|
|
|
// Initialize Serial Monitor
|
|
Serial.begin(115200);
|
|
|
|
pinMode(34, INPUT_PULLUP);
|
|
|
|
// Set device as a Wi-Fi Station
|
|
WiFi.mode(WIFI_STA);
|
|
|
|
// Initialize ESP-NOW
|
|
if (esp_now_init() != ESP_OK) {
|
|
Serial.println("Error initializing ESP-NOW");
|
|
return;
|
|
}
|
|
|
|
// Register callback function to get the status of transmitted packets
|
|
esp_now_register_send_cb(OnDataSent);
|
|
|
|
// Register peer information (receiver)
|
|
esp_now_peer_info_t peerInfo;
|
|
|
|
memcpy(peerInfo.peer_addr, broadcastAddress, sizeof(broadcastAddress));
|
|
peerInfo.channel = 0;
|
|
peerInfo.encrypt = false;
|
|
|
|
// Add peer
|
|
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
|
|
Serial.println("Failed to add peer");
|
|
return;
|
|
}
|
|
|
|
Serial.println("Sender ready. Sending data...");
|
|
}
|
|
|
|
void loop() {
|
|
|
|
// Set values to send (example: read analog pins and digital pin)
|
|
myData.x = map(analogRead(32), 0, 4095, -100, +100); // Map analog value from pin GPIO32
|
|
myData.y = map(analogRead(33), 0, 4095, -100, +100); // Map analog value from pin GPIO33
|
|
myData.b = !digitalRead(34); // Read digital value from pin GPIO34
|
|
|
|
// Send message via ESP-NOW
|
|
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));
|
|
|
|
if (result == ESP_OK) {
|
|
// Serial.print("Sent successfully -> ");
|
|
// Serial.print("x: ");
|
|
Serial.print(myData.x);
|
|
Serial.print(" ");
|
|
Serial.print(myData.y);
|
|
Serial.print(" ");
|
|
Serial.println(myData.b);
|
|
|
|
} else {
|
|
Serial.println("Error sending the data");
|
|
}
|
|
|
|
delay(20); // Small delay between sends to avoid flooding the network
|
|
}
|