#include <WiFi.h>
#include <HTTPClient.h>
// ================= WIFI =================
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ================= TELEGRAM =================
String botToken = "8593534577:AAFaeFrGxeubqWcEK-P6fO_04xK0x0B7A5s";
String chatID = "1238392831";
// ================= PINS =================
// Metal
const int trigMetal = 5;
const int echoMetal = 18;
// Paper
const int trigPaper = 17;
const int echoPaper = 16;
// Plastic
const int trigPlastic = 27;
const int echoPlastic = 26;
// ================= THRESHOLD =================
const float fullThreshold = 4.0;
const float resetThreshold = 9.0;
// ================= FLAGS =================
bool metalSent = false;
bool paperSent = false;
bool plasticSent = false;
// ================= FUNCTION =================
float getDistance(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) return -1;
return duration * 0.0343 / 2;
}
// ================= TELEGRAM =================
void sendTelegram(String msg) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "https://api.telegram.org/bot" + botToken +
"/sendMessage?chat_id=" + chatID +
"&text=" + msg;
http.begin(url);
int code = http.GET();
Serial.print("Telegram: ");
Serial.println(code);
http.end();
}
}
// ================= CHECK BIN =================
void checkBin(float distance, String name, bool &sentFlag) {
if (distance == -1) {
Serial.println(name + ": No reading");
return;
}
Serial.print(name);
Serial.print(": ");
Serial.print(distance);
Serial.println(" cm");
if (distance <= fullThreshold && !sentFlag) {
sendTelegram("Alert: " + name + " bin is FULL");
sentFlag = true;
}
if (distance > resetThreshold) {
sentFlag = false;
}
}
// ================= SETUP =================
void setup() {
Serial.begin(115200);
pinMode(trigMetal, OUTPUT);
pinMode(echoMetal, INPUT);
pinMode(trigPaper, OUTPUT);
pinMode(echoPaper, INPUT);
pinMode(trigPlastic, OUTPUT);
pinMode(echoPlastic, INPUT);
WiFi.begin(ssid, password);
Serial.print("Connecting WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected!");
sendTelegram("Smart bin system is online");
}
// ================= LOOP =================
void loop() {
float d1 = getDistance(trigMetal, echoMetal);
float d2 = getDistance(trigPaper, echoPaper);
float d3 = getDistance(trigPlastic, echoPlastic);
checkBin(d1, "Metal", metalSent);
checkBin(d2, "Paper", paperSent);
checkBin(d3, "Plastic", plasticSent);
Serial.println("------------------");
delay(2000);
}