esp-now/random variables/esp32_esp-now_tx.ino
2024-05-31 22:41:38 -07:00

105 lines
2.8 KiB
C++

#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Define the MAC address of the receiver (ESP8266)
uint8_t receiverMACAddress[] = {0x08, 0xF9, 0xE0, 0x6C, 0x75, 0x84};
// Structure to send data
typedef struct struct_message {
char a[32];
int b;
float c;
bool d;
} struct_message;
// Create a struct_message called myData
struct_message myData;
// OLED display width and height, in pixels
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Callback function when data is sent
void onDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status: ");
String statusMessage = status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail";
Serial.println(statusMessage);
// Update the display with the status message
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setCursor(0, 0);
display.println(statusMessage);
display.display();
}
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Initialize OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display();
delay(2000); // Pause for 2 seconds
// Clear the buffer
display.clearDisplay();
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Register send callback
esp_now_register_send_cb(onDataSent);
// Register peer
esp_now_peer_info_t peerInfo;
memset(&peerInfo, 0, sizeof(peerInfo));
memcpy(peerInfo.peer_addr, receiverMACAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
return;
}
// Seed random number generator
randomSeed(analogRead(0));
}
void loop() {
// Generate random values
snprintf(myData.a, sizeof(myData.a), "Value: %d", random(0, 1000));
myData.b = random(0, 100);
myData.c = random(0, 1000) / 100.0;
myData.d = random(0, 2);
// Send message via ESP-NOW
esp_err_t result = esp_now_send(receiverMACAddress, (uint8_t *) &myData, sizeof(myData));
if (result == ESP_OK) {
Serial.println("Sent with success");
} else {
Serial.println("Error sending the data");
}
delay(2000);
}