#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Ultrasonic.h>
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// Wowki details
const char* wowkiServer = "http://api.wowki.io/v1/device";
const char* deviceId = "YOUR_DEVICE_ID";
const char* apiKey = "YOUR_API_KEY";
// Twilio details
const char* twilioAccountSid = "YOUR_TWILIO_ACCOUNT_SID";
const char* twilioAuthToken = "YOUR_TWILIO_AUTH_TOKEN";
const char* twilioPhoneNumber = "YOUR_TWILIO_PHONE_NUMBER";
const char* recipientPhoneNumber = "RECIPIENT_PHONE_NUMBER";
// Ultrasonic sensor pins
const int triggerPin = 23; // GPIO pin connected to the sensor's trigger pin
const int echoPin = 22; // GPIO pin connected to the sensor's echo pin
Ultrasonic ultrasonic(triggerPin, echoPin);
// LED indicator pin
const int ledPin = 21; // GPIO pin connected to the LED
// Water level threshold (in centimeters)
const int waterLevelThreshold = 10;
bool alertSent = false;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println(" connected");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
float distance = ultrasonic.read(CM);
if (distance <= waterLevelThreshold) {
if (!alertSent) {
Serial.println("Water level exceeded threshold!");
sendSMSAlert();
digitalWrite(ledPin, HIGH); // Turn on LED
alertSent = true;
}
} else {
digitalWrite(ledPin, LOW); // Turn off LED
alertSent = false;
}
} else {
Serial.println("WiFi not connected");
// Attempt to reconnect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println(" reconnected");
}
delay(2000); // Check water level every 2 seconds
}
void sendSMSAlert() {
HTTPClient http;
String url = "https://api.twilio.com/2010-04-01/Accounts/" + String(twilioAccountSid) + "/Messages.json";
http.begin(url);
http.setAuthorization(twilioAccountSid, twilioAuthToken);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String message = "To=" + String(recipientPhoneNumber) +
"&From=" + String(twilioPhoneNumber) +
"&Body=Water level exceeded threshold!";
int httpResponseCode = http.POST(message);
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.print("SMS alert sent! Response code: ");
Serial.println(httpResponseCode);
Serial.println(payload);
} else {
Serial.print("Error sending SMS alert. HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end();
}