Movatterモバイル変換


[0]ホーム

URL:


Skip to content
HOMEESP32ESP8266ESP32-CAMRASPBERRY PIMICROPYTHONRPi PICOARDUINOREVIEWS

ESP32 with PIR Motion Sensor using Interrupts and Timers

This tutorial shows how to detect motion with the ESP32 using a PIR motion sensor. In this example, when motion is detected (an interrupt is triggered), the ESP32 starts a timer and turns an LED on for a predefined number of seconds. When the timer finishes counting down, the LED is automatically turned off.

With this example we’ll also explore two important concepts: interrupts and timers.

Before proceeding with this tutorial you should have the ESP32 add-on installed in your Arduino IDE. Follow one of the following tutorials to install the ESP32 on the Arduino IDE, if you haven’t already.

Watch the Video Tutorial and Project Demo

This tutorial is available in video format (watch below) and in written format (continue reading).

Parts Required

To follow this tutorial you need the following parts

You can use the preceding links or go directly toMakerAdvisor.com/tools to find all the parts for your projects at the best price!

Introducing Interrupts

To trigger an event with a PIR motion sensor, you use interrupts. Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems.

With interrupts you don’t need to constantly check the current value of a pin. With interrupts, when a change is detected, an event is triggered (a function is called).

To set an interrupt in the Arduino IDE, you use theattachInterrupt() function, that accepts as arguments: the GPIO pin, the name of the function to be executed, and mode:

attachInterrupt(digitalPinToInterrupt(GPIO), function, mode);

GPIO Interrupt

The first argument is a GPIO number. Normally, you should usedigitalPinToInterrupt(GPIO) to set the actual GPIO as an interrupt pin. For example, if you want to useGPIO 27 as an interrupt, use:

digitalPinToInterrupt(27)

With an ESP32 board, all the pins highlighted with a red rectangle in the following figure can be configured as interrupt pins. In this example we’ll useGPIO 27 as an interrupt connected to the PIR Motion sensor.

Function to be triggered

The second argument of theattachInterrupt() function is the name of the function that will be called every time the interrupt is triggered.

Mode

The third argument is the mode. There are 5 different modes:

  • LOW: to trigger the interrupt whenever the pin is LOW;
  • HIGH: to trigger the interrupt whenever the pin is HIGH;
  • CHANGE: to trigger the interrupt whenever the pin changes value – for example from HIGH to LOW or LOW to HIGH;
  • FALLING: for when the pin goes from HIGH to LOW;
  • RISING: to trigger when the pin goes from LOW to HIGH.

For this example will be using the RISING mode, because when the PIR motion sensor detects motion, the GPIO it is connected to goes from LOW to HIGH.

Introducing Timers

In this example we’ll also introduce timers. We want the LED to stay on for a predetermined number of seconds after motion is detected. Instead of using adelay() function that blocks your code and doesn’t allow you to do anything else for a determined number of seconds, we should use a timer.

The delay() function

You should be familiar with thedelay() function as it is widely used. This function is pretty straightforward to use. It accepts a single int number as an argument. This number represents the time in milliseconds the program has to wait until moving on to the next line of code.

delay(time in milliseconds)

When you calldelay(1000) your program stops on that line for 1 second.

delay() is a blocking function. Blocking functions prevent a program from doing anything else until that particular task is completed. If you need multiple tasks to occur at the same time, you cannot usedelay().

For most projects, you should avoid using delays and use timers instead.

The millis() function

Using a function calledmillis() you can return the number of milliseconds that have passed since the program first started.

millis()

Why is that function useful? Because by using some math, you can easily check how much time has passed without blocking your code.

Blinking an LED with millis()

The following snippet of code shows how you can use themillis() function to create a blink LED project. It turns an LED on for 1000 milliseconds, and then turns it off.

