Problem with PIR sensor in esp8266

Hi,

I try to run a simple program using esp8266 and PIR sensor. I have connect the output pin of the sensor to the GPIO10 of the esp8266. Here is my sketch:

int sensor = 10;  
long state = digitalRead(sensor);

void setup() {
  pinMode(sensor, INPUT);
  Serial.begin(9600);
  
}

void loop() {
  
  if (state == HIGH) {
    Serial.println("Motion detected!");
    delay(1000);
  }
  else {
    Serial.println("No motion detected.");
    delay(1000);
  }
}

I use two type of PIR sensors. When I use HC SR501, I got "Motion Detected" print out at the serial monitor, even when there no object or movement in front of it. When I disconnect + and - of the PIR pins from the vcc and gnd of the esp8266, the reading at the serial monitor is "no motion detected printout.

But when I use HC SR505, I always got "no motion detected" print out at the serial monitor even when I put my hand in front of it..

Please teach me how to solve this problem.

There are many ESP8266 variants. Which one do you have?

I suggest that you try a different pin. Pins 1, 3, 4, 5, 12, 13, 14 are usable on most variants.

the datasheet of the HC-SR501 and HC-SR505 Mini PIR says operation voltage 4,5V to 20V
So supplying with 3.3V is too low.

Which ESP8266 are you using. GPIO-Pin 10 is available on nodeMCU-boards but not available on Wemos D1 mini

best regards Stefan

StefanL38:
the datasheet of the HC-SR501 and HC-SR505 Mini PIR says operation voltage 4,5V to 20V
So supplying with 3.3V is too low.

Which ESP8266 are you using. GPIO-Pin 10 is available on nodeMCU-boards but not available on Wemos D1 mini

best regards Stefan

Thanks for willing to help.
I'm using NODEMCU Lua ESP8266 ESP-12 V2. I have connected the PIR sensor to the VIN and GND pin on ESP which I believe is 5v.

groundFungus:
There are many ESP8266 variants. Which one do you have?

I suggest that you try a different pin. Pins 1, 3, 4, 5, 12, 13, 14 are usable on most variants.

Thanks. I'm using NODEMCU Lua ESP8266 ESP-12 V2. I've tried pin 1, also got the same result. The other port I have connect them with LCD 12C, MLX thermometer and rfid sensor.

zul77:
Thanks for willing to help.
I'm using NODEMCU Lua ESP8266 ESP-12 V2. I have connected the PIR sensor to the VIN and GND pin on ESP which I believe is 5v.

you have to have a digital multimeter to measure if voltages are really what a code or hardware expects the volatge to be.
I haven't looked up the datasheets of the IR-sensors closely maybe they need a pul-up or pull-down-resistor connected to the signal-pin to work properly
So I recomend to write a very very simple testcode that does nothing more than outputting the IO-pin state to the serial monitor

best regards Stefan

PIR sensors are very sensible for noise. Use caps on the power or an LC filter: