/** Challenge 1 Iot ***
* Pablo Martellucci *
* Maryam *
* *
**********************/
// Leader personcode 10668552
// X = 52 % 50 + 5; // duty cycle period
#include <WiFi.h>
#include <esp_now.h>
#define ECHO 13
#define TRIGGER 14
#define uS_TO_S_FACTOR 1000000
#define TIME_TO_SLEEP 7
uint8_t broadcastAddress[] = {0x8C, 0xAA, 0xB5, 0x84, 0xFB, 0x90}; // MAC receiver
RTC_DATA_ATTR int bootCount = 0;
esp_now_peer_info_t peerInfo;
void print_wake_up_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason){
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}
// 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");
}
//Receiving Callback
void OnDataRecv(const uint8_t * mac, const uint8_t *data, int len) {
Serial.print("Message received: ");
char receivedString[len];
memcpy(receivedString, data, len);
Serial.println(String(receivedString));
}
int get_distance() {
// Start a new measurement: // to estimate the presence of a car: distance < 50cm
digitalWrite(TRIGGER, HIGH); // To change the distance while the simulation is running, click on
delayMicroseconds(10); // the HC-SR04 drawing in the diagram and use the slider to set the
digitalWrite(TRIGGER, LOW); // distance value. You can choose any value between 2cm and 400cm
// Read the result:
int duration = pulseIn(ECHO, HIGH);
// Calculates the distance
int distance = duration / 58;
return distance; // centimeters
}
void setup() {
Serial.begin(115200);
pinMode(ECHO, INPUT);
pinMode(TRIGGER, OUTPUT);
WiFi.mode(WIFI_STA);
++bootCount; // Increment boot number and print it every reboot
Serial.println("Boot number: " + String(bootCount));
esp_now_init();
//send callback
esp_now_register_send_cb(OnDataSent);
//receive callback
esp_now_register_recv_cb(OnDataRecv);
// Peer Registration
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer (Is possible to register multiple peers)
esp_now_add_peer(&peerInfo);
Serial.println("Measured distance: " + String(get_distance()) + "cm");
String message;
if( get_distance() <= 50){Serial.println("ooooooooooooooooooooooooooo");
message = "OCCUPIED";
}
else{Serial.println("ffffffffffffffffffffffffffff");
message = "FREE";
}
esp_now_send(broadcastAddress, (uint8_t*)message.c_str(), message.length() + 1);
//esp_now_deinit();
//WiFi.mode(WIFI_OFF);
Serial.println("Going to sleep now");
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.println("ESP32 sleep every " + String(TIME_TO_SLEEP));
Serial.flush();
esp_deep_sleep_start();
Serial.println("This will never be printed");
}
void loop() {
delay(10);
}