Alarm Panel Mounted Arduino/Wemos D1 v2 multi 7 input PIR HELP

Hi there guys i am trying to program my WiFi capable Arduino to mimic my hardwired PIR zones,
the arduino will be mounted inside alarm panel and communicated with MQTT and HA.
Now when I have a single zone programed it all works with some delays but it works.
Now Ive added some extra code I get errors when compiling the code ill post my errors with
my new 7 zone input code that wont work. I will also post the single zone code that seems to work OK.
If some one can please help me or know of a better way to write this code please please help me I am stuck.
I’m basically wanting to use the arduino to monitor/mirror my alarm zones for lighting automation in HA and arm disarm status eventually adding outputs to arm my alarm system and open doors via the key-switch programing I have Programed into my Alarm System that is a ParadoxEvo48. I have been working on a hack that uses MQTT and the alarms IP150 module to do all of this but have not been able to decode the communications between the ip150 and alarm system. so I decided to put the arduino in there to do the same functions that the Ip150 would normally do.

code of working original single zone sketch:

[CODE] As a binary sensor in configuration.yaml

  • platform: mqtt
    state_topic: “ESP-PIR-01/feeds/motion”
    name: PIR Sensor
    payload_on: “ON”
    payload_off: “OFF”
    qos: 0
    device_class: motion

Arduino sketch. For sure nothing I wrote :slight_smile:

/*
Basic ESP8266 MQTT PIR sketch

*/

#include <ESP8266WiFi.h>
#include “Adafruit_MQTT.h”
#include “Adafruit_MQTT_Client.h”

// Update these with values suitable for your network.

/************************* WiFi Access Point *********************************/

#define WLAN_SSID “my router” // Wi-Fi network name
#define WLAN_PASS “password” // Wi-Fi password

/**************************** MQTT Broker ************************************/

#define AIO_SERVER “192.168.XX.X” // MQTT broker IP
#define AIO_SERVERPORT 1883 // MQTT broker port
#define AIO_USERNAME “user” // MQTT username
#define AIO_KEY “pass” // MQTT password
#define AIO_CID “ESP-PIR-01” // MQTT client ID

// Start a counter for serial logging and set the initial value to no motion
int counter = 0;
int previousReading = LOW;

WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY, AIO_CID);

// Setup publish feeds - define topic name in parenthesis
Adafruit_MQTT_Publish status = Adafruit_MQTT_Publish(&mqtt, AIO_CID “/feeds/motion”);
Adafruit_MQTT_Publish motion_topic = Adafruit_MQTT_Publish(&mqtt, AIO_CID “/feeds/motion”);

long lastMsg = 0;
char msg[50];
int value = 0;

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 15;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin = 12; // the digital pin connected to the PIR sensor’s output
int ledPin = 16; // the digital pin connected to built-in LED

void MQTT_connect();

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println(“WiFi connected”);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

// Setup a MQTT subscription
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [”);
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == ‘1’) {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED off by making the voltage HIGH
}

}

void MQTT_connect() {
int8_t ret;

// Stop if already connected.
if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT… ");

uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println(“Retrying MQTT connection in 5 seconds…”);
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries–;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println(“MQTT Connected!”);
status.publish(“online”);
}

void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin, HIGH);

//give the sensor some time to calibrate
Serial.print(“calibrating sensor “);
for(int i = 0; i < calibrationTime; i++){
Serial.print(”.”);
delay(500);
}
Serial.println(" done");
Serial.println(“SENSOR ACTIVE”);
delay(50);

}

void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();

 if(digitalRead(pirPin) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
   }

}

[/CODE]
My Modified Sketch for 7 zone PIR inputs:

[CODE]/*
Basic ESP8266 MQTT PIR sketch

*/

#include <ESP8266WiFi.h>
#include “Adafruit_MQTT.h”
#include “Adafruit_MQTT_Client.h”

// Update these with values suitable for your network.

/************************* WiFi Access Point *********************************/

#define WLAN_SSID “ParkwayDrive” // Wi-Fi network name
#define WLAN_PASS “Treedolphin” // Wi-Fi password

/**************************** MQTT Broker ************************************/

#define AIO_SERVER “10.0.0.59” // MQTT broker IP
#define AIO_SERVERPORT 1883 // MQTT broker port
#define AIO_USERNAME “guest” // MQTT username
#define AIO_KEY “guest” // MQTT password
#define AIO_CID “ESP-PIR-01” // MQTT client ID

// Start a counter for serial logging and set the initial value to no motion
int counter = 0;
int previousReading = LOW;

WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY, AIO_CID);

// Setup publish feeds - define topic name in parenthesis
Adafruit_MQTT_Publish status = Adafruit_MQTT_Publish(&mqtt, AIO_CID “/feeds/motion”);
Adafruit_MQTT_Publish motion_topic = Adafruit_MQTT_Publish(&mqtt, AIO_CID “/feeds/motion”);

long lastMsg = 0;
char msg[50];
int value = 0;

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 15;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 1000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin1 = 0; // the digital pin connected to the PIR sensor’s output
int pirPin2 = 1; // the digital pin connected to the PIR sensor’s output
int pirPin3 = 2; // the digital pin connected to the PIR sensor’s output
int pirPin4 = 3; // the digital pin connected to the PIR sensor’s output
int pirPin5 = 4; // the digital pin connected to the PIR sensor’s output
int pirPin6 = 5; // the digital pin connected to the PIR sensor’s output
int pirPin7 = 6; // the digital pin connected to the PIR sensor’s output
int ledPin = 8; // the digital pin connected to built-in LED

void MQTT_connect();

void setup_wifi() {

delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println(“WiFi connected”);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

// Setup a MQTT subscription
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [”);
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == ‘1’) {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED off by making the voltage HIGH
}

}

void MQTT_connect() {
int8_t ret;

// Stop if already connected.
if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT… ");

uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println(“Retrying MQTT connection in 5 seconds…”);
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries–;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println(“MQTT Connected!”);
status.publish(“online”);
}

void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
pinMode(pirPin1, INPUT);
pinMode(pirPin2, INPUT);
pinMode(pirPin3, INPUT);
pinMode(pirPin4, INPUT);
pinMode(pirPin5, INPUT);
pinMode(pirPin6, INPUT);
pinMode(pirPin7, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin1, HIGH);
digitalWrite(pirPin2, HIGH);
digitalWrite(pirPin3, HIGH);
digitalWrite(pirPin4, HIGH);
digitalWrite(pirPin5, HIGH);
digitalWrite(pirPin6, HIGH);
digitalWrite(pirPin7, HIGH);

//give the sensor some time to calibrate
Serial.print(“calibrating sensor “);
for(int i = 0; i < calibrationTime; i++){
Serial.print(”.”);
delay(500);
}
Serial.println(" done");
Serial.println(“SENSOR ACTIVE”);
delay(50);

}

void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();

 if(digitalRead(pirPin1) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin1) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
       if(digitalRead(pirPin2) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin2) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
       if(digitalRead(pirPin3) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin3) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
       if(digitalRead(pirPin4) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin4) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
       if(digitalRead(pirPin5) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin5) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
       if(digitalRead(pirPin6) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin6) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
       if(digitalRead(pirPin7) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin7) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
   }

}

[/CODE]

ERROR:

[CODE]testmikefkr:412: error: expected ‘}’ at end of input

        delay(50);                  }

                                    ^

testmikefkr:412: error: expected ‘}’ at end of input

testmikefkr:412: error: expected ‘}’ at end of input

testmikefkr:412: error: expected ‘}’ at end of input

testmikefkr:412: error: expected ‘}’ at end of input

testmikefkr:412: error: expected ‘}’ at end of input

testmikefkr:412: error: expected ‘}’ at end of input

testmikefkr:412: error: expected ‘}’ at end of input

exit status 1
expected ‘}’ at end of input[CODE}

You are missing a closing bracket “}”, you will need to check thru’ the code and see where you have either added an extra opening bracket “{” or deleted a closing bracket “}”

In fact there were six closing brackets } missing. I took your code, added 6 lines in the place that I think is correct (we had to close 6 conditionals if(digitalRead(pirPinXYZ) == LOW){ (for XYZ=1 to 6)) and I’ve compiled this in my machine without errors:

/*
 Basic ESP8266 MQTT PIR sketch
*/
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
// Update these with values suitable for your network.
/************************* WiFi Access Point *********************************/
#define WLAN_SSID       "ParkwayDrive"           // Wi-Fi network name
#define WLAN_PASS       "Treedolphin"           // Wi-Fi password
/**************************** MQTT Broker ************************************/
#define AIO_SERVER      "10.0.0.59"  // MQTT broker IP
#define AIO_SERVERPORT  1883             // MQTT broker port
#define AIO_USERNAME    "guest"           // MQTT username
#define AIO_KEY         "guest"           // MQTT password
#define AIO_CID         "ESP-PIR-01"     // MQTT client ID
// Start a counter for serial logging and set the initial value to no motion 
int counter = 0;
int previousReading = LOW;
WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY, AIO_CID);
// Setup publish feeds - define topic name in parenthesis 
Adafruit_MQTT_Publish status  = Adafruit_MQTT_Publish(&mqtt, AIO_CID "/feeds/motion");
Adafruit_MQTT_Publish motion_topic  = Adafruit_MQTT_Publish(&mqtt, AIO_CID "/feeds/motion");
long lastMsg = 0;
char msg[50];
int value = 0;
/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 15;        
//the time when the sensor outputs a low impulse
long unsigned int lowIn;         
//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 1000;  
boolean lockLow = true;
boolean takeLowTime;  
int pirPin1 = 0;       // the digital pin connected to the PIR sensor's output
int pirPin2 = 1;       // the digital pin connected to the PIR sensor's output
int pirPin3 = 2;       // the digital pin connected to the PIR sensor's output 
int pirPin4 = 3;       // the digital pin connected to the PIR sensor's output
int pirPin5 = 4;       // the digital pin connected to the PIR sensor's output
int pirPin6 = 5;       // the digital pin connected to the PIR sensor's output
int pirPin7 = 6;       // the digital pin connected to the PIR sensor's output
int ledPin = 8;        // the digital pin connected to built-in LED
void MQTT_connect();
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
  // Setup a MQTT subscription
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, LOW);  // Turn the LED off by making the voltage HIGH
  }
}
void MQTT_connect() {
  int8_t ret;
  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }
  Serial.print("Connecting to MQTT... ");
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
  status.publish("online");
}
void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  pinMode(pirPin1, INPUT);
  pinMode(pirPin2, INPUT);
  pinMode(pirPin3, INPUT);
  pinMode(pirPin4, INPUT);
  pinMode(pirPin5, INPUT);
  pinMode(pirPin6, INPUT);
  pinMode(pirPin7, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin1, HIGH);
  digitalWrite(pirPin2, HIGH);
  digitalWrite(pirPin3, HIGH);
  digitalWrite(pirPin4, HIGH);
  digitalWrite(pirPin5, HIGH);
  digitalWrite(pirPin6, HIGH);
  digitalWrite(pirPin7, HIGH);
  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(500);
      }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}
void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();
     if(digitalRead(pirPin1) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin1) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
 }//tim
       if(digitalRead(pirPin2) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin2) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
 }//tim
       if(digitalRead(pirPin3) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin3) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
 }//tim
       if(digitalRead(pirPin4) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin4) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
 }//tim
       if(digitalRead(pirPin5) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin5) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
 }//tim
       if(digitalRead(pirPin6) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin6) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
 }//tim
       if(digitalRead(pirPin7) == HIGH){
   digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
   if(lockLow){  
     motion_topic.publish("ON");  
     //makes sure we wait for a transition to LOW before any further output is made:
     lockLow = false;            
     Serial.println("---");
     Serial.print("motion detected at ");
     Serial.print(millis()/1000);
     Serial.println(" sec"); 
     delay(50);
     }         
     takeLowTime = true;
   }

 if(digitalRead(pirPin7) == LOW){       
   digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

   if(takeLowTime){
    lowIn = millis();          //save the time of the transition from high to LOW
    takeLowTime = false;       //make sure this is only done at the start of a LOW phase
    }
   //if the sensor is low for more than the given pause, 
   //we assume that no more motion is going to happen
   if(!lockLow && millis() - lowIn > pause){  
       motion_topic.publish("OFF");  
       //makes sure this block of code is only executed again after 
       //a new motion sequence has been detected
       lockLow = true;                        
       Serial.print("motion ended at ");      //output
       Serial.print((millis() - pause)/1000);
       Serial.println(" sec");
       delay(50);
       }
   }
}

You can find my additional lines because I added a comment: // tim
Good luck!

Thank you Tim much appreciated and thanks for pointing out the spots you have fixed for me I’m new to the arduino thing and helps a lot to know where I’ve gone wrong. Unfortunately the code although compiles ok it doesn’t do what I’m wanting.

Would you or anyone on this forum know of a sketch that publishes MQTT topics with multiple inputs using digital read pins or similar . I’m wanting to have around 7 inputs open closes from PIR/sensors that publish on and off or open closes to my MQTT setup
If I need to upgrade to a arduino mega that is fine .
These must be a easy way to approach this code I think I’m over complicating it any advice or ideas please

Basicly I Have found this sketch Below for my alarm panel outputs Arming Disarming and Garage Door plus a extra ive just called PGM this one works very well super fast using my wifi Wemos. anyone know how hard it would be to put some inputs for PIRs into this code below.

[CODE]#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>

void callback(char* topic, byte* payload, unsigned int length);

//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER “10.0.0.59” //you MQTT IP Address
const char* ssid = “ParkwayDrive”;
const char* password = “Treedolphin”;

//EJ: Data PIN Assignment on WEMOS D1 R2 https://www.wemos.cc/product/d1.html
// if you are using Arduino UNO, you will need to change the “D1 ~ D4” with the corresponding UNO DATA pin number

const int switchPin1 = D1;
const int switchPin2 = D2;
const int switchPin3 = D3;
const int switchPin4 = D5;

//EJ: These are the MQTT Topic that will be used to manage the state of Relays 1 ~ 4
//EJ: Refer to my YAML component entry
//EJ: feel free to replicate the line if you have more relay switch to control, but dont forget to increment the number suffix so as increase switch logics in loop()

char const* switchTopic1 = “/arm/alarm/”;
char const* switchTopic2 = “/disarm/alarm/”;
char const* switchTopic3 = “/open/garage/”;
char const* switchTopic4 = “/open/pgm/”;

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
//initialize the switch as an output and set to LOW (off)
pinMode(switchPin1, OUTPUT); // Relay Switch 1
digitalWrite(switchPin1, LOW);

pinMode(switchPin2, OUTPUT); // Relay Switch 2
digitalWrite(switchPin2, LOW);

pinMode(switchPin3, OUTPUT); // Relay Switch 3
digitalWrite(switchPin3, LOW);

pinMode(switchPin4, OUTPUT); // Relay Switch 4
digitalWrite(switchPin4, LOW);

ArduinoOTA.setHostname(“My Arduino WEMO”); // A name given to your ESP8266 module when discovering it as a port in ARDUINO IDE
ArduinoOTA.begin(); // OTA initialization

//start the serial line for debugging
Serial.begin(115200);
delay(100);

//start wifi subsystem
WiFi.begin(ssid, password);
//attempt to connect to the WIFI network and then connect to the MQTT server
reconnect();

//wait a bit before starting the main loop
delay(2000);
}

void loop(){

//reconnect if connection is lost
if (!client.connected() && WiFi.status() == 3) {reconnect();}

//maintain MQTT connection
client.loop();

//MUST delay to allow ESP8266 WIFI functions to run
delay(10);
ArduinoOTA.handle();
}

void callback(char* topic, byte* payload, unsigned int length) {

//convert topic to string to make it easier to work with
String topicStr = topic;
//EJ: Note: the “topic” value gets overwritten everytime it receives confirmation (callback) message from MQTT

//Print out some debugging info
Serial.println(“Callback update.”);
Serial.print("Topic: ");
Serial.println(topicStr);

if (topicStr == “/arm/alarm/”)
{

 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin1, HIGH);
   client.publish("/arm/alarmConfirm/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin1, LOW);
   client.publish("/arm/alarmConfirm/", "0");
   }
 }

 // EJ: copy and paste this whole else-if block, should you need to control more switches
 else if (topicStr == "/disarm/alarm/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin2, HIGH);
   client.publish("/disarm/alarmConfirm1/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin2, LOW);
   client.publish("/disarm/alarmConfirm1/", "0");
   }
 }
 else if (topicStr == "/open/garage/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin3, HIGH);
   client.publish("/open/garageConfirm2/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin3, LOW);
   client.publish("/open/garageConfirm2/", "0");
   }
 }
 else if (topicStr == "/open/pgm/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin4, HIGH);
   client.publish("/open/pgmConfirm3/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin4, LOW);
   client.publish("/open/pgmConfirm3/", "0");
   }
 }

}

void reconnect() {

//attempt to connect to the wifi if connection is lost
if(WiFi.status() != WL_CONNECTED){
//debug printing
Serial.print("Connecting to ");
Serial.println(ssid);

//loop while we wait for connection
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

//print out some more debug once connected
Serial.println("");
Serial.println("WiFi connected");  
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

}

//make sure we are connected to WIFI before attemping to reconnect to MQTT
if(WiFi.status() == WL_CONNECTED){
// Loop until we’re reconnected to the MQTT server
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);

  // Generate client name based on MAC address and last 8 bits of microsecond counter
  String clientName;
  clientName += "esp8266-";
  uint8_t mac[6];
  WiFi.macAddress(mac);
  clientName += macToStr(mac);

  //if connected, subscribe to the topic(s) we want to be notified about
  //EJ: Delete "mqtt_username", and "mqtt_password" here if you are not using any 
  if (client.connect((char*) clientName.c_str(),"mqtt_username", "mqtt_password")) {  //EJ: Update accordingly with your MQTT account 
    Serial.print("\tMQTT Connected");
    client.subscribe(switchTopic1);
    client.subscribe(switchTopic2);
    client.subscribe(switchTopic3);
    client.subscribe(switchTopic4);
    //EJ: Do not forget to replicate the above line if you will have more than the above number of relay switches
  }

  //otherwise print failed for debugging
  else{Serial.println("\tFailed."); abort();}
}

}
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

String result;

for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);

if (i < 5){
  result += ':';
}

}

return result;
}[/CODE]
This is my whats in my config.yaml

[CODE]switch:

  • platform: mqtt
    name: “Arm Alarm”
    state_topic: “/arm/alarmConfirm/”
    command_topic: “/arm/alarm/”
    payload_on: “1”
    payload_off: “0”
    qos: 0
    retain: true
  • platform: mqtt
    name: “Disarm Alarm”
    state_topic: “/disarm/alarmConfirm1/”
    command_topic: “/disarm/alarm/”
    payload_on: “1”
    payload_off: “0”
    qos: 0
    retain: true
  • platform: mqtt
    name: “Open Garage Door”
    state_topic: “/open/garageConfirm2/”
    command_topic: “/open/garage/”
    payload_on: “1”
    payload_off: “0”
    qos: 0
    retain: true
  • platform: mqtt
    name: “Open Pgm”
    state_topic: “/open/pgmConfirm3/”
    command_topic: “/open/pgm/”
    payload_on: “1”
    payload_off: “0”
    qos: 0
    retain: true
    [/CODE]
    Please if someone could help with creating up to 7 inputs in this code this would become a very useful project for people wanting a easy way to interface with any alarm system for automation and control via Home assistant.
    at the moment with this code i can Arm, Disarm, Open Garage Door, and have one spare output i may remove PGM4 and use this as a input digital read or somthing but not sure on how to add this code in i wanting to have around 8 inputs coded in but if some one could help me get one digital read or analog read to work with MQTT i can do the rest thanks

So far I have something like this

[CODE]const int switchPin1 = D1;
const int switchPin2 = D2;
const int switchPin3 = D3;
const int switchPin4 = D5;
const int switchPin5 = D0;
const int switchPin6 = D6;
const int switchPin7 = D7;
const int switchPin8 = D8;
const int switchPin9 = A0;
const int switchPin10 = D4; // On board led pin not sure if this can be used as input

//EJ: These are the MQTT Topic that will be used to manage the state of Relays 1 ~ 4
//EJ: Refer to my YAML component entry
//EJ: feel free to replicate the line if you have more relay switch to control, but dont forget to increment the number suffix so as increase switch logics in loop()

// outputs
char const* switchTopic1 = “/arm/alarm/”;
char const* switchTopic2 = “/disarm/alarm/”;
char const* switchTopic3 = “/open/garage/”;
char const* switchTopic4 = “/open/pgm/”; // may reprogram as input as running short of pins LOL

// inputs
char const* switchTopic5 = “/pir2/office/”;
char const* switchTopic6 = “/pir3/upstairs/”;
char const* switchTopic7 = “/pir4/hallway/”;
char const* switchTopic8 = “/pir5/garage/”;
char const* switchTopic9 = “/pir6/kitchen/”;
char const* switchTopic9 = “/pir7/gargedoor/”;
[/CODE]

MY TEST BELOW I HAVE KNOW CLUE LOL

[CODE]#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>

void callback(char* topic, byte* payload, unsigned int length);

//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER “10.0.0.59” //you MQTT IP Address
const char* ssid = “ParkwayDrive”;
const char* password = “Treedolphin”;

//EJ: Data PIN Assignment on WEMOS D1 R2 https://www.wemos.cc/product/d1.html
// if you are using Arduino UNO, you will need to change the “D1 ~ D4” with the corresponding UNO DATA pin number

const int switchPin1 = D1;
const int switchPin2 = D2;
const int switchPin3 = D3;
const int switchPin4 = D5;
const int switchPin5 = D0;
const int switchPin6 = D6;
const int switchPin7 = D7;
const int switchPin8 = D8;
const int switchPin9 = A0;
const int switchPin10 = D4; //on board led not sure if can be programed as input

//EJ: These are the MQTT Topic that will be used to manage the state of Relays 1 ~ 4
//EJ: Refer to my YAML component entry
//EJ: feel free to replicate the line if you have more relay switch to control, but dont forget to increment the number suffix so as increase switch logics in loop()

// outputs
char const* switchTopic1 = “/arm/alarm/”;
char const* switchTopic2 = “/disarm/alarm/”;
char const* switchTopic3 = “/open/garage/”;
char const* switchTopic4 = “/open/pgm/”; // may reprogram as input as running short of pins LOL
char const* switchTopic5 = “/pir1/office/”;
char const* switchTopic6 = “/pir2/upstairs/”;
char const* switchTopic7 = “/pir3/hallway/”;
char const* switchTopic8 = “/pir4/garage/”;
char const* switchTopic9 = “/pir5/kitchen/”;
char const* switchTopic9 = “/pir6/gargedoor/”;

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
//initialize the switch as an output and set to LOW (off)
pinMode(switchPin1, OUTPUT); // Relay Switch 1
digitalWrite(switchPin1, LOW);

pinMode(switchPin2, OUTPUT); // Relay Switch 2
digitalWrite(switchPin2, LOW);

pinMode(switchPin3, OUTPUT); // Relay Switch 3
digitalWrite(switchPin3, LOW);

pinMode(switchPin4, OUTPUT); // Relay Switch 4
digitalWrite(switchPin4, LOW);

pinMode(switchPin5, INPUT); // PIR office // my first input test
digitalWrite(switchPin5, LOW);

ArduinoOTA.setHostname(“My Arduino WEMO”); // A name given to your ESP8266 module when discovering it as a port in ARDUINO IDE
ArduinoOTA.begin(); // OTA initialization

//start the serial line for debugging
Serial.begin(115200);
delay(100);

//start wifi subsystem
WiFi.begin(ssid, password);
//attempt to connect to the WIFI network and then connect to the MQTT server
reconnect();

//wait a bit before starting the main loop
delay(2000);
}

void loop(){

//reconnect if connection is lost
if (!client.connected() && WiFi.status() == 3) {reconnect();}

//maintain MQTT connection
client.loop();

//MUST delay to allow ESP8266 WIFI functions to run
delay(10);
ArduinoOTA.handle();
}

void callback(char* topic, byte* payload, unsigned int length) {

//convert topic to string to make it easier to work with
String topicStr = topic;
//EJ: Note: the “topic” value gets overwritten everytime it receives confirmation (callback) message from MQTT

//Print out some debugging info
Serial.println(“Callback update.”);
Serial.print("Topic: ");
Serial.println(topicStr);

if (topicStr == “/arm/alarm/”)
{

 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin1, HIGH);
   client.publish("/arm/alarmConfirm/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin1, LOW);
   client.publish("/arm/alarmConfirm/", "0");
   }
 }

 // EJ: copy and paste this whole else-if block, should you need to control more switches
 else if (topicStr == "/disarm/alarm/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin2, HIGH);
   client.publish("/disarm/alarmConfirm1/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin2, LOW);
   client.publish("/disarm/alarmConfirm1/", "0");
   }
 }
 else if (topicStr == "/open/garage/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin3, HIGH);
   client.publish("/open/garageConfirm2/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin3, LOW);
   client.publish("/open/garageConfirm2/", "0");
   }
 }
 else if (topicStr == "/open/pgm/") 
 {
 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalWrite(switchPin4, HIGH);
   client.publish("/open/pgmConfirm3/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalWrite(switchPin4, LOW);
   client.publish("/open/pgmConfirm3/", "0");
   }
 }
 if (topicStr == "/pir1/office/") 
{

 //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
 if(payload[0] == '1'){
   digitalRead(switchPin5, HIGH);
   client.publish("/pir1/officeConfirm/", "1");
   }

  //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
 else if (payload[0] == '0'){
   digitalRead(switchPin5, LOW);
   client.publish("/pir1/officeConfirm/", "0");
    if (switchPin5 == HIGH) {     
  // turn LED on: 
  if (ledState == HIGH) {   
   }
 }

}

void reconnect() {

//attempt to connect to the wifi if connection is lost
if(WiFi.status() != WL_CONNECTED){
//debug printing
Serial.print("Connecting to ");
Serial.println(ssid);

//loop while we wait for connection
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

//print out some more debug once connected
Serial.println("");
Serial.println("WiFi connected");  
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

}

//make sure we are connected to WIFI before attemping to reconnect to MQTT
if(WiFi.status() == WL_CONNECTED){
// Loop until we’re reconnected to the MQTT server
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);

  // Generate client name based on MAC address and last 8 bits of microsecond counter
  String clientName;
  clientName += "esp8266-";
  uint8_t mac[6];
  WiFi.macAddress(mac);
  clientName += macToStr(mac);

  //if connected, subscribe to the topic(s) we want to be notified about
  //EJ: Delete "mqtt_username", and "mqtt_password" here if you are not using any 
  if (client.connect((char*) clientName.c_str(),"mqtt_username", "mqtt_password")) {  //EJ: Update accordingly with your MQTT account 
    Serial.print("\tMQTT Connected");
    client.subscribe(switchTopic1);
    client.subscribe(switchTopic2);
    client.subscribe(switchTopic3);
    client.subscribe(switchTopic4);
    client.subscribe(switchTopic5);
    client.subscribe(switchTopic6);
    client.subscribe(switchTopic7);
    client.subscribe(switchTopic8);
    client.subscribe(switchTopic9);
    //EJ: Do not forget to replicate the above line if you will have more than the above number of relay switches
  }

  //otherwise print failed for debugging
  else{Serial.println("\tFailed."); abort();}
}

}
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

String result;

for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);

if (i < 5){
  result += ':';
}

}

return result;
}[/CODE]

Have you tried the sketch that works ok plus an additional PIR? Just to approach to the final solution step by step.
I’ve read that the D1 mini accepts up to 11 inputs so it seems you won’t need to upgrade the hardware.
Below is a sketch I use with a Wemos D1 mini and a PIR (just one). I think we both took it from the same source because it is very similar (if not identic) to the one you posted yesterday. If I were you, I would try to fushion this sketch with the one that works properly. If it works ok with just one PIR then later it may be easy to include the rest of the PIRs.

/*
 Basic ESP8266 MQTT PIR sketch

*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

/************************* WiFi Access Point *********************************/

const char* ssid = "youressid";
const char* password = "yourpass";

/**************************** MQTT Broker ************************************/

const char* mqtt_server = "XXX.XXX.XXX.XXX";
const char* mqtt_username = "YYYYYYYYYYYYYYY";
const char* mqtt_password = "ZZZZZZZZZZZZZZZZ";
const char* mqtt_topic = "ESP-PIR-01/feeds/motion";

// Start a counter for serial logging and set the initial value to no motion 
int counter = 0;
int previousReading = LOW;

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[50];
int value = 0;

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 15;        

//the time when the sensor outputs a low impulse
long unsigned int lowIn;         

//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 5000;  

boolean lockLow = true;
boolean takeLowTime;  

int pirPin = 12;    // the digital pin connected to the PIR sensor's output; D6 in Wemos D1 mini
int ledPin = 2;    // the digital pin connected to built-in LED; D4 in Wemos D1 mini

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.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

// Setup a MQTT subscription
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
      Serial.println("connected");
    } 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() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, HIGH);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(500);
      }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);


}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

     if(digitalRead(pirPin) == HIGH){
       digitalWrite(ledPin, LOW);   //the led visualizes the sensors output pin state
       if(lockLow){  
         client.publish(mqtt_topic,"ON");  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;            
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec"); 
         delay(50);
         }         
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){       
       digitalWrite(ledPin, HIGH);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){  
           client.publish(mqtt_topic,"OFF");  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow = true;                        
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
}

And this is what I have in HA

- platform: mqtt
  state_topic: "ESP-PIR-01/feeds/motion"
  name: Playroom
  payload_on: "ON"
  payload_off: "OFF"
  qos: 0
  device_class: motion

Good luck and keep on asking if you get stuck!

Thanks for your help Tim I’m still trying to get the input code no luck so far but I’ll post code if I get it to work

Ok so I have managed to get a single PIR input programed into code ill post the code bellow
it seems to post topics correctly and I get open and closes Inside home assistant perfectly While still
having the use of the outputs. I can seethe changes on the serial monitor for the Arduino for the outputs but not for the input but I know its working as Home assistant gets its messages via MQTT OK so Ive misses some kind of Serial.println command in code but I am not sure where to add it in

Attempting MQTT connection... MQTT ConnectedCallback update. Topic: /arm/alarm/ Callback update. Topic: /open/garage/

**Here Is My code as it is working now with the following controls **
2x relay controls one for garage door opening the other for key-switch arming/disarming of alarm system and one Garage door sensor

[CODE]#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
void callback(char* topic, byte* payload, unsigned int length);
//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER “10.0.0.59” //you MQTT IP Address
const char* ssid = “ParkwayDrive”;
const char* password = “Treedolphin”;
//EJ: Data PIN Assignment on WEMOS D1 R2 https://www.wemos.cc/product/d1.html
// if you are using Arduino UNO, you will need to change the “D1 ~ D4” with the corresponding UNO DATA pin number
const int switchPin1 = D1;
const int switchPin2 = D2;

int sensor = D3; // the pin that the sensor is atteched to
int state = LOW; // by default, no motion detected
int val = 0;

//EJ: These are the MQTT Topic that will be used to manage the state of Relays 1 ~ 4
//EJ: Refer to my YAML component entry
//EJ: feel free to replicate the line if you have more relay switch to control, but dont forget to increment the number suffix so as increase switch logics in loop()
char const* switchTopic1 = “/arm/alarm/”;
char const* switchTopic2 = “/open/garage/”;
char const* sensorTopic3 = “/sensor/garage/”;

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);
void setup() {
//initialize the switch as an output and set to LOW (off)
pinMode(switchPin1, OUTPUT); // Relay Switch 1
digitalWrite(switchPin1, LOW);
pinMode(switchPin2, OUTPUT); // Relay Switch 2
digitalWrite(switchPin2, LOW);

pinMode(sensor, INPUT); // garage reedswitch

// pinMode(switchPin4, OUTPUT); // Relay Switch 4
// digitalWrite(switchPin4, LOW);
ArduinoOTA.setHostname(“My Arduino WEMO”); // A name given to your ESP8266 module when discovering it as a port in ARDUINO IDE
ArduinoOTA.begin(); // OTA initialization
//start the serial line for debugging
Serial.begin(115200);
delay(100);
//start wifi subsystem
WiFi.begin(ssid, password);
//attempt to connect to the WIFI network and then connect to the MQTT server
reconnect();
//wait a bit before starting the main loop
delay(2000);
}
void loop(){
val = digitalRead(sensor); // read sensor value
if (val == LOW) { // check if the sensor is HIGH
if (state == HIGH) {
client.publish("/sensor/garageconfirm9/", “on”);
state = LOW; // update variable state to HIGH
}
}
else {
if (state == LOW){
client.publish("/sensor/garageconfirm9/", “0ff”);
state = HIGH; // update variable state to LOW
}
}
//reconnect if connection is lost
if (!client.connected() && WiFi.status() == 3) {reconnect();}
//maintain MQTT connection
client.loop();
//MUST delay to allow ESP8266 WIFI functions to run
delay(10);
ArduinoOTA.handle();
}
void callback(char* topic, byte* payload, unsigned int length) {
//convert topic to string to make it easier to work with
String topicStr = topic;
//EJ: Note: the “topic” value gets overwritten everytime it receives confirmation (callback) message from MQTT
//Print out some debugging info
Serial.println(“Callback update.”);
Serial.print(“Topic: “);
Serial.println(topicStr);
if (topicStr == “/arm/alarm/”)
{
//turn the switch on if the payload is ‘1’ and publish to the MQTT server a confirmation message
if(payload[0] == ‘1’){
digitalWrite(switchPin1, LOW);
client.publish(”/arm/alarmConfirm/”, “1”);
}

//turn the switch off if the payload is ‘0’ and publish to the MQTT server a confirmation message
else if (payload[0] == ‘0’){
digitalWrite(switchPin1, HIGH);
client.publish("/arm/alarmConfirm/", “0”);
}
}

// EJ: copy and paste this whole else-if block, should you need to control more switches
else if (topicStr == “/open/garage/”)
{
//turn the switch on if the payload is ‘1’ and publish to the MQTT server a confirmation message
if(payload[0] == ‘1’){
digitalWrite(switchPin2, LOW);
client.publish("/open/garageConfirm2/", “1”);
}

//turn the switch off if the payload is ‘0’ and publish to the MQTT server a confirmation message
else if (payload[0] == ‘0’){
digitalWrite(switchPin2, HIGH);
client.publish("/open/garageConfirm2/", “0”);
}
}
}
void reconnect() {
//attempt to connect to the wifi if connection is lost
if(WiFi.status() != WL_CONNECTED){
//debug printing
Serial.print(“Connecting to “);
Serial.println(ssid);
//loop while we wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(”.”);
}

//print out some more debug once connected
Serial.println("");
Serial.println(“WiFi connected”);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//make sure we are connected to WIFI before attemping to reconnect to MQTT
if(WiFi.status() == WL_CONNECTED){
// Loop until we’re reconnected to the MQTT server
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
// Generate client name based on MAC address and last 8 bits of microsecond counter
String clientName;
clientName += “esp8266-”;
uint8_t mac[6];
WiFi.macAddress(mac);
clientName += macToStr(mac);

//if connected, subscribe to the topic(s) we want to be notified about
//EJ: Delete “mqtt_username”, and “mqtt_password” here if you are not using any
if (client.connect((char*) clientName.c_str(),“mqtt_username”, “mqtt_password”)) { //EJ: Update accordingly with your MQTT account
Serial.print("\tMQTT Connected");
client.subscribe(switchTopic1);
client.subscribe(switchTopic2);
client.subscribe(sensorTopic3);

//EJ: Do not forget to replicate the above line if you will have more than the above number of relay switches

}

//otherwise print failed for debugging
else{Serial.println("\tFailed."); abort();}
}
}
}
//generate unique name from MAC addr
String macToStr(const uint8_t* mac){
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5){
result += ‘:’;
}
}
return result;
}[\CODE]

Can anyone confirm this code seems ok to use and is there a way i can see input changes in serial monitor
then ill go ahead and add the rest of the inputs.
Thanks for any Help or advice.

1 Like

hi Mike, any progress since June?
i like your project and going to try the code you posted in June, will let you know in couple of days. Ronald