#include <WiFi.h>
#include <esp_now.h>
#define PIN_TRIG 32
#define PIN_ECHO 33
// MAC receiver
uint8_t broadcastAddress[] = {0x8C, 0xAA, 0xB5, 0x84, 0xFB, 0x90};
esp_now_peer_info_t peerInfo;
// Sleep time
#define TIME_TO_SLEEP 39 // Time ESP32 will go to sleep (in seconds) 39
// Sending callback
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("Send Status: ");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Ok " : "Error ");
}
void setup() {
Serial.begin(115200);
delay(1000); // Wait for serial monitor to initialize (if necessary)
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
// Start a new measurement
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result
int duration = pulseIn(PIN_ECHO, HIGH);
float distance = duration / 58.0;
String message = distance < 50 ? "OCCUPIED" : "FREE";
//Serial.println("TIMESTAMP: "+String(x));
// Initialize WiFi and ESP-NOW
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Register send and receive callbacks
esp_now_register_send_cb(OnDataSent);
// Peer Registration
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
esp_now_add_peer(&peerInfo);
// Send message via ESP-NOW
esp_now_send(broadcastAddress, (uint8_t*)message.c_str(), message.length() + 1);
// without the println we need to introduce a small delay to ensure
// that the message is sent before entering deep sleep
Serial.println(message);
// Deep sleep
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * 1000000);
Serial.flush();
esp_deep_sleep_start();
}
void loop() {
// Not used since we are going directly to deep sleep after setup
}