#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#define TRIG_PIN 4
#define ECHO_PIN 2
#define Buzzer 13
#define Led1 25
#define Led2 26
#define Led3 27
float duration_us, distance_cm;
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define BOT_TOKEN "6615261736:AAEQGpcZkXV8Z_dJWmbRxb-cOwJaS4ZfIew"
#define CHAT_ID "6242476867"
WiFiClientSecure secured_client;
UniversalTelegramBot bot (BOT_TOKEN, secured_client);
const unsigned long BOT_MTBS = 1000;
unsigned long bot_lasttime;
void setup() {
Serial.begin (9600);
while (!Serial)
delay(3000);
Serial.print("CONNECTING TO: ");
Serial.print(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WIFI CONNECTED");
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(Led1, OUTPUT);
pinMode(Led2, OUTPUT);
pinMode(Led3, OUTPUT);
pinMode(Buzzer, OUTPUT);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration_us = pulseIn(ECHO_PIN, HIGH);
distance_cm = 0.017 * duration_us;
if (distance_cm < 10)
{
digitalWrite(Led1, HIGH);
digitalWrite(Led2, LOW);
digitalWrite(Led3, LOW);
digitalWrite(Buzzer, HIGH);
}
else if (distance_cm < 100)
{
digitalWrite(Led1, LOW);
digitalWrite(Led2, HIGH);
digitalWrite(Led3, LOW);
digitalWrite(Buzzer, LOW);
}
else if (distance_cm < 200)
{
digitalWrite(Led1, LOW);
digitalWrite(Led2, LOW);
digitalWrite(Led3, HIGH);
digitalWrite(Buzzer, LOW);
}
if (millis() - bot_lasttime > BOT_MTBS)
{
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages)
{
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
bot_lasttime = millis();
}
Serial.print("Ketinggian Air: ");
Serial.print(distance_cm);
Serial.println(" Cm");
delay(1000);
}
void handleNewMessages(int numNewMessages)
{
Serial.print("handleNewMessages ");
Serial.println(numNewMessages);
for (int i = 0; i < numNewMessages; i++)
{
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID )
{
bot.sendMessage(chat_id, "Unauthorized user", "");
}
else
{
String text = bot.messages[i].text;
String from_name = bot.messages[i].from_name;
if (from_name == "")
from_name = "Guest";
if (text == "/WaterLevel")
{ String msg = "Ketinggian Air: ";
msg += msg.concat(distance_cm);
msg += " Cm";
bot.sendMessage(chat_id,msg, "");
}
if (text == "/start")
{
String welcome = "Proyek Akhir RADINDA SYAFITRI 20066041\n";
welcome += "Jika Ketinggian Air < 200 Cm, Tanki Hampir Kosong \n";
welcome += "Jika Ketinggian Air < 100 Cm, Tanki Terisi Setengah \n";
welcome += "Jika Ketinggian Air < 10 Cm, Tanki Penuh \n";
welcome += "/WaterLevel : Cek Ketinggian Akhir Saat ini \n";
bot.sendMessage(chat_id, welcome, "Markdown");
}
}
}
}