#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST";
const char* pass = "";
#define BOTtoken "7099855693:AAHhqzd92h34XfizxKlW_R-yOj8hgSbyha8"
#define CHAT_ID "1275934112"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
const int pirPin = 15;
const int trigPin = 4;
const int echoPin = 5;
const int buzzerPin = 18;
const int redLedPin = 19;
const int yellowLedPin = 21;
const int greenLedPin = 22;
void myTone(int pin){
ledcAttachPin(pin, 0);
ledcWriteNote(0, NOTE_F, 4);
}
void myNoTone(int pin){
ledcDetachPin(pin);
}
long duration;
int distance = false;
bool motionDetected = false;
void ICACHE_RAM_ATTR detectsMovement(){
motionDetected = true;
distance = true;
}
void handleTelegramMessages() {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
for (int i = 0; i < numNewMessages; i++) {
String message = bot.messages[i].text;
if (message == "/buzzer_on") {
myTone(buzzerPin);
bot.sendMessage(CHAT_ID, "Buzzer is ON");
} else if (message == "/buzzer_off") {
myNoTone(buzzerPin);
bot.sendMessage(CHAT_ID, "Buzzer is OFF");
}
// Update last message received ID
bot.last_message_received = bot.messages[i].update_id + 1;
}
}
void setup() {
Serial.begin(115200);
pinMode(pirPin, INPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLedPin, OUTPUT);
pinMode(yellowLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
// Setup PWM on buzzerPin
pinMode(buzzerPin, OUTPUT);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
attachInterrupt(digitalPinToInterrupt(pirPin && echoPin), detectsMovement, RISING);
Serial.print("Connecting Wifi: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
bot.sendMessage(CHAT_ID, "BOT memulai", "");
}
void loop() {
if(motionDetected && distance){
bot.sendMessage(CHAT_ID, "HAMA MENDEKAT!!!!");
Serial.println("HAMA MENDEKAT");
motionDetected = false;
distance = false;
}
int pirState = digitalRead(pirPin);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
if (pirState == HIGH && distance <= 200) {
myTone(buzzerPin); // Mengatur duty cycle buzzer menjadi 50%
Serial.println("Motion detected or object within 2 meters!");
} else {
myNoTone(buzzerPin); // Mematikan buzzer
}
// Logika lampu lalu lintas
digitalWrite(redLedPin, pirState == HIGH ? HIGH : LOW);
digitalWrite(yellowLedPin, distance <= 200 ? HIGH : LOW);
digitalWrite(greenLedPin, (pirState == LOW && distance > 200) ? HIGH : LOW);
delay(1000);
handleTelegramMessages();
}