#include <WiFi.h>
#include <esp_now.h>
#define PIN_TRIG 3
#define PIN_ECHO 2
// Define the duty cycle period in seconds
#define TIME_TO_SLEEP 2
RTC_DATA_ATTR int bootCount = 0;
uint8_t brcAdr[] = {0x8C, 0xAA, 0xB5, 0x84, 0xFB, 0x90};
esp_now_peer_info_t peerInfo;
void Sent_Data(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("Send Status: ");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Ok" : "Error");
}
//Receiving Callback
void OnDataRecv(const uint8_t * mac, const uint8_t *data, int len) {
Serial.print("Message received: ");
char receivedString[len+1];
memcpy(receivedString, data, len);
receivedString[len] = '\0';
Serial.println(String(receivedString));
}
void staring_point() {
// Start a new measurement:
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result:
int duration = pulseIn(PIN_ECHO, HIGH);
Serial.print("Distance in CM: ");
int distance= duration / 58;
Serial.println(distance);
// Determine parking spot status based on distance
String status = (distance < 50) ? "OCCUPIED" : "FREE";
//delay(1000);
esp_now_send(brcAdr, (uint8_t*)&status[0], status.length());
}
void setup() {
Serial.begin(115200);
++bootCount;
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
WiFi.mode (WIFI_STA);
esp_now_init();
//send callback
esp_now_register_send_cb(Sent_Data);
//receive callback
esp_now_register_recv_cb(OnDataRecv);
// Peer Registration
memcpy(peerInfo.peer_addr, brcAdr, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer (Is possible to register multiple peers)
esp_now_add_peer(&peerInfo);
staring_point();
// esp_sleep_enable_timer_wakeup(DUTY_CYCLE_PERIOD*10 ); // Convert seconds to microseconds
// Serial.flush();
// esp_deep_sleep_start();
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP*1000000 );
Serial.println("ESP32 sleep every " + String(TIME_TO_SLEEP));
Serial.flush();
esp_deep_sleep_start();
}
void loop() {
// // Start a new measurement:
// digitalWrite(PIN_TRIG, HIGH);
// delayMicroseconds(10);
// digitalWrite(PIN_TRIG, LOW);
// // Read the result:
// int duration = pulseIn(PIN_ECHO, HIGH);
// Serial.print("Distance in CM: ");
// int distance= duration / 58;
// Serial.println(distance);
// // Determine parking spot status based on distance
// String status = (distance < 50) ? "OCCUPIED" : "FREE";
// //delay(1000);
// esp_now_send(brcAdr, (uint8_t*)&status[0], status.length());
// // Enter deep sleep mode for the duty cycle period
// // esp_sleep_enable_timer_wakeup(DUTY_CYCLE_PERIOD ); // Convert seconds to microseconds
// // esp_deep_sleep_start();
}