#include <WiFi.h>
#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>
#define TRIGGER_PIN 5
#define ECHO_PIN 4
// WiFi credentials
const char SSID[] = "Wokwi-GUEST";
const char PASSWORD[] = "";
// IoT Cloud variables
int water_level;
int lowest_level;
int highest_level;
// Callback function to handle cloud updates
void onWaterLevelChange() {
// Handle water level changes in the cloud
}
void setup() {
Serial.begin(9600);
// Set up WiFi connection
ArduinoCloud.begin(SSID, PASSWORD);
// Set up pins for ultrasonic sensor
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Set up IoT Cloud variables
ArduinoCloud.setThingId("42c44d68-3f0b-407f-ac6c-b088467ddfdd");
ArduinoCloud.addProperty(water_level, READ_WRITE, ON_CHANGE, onWaterLevelChange);
ArduinoCloud.addProperty(lowest_level, READ_WRITE, ON_CHANGE, NULL);
ArduinoCloud.addProperty(highest_level, READ_WRITE, ON_CHANGE, NULL);
}
void loop() {
ArduinoCloud.update();
// Measure water level
long duration, distance;
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1;
// Update water level variables
water_level = distance;
if (distance < lowest_level || lowest_level == 0) {
lowest_level = distance;
}
if (distance > highest_level) {
highest_level = distance;
}
// Print water level to serial monitor
Serial.print("Water level: ");
Serial.print(water_level);
Serial.println(" cm");
delay(1000);
}