/*********  Rui Santos  Complete project details at https://randomnerdtutorials.com  *********/// constants won't change. Used here to set a pin number :const int ledPin =  26;      // the number of the LED pin// Variables will change :int ledState = LOW;             // ledState used to set the LED// Generally, you should use "unsigned long" for variables that hold time// The value will quickly become too large for an int to storeunsigned long previousMillis = 0;        // will store last time LED was updated// constants won't change :const long interval = 1000;           // interval at which to blink (milliseconds)void setup() {  // set the digital pin as output:  pinMode(ledPin, OUTPUT);}void loop() {  // here is where you'd put code that needs to be running all the time.  // check to see if it's time to blink the LED; that is, if the  // difference between the current time and last time you blinked  // the LED is bigger than the interval at which you want to  // blink the LED.  unsigned long currentMillis = millis();  if (currentMillis - previousMillis >= interval) {    // save the last time you blinked the LED    previousMillis = currentMillis;    // if the LED is off turn it on and vice-versa:    if (ledState == LOW) {      ledState = HIGH;    } else {      ledState = LOW;    }    // set the LED with the ledState of the variable:    digitalWrite(ledPin, ledState);  }}

View raw code

How the code works

Let’s take a closer look at this blink sketch that works without adelay() function (it uses themillis() function instead).

Basically, this code subtracts the previous recorded time (previousMillis) from the current time (currentMillis). If the remainder is greater than the interval (in this case, 1000 milliseconds), the program updates thepreviousMillis variable to the current time, and either turns the LED on or off.

if (currentMillis - previousMillis >= interval) {  // save the last time you blinked the LED  previousMillis = currentMillis;  (...)

Because this snippet is non-blocking, any code that’s located outside of that firstif statement should work normally.

You should now be able to understand that you can add other tasks to yourloop() function and your code will still be blinking the LED every one second.

You can upload this code to your ESP32 and assemble the following schematic diagram to test it and modify the number of milliseconds to see how it works.

Note: If you’ve experienced any issues uploading code to your ESP32, take a look at theESP32 Troubleshooting Guide.

ESP32 with PIR Motion Sensor

After understanding these concepts: interrupts and timers, let’s continue with the project.

Schematic

The circuit we’ll build is easy to assemble, we’ll be using an LED with a resistor. The LED is connected toGPIO 26. We’ll be using theMini AM312 PIR Motion Sensor that operates at 3.3V.  It will be connected toGPIO 27. Simply follow the next schematic diagram.

Important:theMini AM312 PIR Motion Sensor used in this project operates at 3.3V. However, if you’re using another PIR motion sensor like the HC-SR501, it operates at 5V. You can either modify it to operate at 3.3V or simply power it using the Vin pin.

The following figure shows the AM312 PIR motion sensor pinout.

AM312 mini pir pinout

Uploading the Code

After wiring the circuit as shown in the schematic diagram, copy the code provided to your Arduino IDE.

You can upload the code as it is, or you can modify the number of seconds the LED is lit after detecting motion. Simply change thetimeSeconds variable with the number of seconds you want.

/*********  Rui Santos  Complete project details at https://randomnerdtutorials.com  *********/#define timeSeconds 10// Set GPIOs for LED and PIR Motion Sensorconst int led = 26;const int motionSensor = 27;// Timer: Auxiliary variablesunsigned long now = millis();unsigned long lastTrigger = 0;boolean startTimer = false;boolean motion = false;// Checks if motion was detected, sets LED HIGH and starts a timervoid IRAM_ATTR detectsMovement() {  digitalWrite(led, HIGH);  startTimer = true;  lastTrigger = millis();}void setup() {  // Serial port for debugging purposes  Serial.begin(115200);    // PIR Motion Sensor mode INPUT_PULLUP  pinMode(motionSensor, INPUT_PULLUP);  // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode  attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);  // Set LED to LOW  pinMode(led, OUTPUT);  digitalWrite(led, LOW);}void loop() {  // Current time  now = millis();  if((digitalRead(led) == HIGH) && (motion == false)) {    Serial.println("MOTION DETECTED!!!");    motion = true;  }  // Turn off the LED after the number of seconds defined in the timeSeconds variable  if(startTimer && (now - lastTrigger > (timeSeconds*1000))) {    Serial.println("Motion stopped...");    digitalWrite(led, LOW);    startTimer = false;    motion = false;  }}

View raw code

Note:if you’ve experienced any issues uploading code to your ESP32, take a look at theESP32 Troubleshooting Guide.

How the Code Works

Let’s take a look at the code. Start by assigning two GPIO pins to theled andmotionSensor variables.

// Set GPIOs for LED and PIR Motion Sensorconst int led = 26;const int motionSensor = 27;

Then, create variables that will allow you set a timer to turn the LED off after motion is detected.

// Timer: Auxiliar variableslong now = millis();long lastTrigger = 0;boolean startTimer = false;

Thenow variable holds the current time. ThelastTrigger variable holds the time when the PIR sensor detects motion. ThestartTimer is a boolean variable that starts the timer when motion is detected.

setup()

In thesetup(), start by initializing the Serial port at 115200 baud rate.

Serial.begin(115200);

Set the PIR Motion sensor as an INPUT PULLUP.

pinMode(motionSensor, INPUT_PULLUP);

To set the PIR sensor pin as an interrupt, use theattachInterrupt() function as described earlier.

attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);

