Gas Detector
Menggunakan sensor MQ-135, Wemos ESP 8266, dan buzzzer. Kode dibawah ini sudah termasuk kode untuk mengirimkan sinyal ke telegram pengguna menggunakan bot.
FULL CODE
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> // Telegram BOT library
// WiFi
const char* ssid = “Lab PnP”;
const char* password = “12345678”;
// Token BOT Tele
#define BOTtoken “6680098384:AAEgeTZ98Q6rLsbsMjc3PrCBIP5IkKlnn_4”
// id penerima
#define CHAT_ID “6115744167”
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
// Checks for new messages every 1 second.
int botRequestDelay = 0;
int x;
unsigned long lastTimeBotRan;
bool ledState = LOW;
// Handle what happens when you receive new messages
void handleNewMessages(int numNewMessages) {
Serial.println(“handleNewMessages”);
Serial.println(String(numNewMessages));
for (int i=0; i<numNewMessages; i++) {
// Chat id of the requester
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, “Unauthorized user”, “”);
continue;
}
// Print the received message
String text = bot.messages[i].text;
Serial.println(text);
String from_name = bot.messages[i].from_name;
if (text == “/start”) {
String welcome = “Welcome, “ + from_name + “.\n”;
welcome += “Gunakan Perintah dibawah \n”;
welcome += “/status untuk melihat status \n”;
bot.sendMessage(chat_id, welcome, “”);
}
if (text == “/status”) {
x = analogRead(A0);
String y = String(x);
bot.sendMessage(chat_id, y, “”);
}
}
}
void setup() {
Serial.begin(115200);
#ifdef ESP8266
configTime(0, 0, “pool.ntp.org“); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
#endif
pinMode(D5, OUTPUT);
pinMode(A0, INPUT);
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
#ifdef ESP32
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println(“Connecting to WiFi..”);
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
digitalWrite(D5, HIGH);
delay(500);
digitalWrite(D5, LOW);
}
void loop() {
if (millis() > lastTimeBotRan + botRequestDelay) {
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);
}
lastTimeBotRan = millis();
}
x = analogRead(A0);
Serial.println(x);
if(x >= 600) {
digitalWrite(D5, HIGH);
Serial.println(x);
bot.sendMessage(CHAT_ID, “Meledak”, “”);
}
else {
digitalWrite(D5, LOW);
}
}