/*
 * This ESP32 code is created by esp32io.com
 *
 * This ESP32 code is released in the public domain
 *
 * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-ldr-module
 */

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

#define DO_PIN1 13  // ESP32's pin GPIO13 connected to DO pin of the ldr module
#define DO_PIN2  4  // ESP32's pin GPIO13 connected to DO pin of the ldr module
#define DO_PIN3  2  // ESP32's pin GPIO13 connected to DO pin of the ldr module

#define LED_PIN           21  // ESP32 pin GPIO22 connected to LED

const int buzzer = 22; //buzzer to arduino pin 9


BluetoothSerial SerialBT;

void setup() {
  // initialize serial communication
 Serial.begin(9600);
 SerialBT.begin("MY_ESP32"); //Bluetooth device name
 Serial.println("The device started, now you can pair it with bluetooth!");

  // initialize the ESP32's pin as an input
  pinMode(DO_PIN1, INPUT);
  pinMode(DO_PIN2, INPUT);
  pinMode(DO_PIN3, INPUT);

  pinMode(LED_PIN, OUTPUT); // set ESP32 pin to output mode
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
}

void loop() {
  int motionState = digitalRead(DO_PIN1);
  if
   (motionState == HIGH){
     Serial.println("MOTION DETECTED");
     SerialBT.println("MOTION DETECTED");
    digitalWrite(LED_PIN, HIGH);      //Turn LED ON
    tone(buzzer, 1000); // Send 1KHz sound signal...
    delay(200);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(200);        // ...for 1sec
   } 
    else {
    //      Serial.println("EVERYTHING OK");
    digitalWrite(LED_PIN, LOW);  // turn off LED
  }
  //delay(200);
  
    
  int fireState = digitalRead(DO_PIN2);
  
  if
   (fireState == LOW){
    Serial.println("FIRE DETECTED");
    SerialBT.println("FIRE DETECTED");
    digitalWrite(LED_PIN, HIGH);      //Turn LED ON
    tone(buzzer, 750); // Send 1KHz sound signal...
    delay(200);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(200);        // ...for 1sec
   } 
    else {
    //      Serial.println("EVERYTHING OK");
    digitalWrite(LED_PIN, LOW);  // turn off LED
     //SerialBT.println("NO MOTION DETECTED");   

    
  }
  delay(200);

int gasState = digitalRead(DO_PIN3);
  
  if
   (gasState == LOW){
     Serial.println("GAS DETECTED");
     SerialBT.println("GAS DETECTED");
    digitalWrite(LED_PIN, HIGH);      //Turn LED ON
    tone(buzzer, 250); // Send 1KHz sound signal...
    delay(200);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(200);        // ...for 1sec
   } 
    else {
    //      Serial.println("EVERYTHING OK");
    digitalWrite(LED_PIN, LOW);  // turn off LED
     //SerialBT.println("NO MOTION DETECTED");   

    
  }
  delay(200);

}