Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifdef ESP32
- #include <WiFi.h>
- #else
- #include <ESP8266WiFi.h>
- #endif
- #include <PubSubClient.h>
- #include <DHT.h>
- #include <ESP32Servo.h>
- #include <UniversalTelegramBot.h>
- #include <WiFiClientSecure.h>
- // WiFi Configuration
- const char* ssid = "kai";
- const char* password = "lupapassword";
- // MQTT Broker
- #define MQTT_SERVER "192.168.155.4"
- #define MQTT_PORT 1883
- #define MQTT_USER "localmech"
- #define MQTT_PASS "1234"
- // Telegram Bot
- #define BOT_TOKEN "7656293833:AAGYM7SMpJ-reRpHgsSSPkvT2i57Ji88Q24"
- #define CHAT_ID "5188663019"
- WiFiClientSecure secured_client;
- UniversalTelegramBot bot(BOT_TOKEN, secured_client);
- // MQTT Client
- WiFiClient espClient;
- PubSubClient client(espClient);
- // DHT Sensor
- #define DHT_PIN 4
- #define DHT_TYPE DHT11
- DHT dht(DHT_PIN, DHT_TYPE);
- // Pins
- #define LDR_PIN 34
- #define MQ2_PIN 35
- #define PIR_PIN 27
- #define BUZZER_PIN 18
- #define LED_HIJAU 25
- #define LED_MERAH 32
- // #define SERVO_PIN 23
- Servo servoMotor;
- // Variables
- int ldrValue = 0;
- int mq2Value = 0;
- bool pirMotionDetected = false;
- float temperature = 0.0;
- float humidity = 0.0;
- // Thresholds
- const int MQ2_THRESHOLD = 300; // Threshold untuk konsentrasi gas (deteksi bocor)
- // MQTT Topics
- const char* topic_sensor = "smarthome/sensor";
- const char* topic_control = "smarthome/control";
- // Servo control variables
- const int SERVO_OPEN_ANGLE = 90; // Sudut servo saat membuka
- const int SERVO_CLOSE_ANGLE = 0; // Sudut servo saat menutup
- const int SERVO_DELAY = 200; // Waktu delay untuk menutup kembali (ms)
- void setup() {
- servoMotor.attach(23);
- Serial.begin(115200);
- // Connect to WiFi
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(1000);
- Serial.println("Connecting to WiFi...");
- }
- Serial.println("Connected to WiFi!");
- // Initialize sensors and actuators
- dht.begin();
- // servoMotor.attach(SERVO_PIN);
- servoMotor.write(SERVO_CLOSE_ANGLE);
- pinMode(LED_HIJAU, OUTPUT);
- pinMode(LED_MERAH, OUTPUT);
- pinMode(BUZZER_PIN, OUTPUT);
- pinMode(PIR_PIN, INPUT);
- // Initialize MQTT
- client.setServer(MQTT_SERVER, MQTT_PORT);
- client.setCallback(mqttCallback);
- // Telegram SSL configuration
- secured_client.setInsecure();
- Serial.println("Setup complete.");
- }
- void loop() {
- // Ensure MQTT is connected
- if (!client.connected()) {
- reconnectMQTT();
- }
- client.loop();
- // Read sensor data
- readSensors();
- // Read sensor LDR
- checkLDR();
- // Publish data to MQTT
- publishSensorData();
- // Check Telegram messages
- handleTelegramMessages();
- // Control logic
- checkGasLeak();
- checkMotion();
- delay(2000);
- }
- void readSensors() {
- ldrValue = analogRead(LDR_PIN);
- mq2Value = analogRead(MQ2_PIN);
- pirMotionDetected = digitalRead(PIR_PIN);
- temperature = dht.readTemperature();
- humidity = dht.readHumidity();
- }
- void publishSensorData() {
- char payload[256];
- snprintf(payload, sizeof(payload), "{\"temperature\":%.2f,\"humidity\":%.2f,\"ldr\":%d,\"mq2\":%d,\"pir\":%d}",
- temperature, humidity, ldrValue, mq2Value, pirMotionDetected);
- client.publish(topic_sensor, payload);
- Serial.println(payload);
- }
- void checkGasLeak() {
- if (mq2Value > MQ2_THRESHOLD) {
- // Gas bocor terdeteksi
- Serial.println("Gas leak detected!");
- digitalWrite(LED_MERAH, HIGH); // Nyalakan LED merah
- tone(BUZZER_PIN, 1000); // Bunyi buzzer
- // Kirim notifikasi ke Telegram
- bot.sendMessage(CHAT_ID, "Warning: Gas leak detected!", "");
- } else {
- // Tidak ada gas bocor
- digitalWrite(LED_MERAH, LOW); // Matikan LED merah
- noTone(BUZZER_PIN); // Matikan buzzer
- }
- }
- void checkMotion() {
- if (pirMotionDetected) {
- Serial.println("Motion detected!");
- servoMotor.write(SERVO_OPEN_ANGLE); // Buka servo
- bot.sendMessage(CHAT_ID, "Motion detected! Servo opened.", "");
- delay(SERVO_DELAY); // Tunggu sebelum menutup kembali
- servoMotor.write(SERVO_CLOSE_ANGLE); // Tutup servo
- Serial.println("Servo closed.");
- bot.sendMessage(CHAT_ID, "Motion not detected! Servo closed.", "");
- }
- }
- void mqttCallback(char* topic, byte* payload, unsigned int length) {
- String message = "";
- for (int i = 0; i < length; i++) {
- message += (char)payload[i];
- }
- Serial.print("Message received: ");
- Serial.println(message);
- if (!strcmp(topic, topic_control)) {
- if (message == "LED_HIJAU_ON") digitalWrite(LED_HIJAU, HIGH);
- if (message == "LED_HIJAU_OFF") digitalWrite(LED_HIJAU, LOW);
- if (message == "BUZZER_ON") tone(BUZZER_PIN, 1000);
- if (message == "BUZZER_OFF") noTone(BUZZER_PIN);
- }
- }
- void checkLDR() {
- // Jika nilai LDR lebih tinggi dari ambang batas (misalnya 1000, tergantung sensor)
- if (ldrValue > 1000) {
- digitalWrite(LED_HIJAU, HIGH); // Nyalakan LED hijau
- } else {
- digitalWrite(LED_HIJAU, LOW); // Matikan LED hijau
- }
- }
- void reconnectMQTT() {
- while (!client.connected()) {
- Serial.println("Connecting to MQTT...");
- String clientId = "MyIoT";
- clientId += String(random(0xffff), HEX);
- if (client.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) {
- Serial.println("connected");
- client.publish(topic_control, "hello world");
- client.subscribe(topic_control);
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- void handleTelegramMessages() {
- int newMessages = bot.getUpdates(bot.last_message_received + 1);
- for (int i = 0; i < newMessages; i++) {
- String text = bot.messages[i].text;
- if (text == "/status") {
- String message = "Temperature: " + String(temperature) + "°C\n"
- + "Humidity: " + String(humidity) + "%\n"
- + "LDR: " + String(ldrValue) + "\n"
- + "MQ2: " + String(mq2Value) + "\n"
- + "PIR: " + String(pirMotionDetected ? "Motion Detected" : "No Motion");
- bot.sendMessage(CHAT_ID, message, "");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement