#include <esp_now.h>
#include <WiFi.h>
// Pin assignments for the HC-SR04 sensor
#define TRIGGER_PIN 26
#define ECHO_PIN 25
#define uS_TO_S_FACTOR 1000000LL // Conversion factor from microseconds to seconds
#define SLEEP_TIME 54 // Sleep time in seconds calculated from personal code
// ESP-NOW broadcast address
uint8_t broadcastAddress[] = {0x8C, 0xAA, 0xB5, 0x84, 0xFB, 0x90};
esp_now_peer_info_t peerInfo;
// Callback when data is sent
void onDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("Send Status: ");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Success" : "Error");
}
// Initialize the sensor and ESP-NOW communication
void setup() {
Serial.begin(115200); // Start serial communication at 115200 baud
WiFi.mode(WIFI_STA); // Set Wi-Fi to Station mode
// Initialize ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Register ESP-NOW peers
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
esp_now_add_peer(&peerInfo);
// Register callback functions
esp_now_register_send_cb(onDataSent);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the time it takes for the echo to return
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance based on the duration of the echo
int distance = duration / 58; // Conversion from pulse duration to distance
// Determine the parking spot status based on the measured distance
String message = (distance < 50) ? "OCCUPIED" : "FREE";
Serial.print("Parking Status: ");
Serial.println(message);
// Send the status message via ESP-NOW
esp_now_send(broadcastAddress, (uint8_t *)message.c_str(), message.length() + 1);
// Enter deep sleep for the calculated duration
Serial.println("Entering deep sleep mode");
esp_sleep_enable_timer_wakeup(SLEEP_TIME * uS_TO_S_FACTOR);
esp_deep_sleep_start();
}