#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include "HX711.h"
#include <ESP32Servo.h>
#define DT 16
#define SCK 4
#define SensorTRG 25
#define SensorECH 26
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const String botToken = "YOUR_TELEGRAM_BOT_TOKEN"; // Ganti dengan token bot Telegram Anda
WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);
Servo myServo;
HX711 scale;
const int servoPin = 19;
long lastTime = 0;
const int delayTime = 2000; // Interval untuk memeriksa pesan baru
void setup() {
Serial.begin(115200);
scale.begin(DT, SCK);
myServo.attach(servoPin, 500, 2400);
myServo.write(90);
pinMode(SensorTRG, OUTPUT);
pinMode(SensorECH, INPUT);
// Koneksi WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Aman untuk komunikasi HTTPS
client.setInsecure();
}
void handleNewMessages(int numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
String text = bot.messages[i].text;
if (text == "/start") {
bot.sendMessage(chat_id, "Selamat datang di AutoCat Meal Bot. Gunakan perintah /dispense untuk mengeluarkan makanan", "");
}
else if (text == "/dispense") {
double weight = weightRead();
long distance = readDistance();
if (weight > 1) {
containerOpen();
bot.sendMessage(chat_id, "Container dibuka, sedang mengeluarkan makanan.", "");
} else {
bot.sendMessage(chat_id, "Container kosong, silakan isi ulang.", "");
}
}
else if (text == "/stop") {
containerClose();
bot.sendMessage(chat_id, "Container ditutup.", "");
}
}
}
long readDistance() {
digitalWrite(SensorTRG, LOW);
delayMicroseconds(2);
digitalWrite(SensorTRG, HIGH);
delayMicroseconds(10);
digitalWrite(SensorTRG, LOW);
long duration = pulseIn(SensorECH, HIGH);
long distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
return distance;
}
void containerOpen() {
Serial.println("Dispensing FOOD..!!");
myServo.write(0);
}
void containerClose() {
myServo.write(90);
Serial.println("Food dispensed...!!");
}
float weightRead() {
if (scale.is_ready()) {
Serial.println("Reading Weight..");
float weight = scale.get_units();
weight *= 2.381;
float kilograms = weight / 1000;
Serial.print("Weight : ");
Serial.print(kilograms);
Serial.println(" kgs");
return kilograms;
} else {
Serial.println("Error in Reading weight value");
return 0;
}
}
void loop() {
if (millis() > lastTime + delayTime) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTime = millis();
}
}