Thursday, October 8, 2020

Home Automation step1

LAMP1,2,3 are the light going to control. L1 controlled by PIR sensor that attached to ESP32, L2 and L3 can control via MQTT massage which pass by node-red dashboard, Node-red dash board can be access using any portable device such as phone, Tab etc.

 

#include <WiFi.h>
#include <PubSubClient.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// Change the credentials below, so your ESP32 connects to your router
const char* ssid = "Dialog 4G";
const char* password = "YJNHQ102RD8";

// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "192.168.0.105";

// Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
WiFiClient espClient;
PubSubClient client(espClient);

#define timeSeconds 10 // dealy for PIR motion

const int lamp2 = 17; // lamp2 - LED - GPIO 17 on ESP32 board
const int lamp3 = 5 ; // Lamp3 - LED - GPIO 5 on ESP32 board
const int lamp1 = 14;  // lamp1==PIR out // Set GPIOs for lamp1 and PIR Motion Sensor
const int mqttInterrupt = 12; // Interrupt GPIO for PIR mtion sensor trigger input
const int mqttInterruptL2= 13; // interrrupt GPIO for Lamp2
const int mqttInterruptL3= 27; // interrrupt GPIO for Lamp2
boolean toggle =false;
boolean toggle1=false;


// Timer: Auxiliary variables
unsigned long now_delay = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;

// Checks if motion was detected, sets LED HIGH and starts a timer
void IRAM_ATTR detectsMovement() {
  Serial.println("MOTION DETECTED!!!");
  digitalWrite(lamp1, HIGH);
  startTimer = true;
  lastTrigger = millis();
}
void IRAM_ATTR lamp2interrupt() {
  toggle=!toggle;
  Serial.println("Lamp2 interrupt");
  digitalWrite(lamp2, toggle );

}
void IRAM_ATTR lamp3interrupt() {
  toggle1=!toggle1;
  Serial.println("Lamp3 interrupt");
  digitalWrite(lamp3, toggle1 );

}

// Don't change the function below. This functions connects your ESP8266 to your router
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected - ESP IP address: ");
  Serial.println(WiFi.localIP());
}


void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
 
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT
  if(topic=="room/lamp3"){
      Serial.print("Changing Room lamp3 to ");
      if(messageTemp == "on"){
        digitalWrite(lamp3, HIGH);
        Serial.print("On");
      }
      else if(messageTemp == "off"){
        digitalWrite(lamp3, LOW);
        Serial.print("Off");
      }
  }
  Serial.println();
  // If a message is received on the topic room/lamp2, you check if the message is either on or off. Turns the lamp GPIO according to the message
  if(topic=="room/lamp2"){
      Serial.print("Changing Room lamp2 to ");
      if(messageTemp == "on"){
        digitalWrite(lamp2, HIGH);
        Serial.print("On");
      }
      else if(messageTemp == "off"){
        digitalWrite(lamp2, LOW);
        Serial.print("Off");
      }
  }
  Serial.println();

  if(topic=="room/pir"){
      Serial.print("PIR DETECTED ");
      if(messageTemp == "on"){
        digitalWrite(lamp1, HIGH);
        Serial.print("PIR On");
      }
      else if(messageTemp == "off"){
        digitalWrite(lamp1, LOW);
        Serial.print("PIR Off");
      }
  }
  Serial.println();
 
}



void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    /*
     YOU MIGHT NEED TO CHANGE THIS LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
     To change the ESP device ID, you will have to give a new name to the ESP8266.
     Here's how it looks:
       if (client.connect("ESP8266Client")) {
     You can do it like this:
       if (client.connect("ESP1_Office")) {
     Then, for the other ESP:
       if (client.connect("ESP2_Garage")) {
      That should solve your MQTT multiple connections problem
    */
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");  
      // Subscribe or resubscribe to a topic
      // You can subscribe to more topics (to control more LEDs in this example)
      client.subscribe("room/pir");
      client.subscribe("room/lamp2");
      client.subscribe("room/lamp3");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup() {

 
 
 
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

 
  // Serial port for debugging purposes
  Serial.begin(115200);
 
  // PIR Motion Sensor mode INPUT_PULLUP
  pinMode(mqttInterrupt, INPUT_PULLUP);
  pinMode(mqttInterruptL2, INPUT_PULLUP);
  pinMode(mqttInterruptL3, INPUT_PULLUP);
  // Set mqttInterrupt pin as interrupt, assign interrupt function and set RISING mode
  attachInterrupt(digitalPinToInterrupt(mqttInterrupt), detectsMovement, RISING);
  attachInterrupt(digitalPinToInterrupt(mqttInterruptL2), lamp2interrupt, RISING);
  attachInterrupt(digitalPinToInterrupt(mqttInterruptL3), lamp3interrupt, RISING);
 
  // Set lamps to LOW
  pinMode(lamp1, OUTPUT);
  digitalWrite(lamp1, LOW);
  pinMode(lamp2, OUTPUT);
  digitalWrite(lamp2, LOW);
  pinMode(lamp3, OUTPUT);
  digitalWrite(lamp3, LOW);
}

void loop() {

 
  if (!client.connected()) {
    reconnect();
  }
  if(!client.loop())
    client.connect("ESP8266Client");

 // now = millis();
  //   return;
 
   Serial.println("im busy .");
   delay(500);
 
  // Current time
  now_delay = millis();
  // Turn off the lamp1 after the number of seconds defined in the timeSeconds variable
  if(startTimer && (now_delay - lastTrigger > (timeSeconds*1000))) {
    Serial.println("Motion stopped...");
    digitalWrite(lamp1, LOW);
    startTimer = false;
  }
}

No comments:

Search This Blog