#include <Wire.h>
#include <ESPNow.h>
// Define the data structure to hold GPIO and I2C data
struct SensorData {
uint8_t gpioData;
uint8_t i2cData;
};
// Create an instance of the ESPNow class
ESPNow espNow;
// Define the device addresses for sending/receiving messages
uint8_t masterAddress[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; // address of the master ESP32
uint8_t slaveAddress[] = {0x06, 0x05, 0x04, 0x03, 0x02, 0x01}; // address of the slave ESP32
// Function to handle receiving messages from the master ESP32
void OnDataReceived(const uint8_t *macAddr, const uint8_t *data, int dataLen) {
if (memcmp(macAddr, masterAddress, 6) == 0) {
// Parse received data as SensorData struct
SensorData receivedData;
memcpy(&receivedData, data, sizeof(SensorData));
// Perform desired action with received GPIO and I2C data
// ... (e.g., update peripherals, control actuators, etc.)
}
}
// Function to send GPIO and I2C data to the slave ESP32
void sendDataToSlave(SensorData data) {
espNow.send(slaveAddress, reinterpret_cast<uint8_t*>(&data), sizeof(data));
}
// Example Arduino program from the Examples Library
void exampleArduinoProgram() {
// Place any example program code from the Arduino Examples Library here
// ... (e.g., blink LED, read temperature sensor, etc.)
// Update GPIO and I2C data
SensorData sensorData;
sensorData.gpioData = 0x01;
sensorData.i2cData = 0x10;
sendDataToSlave(sensorData);
}
void setup() {
// Initialize Serial communication for debugging (optional)
Serial.begin(115200);
// Initialize ESPNow
espNow.init();
espNow.onDataReceived(OnDataReceived);
}
void loop() {
// Run your desired example program
exampleArduinoProgram();
// Implement other code as needed
// ...
}
In this code, the master ESP32 acts as the main controller where you can run any example program from the Arduino Examples Library. Upon receiving data from the master, the slave ESP32 will update its GPIO and I2C accordingly.