Advertisement
Painlover

myiot

Jan 20th, 2025
32
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.08 KB | None | 1 0
  1. #ifdef ESP32
  2. #include <WiFi.h>
  3. #else
  4. #include <ESP8266WiFi.h>
  5. #endif
  6. #include <PubSubClient.h>
  7. #include <DHT.h>
  8. #include <ESP32Servo.h>
  9. #include <UniversalTelegramBot.h>
  10. #include <WiFiClientSecure.h>
  11.  
  12. // WiFi Configuration
  13. const char* ssid = "kai";
  14. const char* password = "lupapassword";
  15.  
  16. // MQTT Broker
  17. #define MQTT_SERVER "192.168.155.4"
  18. #define MQTT_PORT 1883
  19. #define MQTT_USER "localmech"
  20. #define MQTT_PASS "1234"
  21.  
  22. // Telegram Bot
  23. #define BOT_TOKEN "7656293833:AAGYM7SMpJ-reRpHgsSSPkvT2i57Ji88Q24"
  24. #define CHAT_ID "5188663019"
  25.  
  26. WiFiClientSecure secured_client;
  27. UniversalTelegramBot bot(BOT_TOKEN, secured_client);
  28.  
  29. // MQTT Client
  30. WiFiClient espClient;
  31. PubSubClient client(espClient);
  32.  
  33. // DHT Sensor
  34. #define DHT_PIN 4
  35. #define DHT_TYPE DHT11
  36. DHT dht(DHT_PIN, DHT_TYPE);
  37.  
  38. // Pins
  39. #define LDR_PIN 34
  40. #define MQ2_PIN 35
  41. #define PIR_PIN 27
  42. #define BUZZER_PIN 18
  43. #define LED_HIJAU 25
  44. #define LED_MERAH 32
  45. // #define SERVO_PIN 23
  46.  
  47. Servo servoMotor;
  48.  
  49. // Variables
  50. int ldrValue = 0;
  51. int mq2Value = 0;
  52. bool pirMotionDetected = false;
  53. float temperature = 0.0;
  54. float humidity = 0.0;
  55.  
  56. // Thresholds
  57. const int MQ2_THRESHOLD = 300;  // Threshold untuk konsentrasi gas (deteksi bocor)
  58.  
  59. // MQTT Topics
  60. const char* topic_sensor = "smarthome/sensor";
  61. const char* topic_control = "smarthome/control";
  62.  
  63. // Servo control variables
  64. const int SERVO_OPEN_ANGLE = 90;  // Sudut servo saat membuka
  65. const int SERVO_CLOSE_ANGLE = 0;  // Sudut servo saat menutup
  66. const int SERVO_DELAY = 200;      // Waktu delay untuk menutup kembali (ms)
  67.  
  68. void setup() {
  69.   servoMotor.attach(23);
  70.   Serial.begin(115200);
  71.  
  72.   // Connect to WiFi
  73.   WiFi.begin(ssid, password);
  74.   while (WiFi.status() != WL_CONNECTED) {
  75.     delay(1000);
  76.     Serial.println("Connecting to WiFi...");
  77.   }
  78.   Serial.println("Connected to WiFi!");
  79.  
  80.   // Initialize sensors and actuators
  81.   dht.begin();
  82.   // servoMotor.attach(SERVO_PIN);
  83.   servoMotor.write(SERVO_CLOSE_ANGLE);
  84.  
  85.   pinMode(LED_HIJAU, OUTPUT);
  86.   pinMode(LED_MERAH, OUTPUT);
  87.   pinMode(BUZZER_PIN, OUTPUT);
  88.   pinMode(PIR_PIN, INPUT);
  89.  
  90.   // Initialize MQTT
  91.   client.setServer(MQTT_SERVER, MQTT_PORT);
  92.   client.setCallback(mqttCallback);
  93.  
  94.   // Telegram SSL configuration
  95.   secured_client.setInsecure();
  96.  
  97.   Serial.println("Setup complete.");
  98. }
  99.  
  100. void loop() {
  101.   // Ensure MQTT is connected
  102.   if (!client.connected()) {
  103.     reconnectMQTT();
  104.   }
  105.   client.loop();
  106.  
  107.   // Read sensor data
  108.   readSensors();
  109.  
  110.   // Read sensor LDR
  111.   checkLDR();
  112.  
  113.   // Publish data to MQTT
  114.   publishSensorData();
  115.  
  116.   // Check Telegram messages
  117.   handleTelegramMessages();
  118.  
  119.   // Control logic
  120.   checkGasLeak();
  121.   checkMotion();
  122.  
  123.   delay(2000);
  124. }
  125.  
  126. void readSensors() {
  127.   ldrValue = analogRead(LDR_PIN);
  128.   mq2Value = analogRead(MQ2_PIN);
  129.   pirMotionDetected = digitalRead(PIR_PIN);
  130.   temperature = dht.readTemperature();
  131.   humidity = dht.readHumidity();
  132. }
  133.  
  134. void publishSensorData() {
  135.   char payload[256];
  136.   snprintf(payload, sizeof(payload), "{\"temperature\":%.2f,\"humidity\":%.2f,\"ldr\":%d,\"mq2\":%d,\"pir\":%d}",
  137.            temperature, humidity, ldrValue, mq2Value, pirMotionDetected);
  138.   client.publish(topic_sensor, payload);
  139.   Serial.println(payload);
  140. }
  141.  
  142. void checkGasLeak() {
  143.   if (mq2Value > MQ2_THRESHOLD) {
  144.     // Gas bocor terdeteksi
  145.     Serial.println("Gas leak detected!");
  146.     digitalWrite(LED_MERAH, HIGH);  // Nyalakan LED merah
  147.     tone(BUZZER_PIN, 1000);         // Bunyi buzzer
  148.     // Kirim notifikasi ke Telegram
  149.     bot.sendMessage(CHAT_ID, "Warning: Gas leak detected!", "");
  150.   } else {
  151.     // Tidak ada gas bocor
  152.     digitalWrite(LED_MERAH, LOW);  // Matikan LED merah
  153.     noTone(BUZZER_PIN);            // Matikan buzzer
  154.   }
  155. }
  156.  
  157. void checkMotion() {
  158.   if (pirMotionDetected) {
  159.     Serial.println("Motion detected!");
  160.     servoMotor.write(SERVO_OPEN_ANGLE);  // Buka servo
  161.     bot.sendMessage(CHAT_ID, "Motion detected! Servo opened.", "");
  162.     delay(SERVO_DELAY);                   // Tunggu sebelum menutup kembali
  163.     servoMotor.write(SERVO_CLOSE_ANGLE);  // Tutup servo
  164.     Serial.println("Servo closed.");
  165.     bot.sendMessage(CHAT_ID, "Motion not detected! Servo closed.", "");
  166.   }
  167. }
  168.  
  169. void mqttCallback(char* topic, byte* payload, unsigned int length) {
  170.   String message = "";
  171.   for (int i = 0; i < length; i++) {
  172.     message += (char)payload[i];
  173.   }
  174.   Serial.print("Message received: ");
  175.   Serial.println(message);
  176.  
  177.   if (!strcmp(topic, topic_control)) {
  178.     if (message == "LED_HIJAU_ON") digitalWrite(LED_HIJAU, HIGH);
  179.     if (message == "LED_HIJAU_OFF") digitalWrite(LED_HIJAU, LOW);
  180.     if (message == "BUZZER_ON") tone(BUZZER_PIN, 1000);
  181.     if (message == "BUZZER_OFF") noTone(BUZZER_PIN);
  182.   }
  183. }
  184.  
  185. void checkLDR() {
  186.   // Jika nilai LDR lebih tinggi dari ambang batas (misalnya 1000, tergantung sensor)
  187.   if (ldrValue > 1000) {
  188.     digitalWrite(LED_HIJAU, HIGH);  // Nyalakan LED hijau
  189.   } else {
  190.     digitalWrite(LED_HIJAU, LOW);  // Matikan LED hijau
  191.   }
  192. }
  193.  
  194. void reconnectMQTT() {
  195.   while (!client.connected()) {
  196.     Serial.println("Connecting to MQTT...");
  197.     String clientId = "MyIoT";
  198.     clientId += String(random(0xffff), HEX);
  199.     if (client.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) {
  200.       Serial.println("connected");
  201.       client.publish(topic_control, "hello world");
  202.       client.subscribe(topic_control);
  203.     } else {
  204.       Serial.print("failed, rc=");
  205.       Serial.print(client.state());
  206.       Serial.println(" try again in 5 seconds");
  207.       delay(5000);
  208.     }
  209.   }
  210. }
  211.  
  212. void handleTelegramMessages() {
  213.   int newMessages = bot.getUpdates(bot.last_message_received + 1);
  214.   for (int i = 0; i < newMessages; i++) {
  215.     String text = bot.messages[i].text;
  216.     if (text == "/status") {
  217.       String message = "Temperature: " + String(temperature) + "°C\n"
  218.                        + "Humidity: " + String(humidity) + "%\n"
  219.                        + "LDR: " + String(ldrValue) + "\n"
  220.                        + "MQ2: " + String(mq2Value) + "\n"
  221.                        + "PIR: " + String(pirMotionDetected ? "Motion Detected" : "No Motion");
  222.       bot.sendMessage(CHAT_ID, message, "");
  223.     }
  224.   }
  225. }
  226.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement