# PIR Sensor Motion + ESP8266

**URL:** https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240
**Category:** Dúvidas
**Created:** [24 Outubro , 2018 11:25 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240 "2018-10-24T11:25:52Z")
**Posts on this page:** 12
**Page:** 1

<div class="post-metadata">

### Author: ![karma](https://forum.cpha.pt/letter_avatar_proxy/v4/letter/k/bcef8e/32.png) [@karma](https://forum.cpha.pt/u/karma)
#### Post date: [24 Outubro , 2018 11:25 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/1 "2018-10-24T11:25:52Z")

</div>

Boas.

Estou a tentar ligar estes dois meninos um ao outro mas não estou a conseguir.  
Deixo o código que estou a tentar. Alterei os valores do Wifi e MQTT e mantive o "int pirPin = 12; ".

O codigo é enviado sem problemas e o nodemcu aparece na minha rede. Porém no HA o PIR encontra-se sempre desligado.  
O que estou a fazer mal?  
Obrigado

Codigo para o Nodemcu:

```
/*
 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 "ssid" // Wi-Fi network name
#define WLAN_PASS "pass" // Wi-Fi password

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

#define AIO_SERVER "192.168.1.xxx" // 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);
           }
       }

}

```

Em binary\_sensor.yaml:

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

```

> **[Gyazo](https://gyazo.com/fee81ea9f55d9fccfea2e2dc1171321b)**
>
> Gyazo is the easiest way to record screenshots & videos you can share instantly. Save time with async visual communication that's effortless and engaging.

> **[Gyazo](https://gyazo.com/8915d4639aca77c923924b57766969f8)**
>
> Gyazo is the easiest way to record screenshots & videos you can share instantly. Save time with async visual communication that's effortless and engaging.

---

<div class="post-metadata">

### Author: ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)
#### Post date: [24 Outubro , 2018 13:00 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/2 "2018-10-24T13:00:09Z")

</div>

@karma  
O código deve ser colocado como texto aqui no fórum e formatado devidamente. Deves sublinhar o texto que queres transformar em código e clicar no icone \</\>. Deverá existir um espaço antes e outro depois do bloco de código para que funcione correctamente.

---

<div class="post-metadata">

### Author: ![Marco\_Reis](https://forum.cpha.pt/user_avatar/forum.cpha.pt/marco_reis/32/942_2.png) [@Marco\_Reis](https://forum.cpha.pt/u/Marco_Reis)
#### Post date: [25 Outubro , 2018 14:48 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/3 "2018-10-25T14:48:52Z")

</div>

Boas,

Que dados aparecem no ESPlorer? Aperenta ser pin.

---

<div class="post-metadata">

### Author: ![karma](https://forum.cpha.pt/letter_avatar_proxy/v4/letter/k/bcef8e/32.png) [@karma](https://forum.cpha.pt/u/karma)
#### Post date: [25 Outubro , 2018 16:09 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/4 "2018-10-25T16:09:40Z")

</div>

Aparentemente este PIR Motion que estava a usar está avariado ( falta saber se já veio assim), não faz detecção nenhuma e uma vez que tinha aqui outro testei com esse e já deu… Mas está com outro código a funcionar.  
Estes PIR não são nada de especial.

---

<div class="post-metadata">

### Author: ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)
#### Post date: [25 Outubro , 2018 16:23 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/5 "2018-10-25T16:23:09Z")

</div>

Esses sensores são analógicos e costumam dar problemas devido a interferências com os ESP. Eu uso os AM320 (penso que essa a referencia) que são digitais e imunes à interferência, além de serem muito mais pequenos.

[https://www.ebay.com/itm/Mini-IR-Infrared-Pyroelectric-PIR-Body-Motion-Human-Sensor-Detector-Module-CK/191945082023?epid=1566412004&hash=item2cb0d184a7:g:nHwAAOSwZVlXrsXI:rk:3:pf:0](https://www.ebay.com/itm/Mini-IR-Infrared-Pyroelectric-PIR-Body-Motion-Human-Sensor-Detector-Module-CK/191945082023?epid=1566412004&hash=item2cb0d184a7:g:nHwAAOSwZVlXrsXI:rk:3:pf:0)

---

<div class="post-metadata">

### Author: ![karma](https://forum.cpha.pt/letter_avatar_proxy/v4/letter/k/bcef8e/32.png) [@karma](https://forum.cpha.pt/u/karma)
#### Post date: [25 Outubro , 2018 20:49 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/6 "2018-10-25T20:49:58Z")

</div>

Também li sobre isso… Sobre as interferências. Quando o colocar no sitio vou blinda-lo de papel de aluminio 😄  
Esses realmente é muito mais pequeno. Mas não tem ajustes de tempo nem de sensibilidade pois não?

---

<div class="post-metadata">

### Author: ![RodolfoVieira](https://forum.cpha.pt/user_avatar/forum.cpha.pt/rodolfovieira/32/14633_2.png) [@RodolfoVieira](https://forum.cpha.pt/u/RodolfoVieira)
#### Post date: [25 Outubro , 2018 21:17 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/7 "2018-10-25T21:17:29Z")

</div>

@karma queres instalar isso onde?

---

<div class="post-metadata">

### Author: ![karma](https://forum.cpha.pt/letter_avatar_proxy/v4/letter/k/bcef8e/32.png) [@karma](https://forum.cpha.pt/u/karma)
#### Post date: [25 Outubro , 2018 21:23 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/8 "2018-10-25T21:23:33Z")

</div>

A ideia era ligar esses dois meninos. E posteriormente coloca-los no hall de entrada… Agora já o consegui por a funcionar. E pareceu-me funcionar mais ou menos. Quando o colocar no sitio é que vou tirar as duvidas.  
Como também li sobre as interferencias do PIR, hei-de arranjar uma caixinha só para ele de maneira a ficar mais “protegido”. Se mesmo assim não corresponder como devido é mais um que ficará na gaveta

---

<div class="post-metadata">

### Author: ![RodolfoVieira](https://forum.cpha.pt/user_avatar/forum.cpha.pt/rodolfovieira/32/14633_2.png) [@RodolfoVieira](https://forum.cpha.pt/u/RodolfoVieira)
#### Post date: [25 Outubro , 2018 21:25 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/9 "2018-10-25T21:25:09Z")

</div>

Mas porque não usas os sensores pir da xiaomi ou mesmo os 433? alguma razão em especial?

---

<div class="post-metadata">

### Author: ![karma](https://forum.cpha.pt/letter_avatar_proxy/v4/letter/k/bcef8e/32.png) [@karma](https://forum.cpha.pt/u/karma)
#### Post date: [25 Outubro , 2018 21:32 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/10 "2018-10-25T21:32:04Z")

</div>

Não. Foi só mesmo por opção ( ou ma opção) porque quando fiz a encomenda dos ESP vi que estes PIR funcionariam lá. Então acabei por comprar também. Mas não são grande coisa. Pelo menos a meu ver… Pode ser que quando o coloque no sitio mude de opinião

---

<div class="post-metadata">

### Author: ![j\_assuncao](https://forum.cpha.pt/user_avatar/forum.cpha.pt/j_assuncao/32/3_2.png) [@j\_assuncao](https://forum.cpha.pt/u/j_assuncao)
#### Post date: [25 Outubro , 2018 21:43 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/11 "2018-10-25T21:43:59Z")

</div>

Não tem ajuste directo do tempo e sensibilidade mas podes fazer as alterações que quiseres no sketch.

---

<div class="post-metadata">

### Author: ![system](https://forum.cpha.pt/user_avatar/forum.cpha.pt/system/32/2_2.png) [@system](https://forum.cpha.pt/u/system)
#### Post date: [23 Janeiro , 2019 21:44 UTC](https://forum.cpha.pt/t/pir-sensor-motion-esp8266/1240/12 "2019-01-23T21:44:02Z")

</div>

Este tópico foi automaticamente fechado 90 dias após a última resposta. Novas respostas não são permitidas.