The pin that will detect motion isGPIO 27 and it will call the functiondetectsMovement() on RISING mode.

The LED is an OUTPUT whose state starts at LOW.

pinMode(led, OUTPUT);digitalWrite(led, LOW);

loop()

Theloop() function is constantly running over and over again. In every loop, thenow variable is updated with the current time.

now = millis();

Nothing else is done in theloop().

But, when motion is detected, thedetectsMovement() function is called because we’ve set an interrupt previously on thesetup().

ThedetectsMovement() function prints a message in the Serial Monitor, turns the LED on, sets thestartTimer boolean variable totrue and updates thelastTrigger variable with the current time.

void IRAM_ATTR detectsMovement() {  Serial.println("MOTION DETECTED!!!");  digitalWrite(led, HIGH);  startTimer = true;  lastTrigger = millis();}

Note:IRAM_ATTR is used to run the interrupt code in RAM, otherwise code is stored in flash and it’s slower.

After this step, the code goes back to theloop().

This time, thestartTimer variable is true. So, when the time defined in seconds has passed (since motion was detected), the followingif statement will be true.

if(startTimer && (now - lastTrigger > (timeSeconds*1000))) {  Serial.println("Motion stopped...");  digitalWrite(led, LOW);  startTimer = false;}

The “Motion stopped…” message will be printed in the Serial Monitor, the LED is turned off, and the startTimer variable is set to false.

Demonstration

Upload the code to your ESP32 board. Make sure you have the right board and COM port selected.

Open the Serial Monitor at a baud rate of 115200.

Move your hand in front of the PIR sensor. The LED should turn on, and a message is printed in the Serial Monitor saying “MOTION DETECTED!!!”. After 10 seconds the LED should turn off.

Wrapping Up

To wrap up, interrupts are used to detect a change in the GPIO state without the need to constantly read the current GPIO value. With interrupts, when a change is detected, a function is triggered. You’ve also learned how to set a simple timer that allows you to check if a predefined number of seconds have passed without having to block your code.

We have other tutorials related with ESP32 that you may also like:

This is an excerpt from our course: Learn ESP32 with Arduino IDE. If you like ESP32 and you want to learn more, we recommend enrolling in Learn ESP32 with Arduino IDE course.

Thanks for reading.



SMART HOME with Raspberry Pi ESP32 and ESP8266 Node-RED InfluxDB eBook
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

62 thoughts on “ESP32 with PIR Motion Sensor using Interrupts and Timers”

  1. Good Job)

    Reply
    • Thank you!

      Reply
    • I have this problem, but don’t know how to fix:
      load 0x4010f000, len 1384, room 16
      tail 8
      chksum 0x2d
      csum 0x2d
      v8b899c12
      ~ld
      ISR not in IRAM!

      Reply
      • Hi.
        Your callback function needs to be defined in RAM.
        For that, use voidIRAM_ATTR before the function definition.
        Regards,
        Sara

        Reply
        • hello sara
          when i used this command in your motion project,s void setup():
          attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
          i received unknown respanses in my arduino serial monitor that,s run fast and program does not execute.
          thanks vm,
          areza alikhani

          Reply
          • Hi.
            Which GPIO are you using to connect the PIR motion sensor?
            Make sure that your PIR motion sensor is well connected.
            Regards,
            Sara

          • thanks sara
            i fixed this problem but i want when motion detect the picture and sms transfered for my phone by 8266 and node-red
            thanks vm

          • hello sara
            help me pls for my last post

          • ISR Best Practice is to do as little as possible inside them. Like only set a flag, ie, FIRED = 1; After the ISR completes and program execution returns back to the main loop(), check the flag, if (FIRED == 1) if TRUE, execute the send “picture and sms “, then clear the flag, FIRED = 0;

            Within the ISR, the FIRED flag should probably checked. If it is TRUE, then the ISR was trigger again before the send “picture and sms” code completed.

            This is only a problem if the ISR’s continues to get triggered before the main code completes. ISR’s queue up and can exhaust memory, ie, that IRAM.

  2. EXCELLENT ARTICLE!

    EXCELENTE ARTIGO, COMO TODOS OUTROS

    Reply
  3. Work for me 100 % Thank you very much !

    Reply
  4. Can I use 5V triggering for ESP32 pins which operate on 3.3V ?

    Reply
  5. Hello great tutorial i got it working but now i am working on a button to activate the system od not, as a alarm system do you have any ideas?

    thnx reinier

    Reply
    • Hi.
      You can add a button and declare it as an interrupt. This button will simply change a variable state to “active” or “not active”.
      Then, instead of just looking if motion was detected or not, you also need to check if it is active or not.
      So you’ll need a condition that checks the following:
      if (motion detected and motion sensor is activated) then do something…
      I hope this helps.
      Regards,
      Sara

      Reply
  6. Hi, good tutorial. Surprised no one has commented on the little timing mistake for “Blinking an LED with millis()”. You refer to using 1000 milliseconds, but your code has “const long interval = 5000; // interval at which to blink (milliseconds)”. That’s a 4 second difference. Not a big deal. Just an FYI.

    Reply
  7. Hello Thank you for the Tutorial,

    i have a question how i can blink the Motion led after motion detected? t i need 10 sec. continuous blinking and after 10 sec. stop the blinking.
    Thank you

    Reply
    • Hi Ferdi.
      I think the best way to do that is by creating two timers, one to keep track of the 10 seconds and the other to blink the LED without delay.
      You can find an example to blink the LED without delay in the Arduino examples. In your Arduino IDE, go to File > Examples > 02.Digital > BlinkWithoutDelay
      Regards,
      Sara

      Reply
  8. I tried the same code just changed the pins a little bit. I attached an interrupt to gpio27, led on gpio2 and also changed the ON time of led to 1 second in place of 10. But I get error “Guru Meditation Error: Core 1 panic’ed (Interrupt wdt timeout on CPU1) ” but as soon as I disable Serial.begin function things work fine. Any clue why is this happening?

    Reply
  9. I get an error trying to compile: “expected initializer before ‘detectsMovement'” I’m using a Sparkfun ESP32 Thing. Otherwise everything is as explained in the tutorial. I’ve googled and not been able to find anything for this particular error. Any ideas appreciated, please.

    Reply
  10. Hi Mrs. Sara Santos!

    My name is Angel and I bought your book “Learn Esp32 with arduino” and is really good! but in the “Multisensor Project” there is a fatal error in the code:

    This Fail says:
    ‘detectsMovement’ was not declared in this scope

    C:\Users\Jhon Kremer\Documents\Arduino\Mando_central\Mando_central.ino: In function ‘void setup()’:

    Mando_central:81:55: error: ‘detectsMovement’ was not declared in this scope

    attachInterrupt(digitalPinToInterrupt(motionSensor),detectsMovement, RISING);

    C:\Users\Jhon Kremer\Documents\Arduino\Mando_central\Mando_central.ino: At global scope:

    Mando_central:91:3: error: ‘Serial’ does not name a type

    Serial.println(” bytes read from Flash . Values are:”);

    ^

    Mando_central:92:3: error: expected unqualified-id before ‘for’

    for(int i = 0; i < EEPROM_SIZE; i++) {

    ^

    Mando_central:92:18: error: 'i' does not name a type

    for(int i = 0; i < EEPROM_SIZE; i++) {

    ^

    Mando_central:92:35: error: 'i' does not name a type

    for(int i = 0; i < EEPROM_SIZE; i++) {

    ^

    Mando_central:98:10: error: expected constructor, destructor, or type conversion before '(' token

    pinMode(output, OUTPUT);

    ^

    Mando_central:99:10: error: expected constructor, destructor, or type conversion before '(' token

    pinMode(redRGB, OUTPUT);

    ^

    Mando_central:100:10: error: expected constructor, destructor, or type conversion before '(' token

    pinMode(greenRGB, OUTPUT);

    ^

    Mando_central:101:10: error: expected constructor, destructor, or type conversion before '(' token

    pinMode(blueRGB, OUTPUT);

    ^

    Mando_central:105:3: error: expected unqualified-id before 'if'

    if(!EEPROM.read(0)) {

    ^

    Mando_central:109:3: error: expected unqualified-id before 'else'

    else {

    ^

    Mando_central:113:3: error: 'selectedMode' does not name a type

    selectedMode = EEPROM.read(1);

    ^

    Mando_central:114:3: error: 'timer' does not name a type

    timer = EEPROM.read(2);

    ^

    Mando_central:115:3: error: 'ldrThreshold' does not name a type

    ldrThreshold = EEPROM.read(3);

    ^

    Mando_central:116:18: error: expected constructor, destructor, or type conversion before ';' token

    configureMode();

    ^

    Mando_central:119:3: error: 'Serial' does not name a type

    Serial.print("Connecting to ");

    ^

    Mando_central:120:3: error: 'Serial' does not name a type

    Serial.println(ssid);

    ^

    Mando_central:121:3: error: 'WiFi' does not name a type

    WiFi.begin(ssid, password);

    ^

    Mando_central:122:3: error: expected unqualified-id before 'while'

    while (WiFi.status() != WL_CONNECTED) {

    ^

    Mando_central:127:3: error: 'Serial' does not name a type

    Serial.println("");

    ^

    Mando_central:128:3: error: 'Serial' does not name a type

    Serial.println("WiFi connected.");

    ^

    Mando_central:129:3: error: 'Serial' does not name a type

    Serial.println("IP address: ");

    ^

    Mando_central:130:3: error: 'Serial' does not name a type

    Serial.println(WiFi.localIP());

    ^

    Mando_central:131:3: error: 'server' does not name a type

    server.begin();

    ^

    Mando_central:132:1: error: expected declaration before '}' token

    }

    ^

    Se encontraron varias bibliotecas para "WiFi.h"
    Usado: C:\Users\Jhon
    No usado: C:\Users\Jhon
    No usado: C:\Program
    Se encontraron varias bibliotecas para "EEPROM.h"
    Usado: C:\Users\Jhon
    Se encontraron varias bibliotecas para "DHT.h"
    Usado: C:\Users\Jhon
    Se encontraron varias bibliotecas para "Adafruit_Sensor.h"
    Usado: C:\Users\Jhon
    No usado: C:\Users\Jhon
    exit status 1
    'detectsMovement' was not declared in this scope

    I would like that you help me as soon as possible.
    I will hope your answer wishing you a have a nice day!

    Greetings from México!

    PS. I already have installed all "The Libraries", really i don´t know why the code fail it, if i renamed the adafruit librarie and Installed many libraries about this. Thank you!

    Reply
    • Hi jhon kremer.
      If you have bought the ESP32 course, please post your questions on the RNTLab forum, so that we can reach to you faster:https://rntlab.com/forum/
      Cut the detectsMovement() function and paste it before the setup(). I’m talking about the following lines:
      void detectsMovement() {
      if(armMotion || (armMotion && armLdr)) {
      Serial.println(“MOTION DETECTED!!!”);
      startTimer = true;
      lastMeasure = millis();
      }
      }
      Let me know if this solved your issue. If not, open a new question on the RNTLAB forum. Exclusive for those who have bought the course.

      Regards,
      Sara

      Reply
  11. Hi Sara,

    Thanks for this – really helpful. When I tried it I sometimes got unexpected results – the LED flashed, or just didn’t stay on for the full time. I made a couple of minor changes that I think helped. Firstly, variables that are used in both the main code and the interrupt I made ‘volatile’:

    volatile unsigned long lastTrigger = 0;
    volatile boolean startTimer = false;

    Secondly, I stopped the interrupt from firing again while the LED was still lit:

    void IRAM_ATTR detectsMovement() {
    if (!startTimer) {
    Serial.println(“MOTION DETECTED!!!”);
    digitalWrite(led, HIGH);
    startTimer = true;
    lastTrigger = millis();
    }
    }

    What do you think?

    Best wishes,

    Peter

    Reply
    • Peter,
      From what I’ve read, making shared variables volatile is the right way to handle them, so that there is no chance of using a pre-stored register copy of the variable value, after the variable itself has changed.
      Seems like a good practice….still working better?

      Dave K.

      Reply
  12. Hi ,
    Is it possible to have the input GPIO on a “master” esp32 and the output GPIO on a “slave” esp32 communicating using esp now?

    Reply
  13. Great code. Been looking for this for some time now. Thanks.

    Reply
  14. Witam Sara.
    Bardzo fajny artykuł.
    Jestem pod wrażeniem Twojej wiedzy.
    Pozdrawiam Bogdan.

    Reply
  15. Hi,

    Maybe someone else has mentioned it before but I did not find a post about the interrupt types of the ESP32 when used with Arduino.

    In this tutorial a list is shown with ESP32 interrupt types but the list is not correct! There are no HIGH or LOW interrupts, HIGH and LOW are equal to TRUE and FALSE, 1 and 0 resp. and should be used for logical purposes, not for interrupts.

    By using HIGH or LOW for the interrupt type can lead to unexpected or “faulty” behaviour because HIGH (1) as interrupt type actualy yields an interrupt on the RISING edge and LOW (0) does not correspond to any interrupt type.

    Instead of HIGH and LOW, ONHIGH and ONLOW should be used.

    Here is are the types for ESP32 as defined in Arduino.h:
    RISING 1
    FALLING 2
    CHANGE 3
    ONLOW 4
    ONHIGH 5
    ONLOW_WE 0x0C
    ONHIGH_WE 0x0D

    This is realy different from Arduino Uno for instance.

    I am just starting with the ESP32 and with some experimenting with pushbuttons and interrupts and it looks like the falling edge of a pulse on a input pin with pull_up resistor, also often triggers the FALLING interrupt on the rising edge of a pulse (debouncing is accounted for). It happens often but not always, when releasing the pushbutton. Even after five seconds or more. I checked the inputpin with my oscilliscope and there are no spikes or debounce pulses shown. Is this a known (erratic) behaviour of the ESP32 ?

    Thank you.

    Reply
  16. Hi!

    Thanks for all the suggestions and the good explanations!
    Modifying the code slightly, the “lamp” will always light when motion is detected; this may be more like the real world:

    if (startTimer && (now – lastTrigger > (timeSeconds*1000)) && !digitalRead (motionSensor))

    About IRAM/Instruction RAM: I think it’s not just about the flash being slower, but what effect it has. My understanding is that it must be ensured that all data and functions accessed by an interrupt handler, including those that call the handlers, are in IRAM. If a function or symbol is not properly stored in IRAM and the interrupt handler reads from the flash cache during a flash operation, it will cause a crash.

    Thanks.

    Reply
  17. Rui and Sara, Thank you for the great tutorials. I am really enjoying them and have been telling other people about them.

    Reply
  18. You guys at RNT (Rui and Sara) make learning this stuff so much easier than other sites and it comes down to the clear way you present the material. I have long wanted to find out how to use interrupts in my code but thought must be too difficult for me to figure out. But finally I absolutely needed ‘interrupts’ because I have a optical shaft encoder to read and the speed it runs means that normal code is not going to cut it. So I first watched the video then followed along with the code explanations and got the idea instantly. There was simply nothing in the code that I did not understand except IRAM_ATTR. But you even explained that. As a 70 year old learning this stuff from scratch I feel so empowered by this new knowledge and understanding and that is down to you guys.

    Reply
  19. I have a Wemos D1 Mini with a motion sensor connected to it. I would like to add a LED of 5v to it so if the montion sensor detects movement the led will stay ON for 60 seconds.
    For now I have this:

    binary_sensor:
    – platform: gpio
    pin: GPIO12
    name: “PIR Sensor”
    device_class: motion

    Is it possible to use the same Wemos to power the 5v led?
    Where do I need to connect the LED and what do I have to add to the code?

    Reply
  20. You should always avoid putting a Serial.println statement inside an isr interrupt handler.
    Serial.println(“MOTION DETECTED!!!”);
    This statement was causing my ESP32 to reboot sometimes when the isr was executed.
    Once I commented this statement out, all OK.
    Discussion herehttps://esp32.com/viewtopic.php?f=13&t=3748&p=17131

    Reply
  21. I forgot to mention you can replace the Serial.println statement with an isr safe print statement ets_printf()

    This small change eliminated the rebooting issue

    //Serial.println(“MOTION DETECTED!!!”);
    ets_printf(“MOTION DETECTED!!!\n”);

    Reply
  22. Hi There,

    What do you suggest for implementing the timer in assembly (directly in ESP32)?

    Thanks

    Reply
  23. hey there i need some help i want to connect another led TO GPIO25 that switches on and of after led GPIO26 and switches on just before GPIO26 switchs off
    please help with code

    Reply
  24. The persistent popup advert for your books is VERY annoying. I have purchased the books of interest to me and continually having to be interrupted and close this advert is irritating. Maybe look at some other strategy as it is not up to the standard of your excellent website.

    Reply
    • Hi.
      I’m sorry for that issue.
      If you login into your browser and use your account, for example using your google account on google chrome, it will save that on cache and it will only display it the first three times.
      Regards,
      Sara

      Reply
  25. Hello Random Nerd, excellent article, as usual.
    Using timer for the first time with esp32 and following your article, works real good until I enable esp-now ( or the wifi ) .
    is it possible to get a precise timer running with the WiFi ( or esp-now ) ??
    if yes , how.

    tks

    Reply
  26. tks for the reply Sara as ‘ The Wi-Fi should not interfere with the timers’

    Altough, I see otherwise.

    Will continue my search

    Do you have a sample code that uses timers and wifi ?

    Reply
  27. Hi sara,

    Which GPIO pin on ESP32 board to connect the PIR motion sensor?

    Reply
  28. Hi Sara,
    First Happy Newyear!!
    Currently I’m working on a birdhouse with webcamera for my little son.
    I want to use the PIR code for bird detection in a “counter” ( instead of your LED). Just to detect if there is any activity in the birdhouse.
    I want to run your PIR code together with the “ESP32-CAM Video Streaming Web Server” and have the “counter” value represented in the camera webserver-website…
    Main headache for now is how to handover the “counter” value to the camera webserver. Any idea how to accomplish this?
    THX for your reply.

    Reply
  29. Hi sarah, we would like to do an IoT project exactly like the one you mentioned, but we want to add buzzer and use blynk for notifications, do you might know how to do it ?
    Best regards,
    Lily

    Reply

Leave a CommentCancel reply

Learn ESP32

ESP32 Introduction

ESP32 Arduino IDE

ESP32 Arduino IDE 2.0

VS Code and PlatformIO

ESP32 Pinout

ESP32 Inputs Outputs

ESP32 PWM

ESP32 Analog Inputs

ESP32 Interrupts Timers

ESP32 Deep Sleep

Protocols

ESP32 Web Server

ESP32 LoRa

ESP32 BLE

ESP32 BLE Client-Server

ESP32 Bluetooth

ESP32 MQTT

ESP32 ESP-NOW

ESP32 Wi-Fi

ESP32 WebSocket

ESP32 ESP-MESH

ESP32 Email

ESP32 Text Messages

ESP32 HTTP GET POST

HTTP GET Web APIs

HTTP POST Web APIs

Server-Sent Events

Web Servers

Output Web Server

PWM Slider Web Server

PWM Multiple Sliders Web Server

Async Web Server

Relay Web Server

Servo Web Server

DHT Web Server

BME280 Web Server

BME680 Web Server

DS18B20 Web Server

LoRa Web Server

Plot/Chart Web Server

Chart Multiple Series Web Server

SPIFFS Web Server

Thermostat Web Server

Momentary Switch Web Server

Physical Button Web Server

Input Fields Web Server

Images Web Server

RGB LED Web Server

Timer/Pulse Web Server

HTTP Auth Web Server

MPU-6050 Web Server

MicroSD Card Web Server

Stepper Motor Web Server

Stepper Motor WebSocket

Gauges Web Server

DIY Cloud

ESP32 Weather Station

Control GPIOs

View Sensor Readings

ESP32 MySQL

ESP32 PHP Email

ESP32 SIM800L

Cloud Node-RED Dashboard

Cloud MQTT Broker

ESP32 Cloud MQTT

ESP-NOW

ESP-NOW Introduction

ESP-NOW Two-Way

ESP-NOW One-to-Many

ESP-NOW Many-to-One

ESP-NOW + Wi-Fi Web Server

Firebase

Firebase Realtime Database

Firebase Web App

Firebase Authentication

Firebase BME280

Firebase Web App Sensor Readings

Firebase ESP32 Data Logging

Modules

ESP32 Relay Module

ESP32 DC Motors

ESP32 Servo

ESP32 Stepper Motor

ESP32 MicroSD Card

ESP32 MicroSD Card Data Logging

ESP32 PIR

ESP32 HC-SR04

ESP32 I2C Multiplexer

Sensors

ESP32 DHT11/DHT22

ESP32 BME280

ESP32 BME680

ESP32 DS18B20

ESP32 Multiple DS18B20

ESP32 BMP180

ESP32 BMP388

MQTT DHT11/DHT22

MQTT BME280

MQTT BME680

MQTT DS18B20

ESP32 MPU-6050

Displays

ESP32 OLED

ESP32 LCD

OLED Temperature

ESP32 Features

ESP32 Hall Sensor

ESP32 Touch Sensor

ESP32 I2C

ESP32 Flash Memory

ESP32 Dual Core

Useful Guides

ESP32 Troubleshooting

ESP32 Access Point

ESP32 Fixed IP Address

ESP32 MAC Address

ESP32 Hostname

ESP32 OTA

ESP32 OTA Arduino

ESP32 OTA VS Code

ESP32 Solar Panels

ESP32 Alexa

ESP32 Install SPIFFS

ESP32 Time and Date

ESP32 Epoch Time

ESP32 Google Sheets

ESP32 Email Altert

ESP32 ThingSpeak

Weather Station Shield

ESP32 IoT Shield

ESP32 Weather Station PCB

ESP32 Wi-Fi Manager

VS Code and PlatformIO

VS Code SPIFFS

VS Code Workspaces

Save Data Preferences Library

Reconnect to Wi-Fi

Useful Wi-Fi Functions

Other Projects

Telegram Control Outputs

Telegram Sensor Readings

Telegram Detect Motion

Telegram Group

ESP32 Status PCB

ESP32 BMP388 Datalogger

ESP32 Web Serial

ESP32 Door Monitor

ESP32 Door Telegram

ESP32 NTP Timezones

ESP32 Boards

ESP32 Camera

ESP32 LoRa

ESP32 OLED

ESP32 SIM800L

Learn More

Learn ESP32

Learn ESP8266

Learn ESP32-CAM

Learn MicroPython

Learn Arduino

Build Web Servers eBook

Smart Home eBook

Firebase Web App eBook

ESP32 Premium Course

Affiliate Disclosure:Random Nerd Tutorials is a participant in affiliate advertising programs designed to provide a means for us to earn fees by linking to Amazon, eBay, AliExpress, and other sites. We might be compensated for referring traffic and business to these companies.



Learn ESP32 with Arduino IDE eBook » Complete guide to program the ESP32 with Arduino IDE!



SMART HOME with Raspberry Pi, ESP32, and ESP8266 » learn how to build a complete home automation system.



Learn Raspberry Pi Pico/Pico W with MicroPython​ » The complete getting started guide to get the most out of the the Raspberry Pi Pico/Pico W (RP2040) microcontroller board using MicroPython programming language.



🔥 Learn LVGL: Build GUIs for ESP32 Projects​ » Learn how to build Graphical User Interfaces (GUIs) for ESP32 Projects using LVGL (Light Versatile Graphics Library) with the Arduino IDE.

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.


[8]ページ先頭

©2009-2025 Movatter.jp