• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

Motion is not detected in serial monitor

Q&A Forum › Category: Home Automation › Motion is not detected in serial monitor
0 Vote Up Vote Down
Iliuta Ovidiu Dragos asked 1 month ago

My PIR sensor does not detects motion, in unit 7.4 Motion Detector with Notifications, from Smart_Home ebook.
I used the code provided in ebook. I use the GPIO 4 from ESP 32 for PIR out, VCC to 3v3 ESP PIN, GND to GND.  I tried to test the sensor on other simple example and it worked.

Question Tags: Arduino IDE, ESP32, home automation, PIR sensor
19 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 1 month ago

Hi.
Can you share with me the example that worked?
 
Regards,
Sara

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 1 month ago

Hi, this is the code that works.

#include <Arduino.h>
#include <WiFi.h>
extern “C” {
#include “freertos/FreeRTOS.h”
#include “freertos/timers.h”
}
#include <AsyncMqttClient.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
// WiFi
#define WIFI_SSID “”
#define WIFI_PASSWORD “”
// MQTT
#define MQTT_HOST IPAddress()
#define MQTT_PORT 1883
#define BROKER_USER “”
#define BROKER_PASS “”
#define MQTT_PUB_TEMP “esp/bme280/temperature”
#define MQTT_PUB_HUM “esp/bme280/humidity”
#define MQTT_PUB_PRES “esp/bme280/pressure”
#define MQTT_PUB_MOTION “esp/motion/notification”
// PIR
const int PIR_PIN = 4;
// BME280
Adafruit_BME280 bme;
// MQTT
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
// Publish interval
unsigned long previousMillis = 0;
const long interval = 10000;
// PIR debounce
volatile bool pirFlag = false;
volatile unsigned long lastPirTime = 0;
const unsigned long PIR_DEBOUNCE = 2500;
// ===== ISR PIR =====
void IRAM_ATTR detectsMovement() {
unsigned long now = millis();
if (now – lastPirTime > PIR_DEBOUNCE) {
pirFlag = true;
lastPirTime = now;
}
}
// ===== WIFI =====
void connectToWifi() {
Serial.println(“Connecting to Wi-Fi…”);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf(“[WiFi-event] event: %d\n”, event);

switch(event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
mqttClient.connect();
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println(“WiFi lost connection”);
xTimerStop(mqttReconnectTimer, 0);
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
// ===== MQTT =====
void connectToMqtt() {
Serial.println(“Connecting to MQTT…”);
mqttClient.connect();
}
void onMqttConnect(bool sessionPresent) {
Serial.println(“Connected to MQTT.”);
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println(“Disconnected from MQTT.”);
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}
// ===== SETUP =====
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
pinMode(PIR_PIN, INPUT_PULLDOWN);
attachInterrupt(digitalPinToInterrupt(PIR_PIN), detectsMovement, RISING);
if (!bme.begin(0x77)) {
Serial.println(“Could not find a valid BME280 sensor!”);
while (1);
}
mqttReconnectTimer = xTimerCreate(“mqttTimer”, pdMS_TO_TICKS(2000), pdFALSE, 0, (TimerCallbackFunction_t)connectToMqtt);
wifiReconnectTimer = xTimerCreate(“wifiTimer”, pdMS_TO_TICKS(2000), pdFALSE, 0, (TimerCallbackFunction_t)connectToWifi);
WiFi.onEvent(WiFiEvent);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
mqttClient.setCredentials(BROKER_USER, BROKER_PASS);
connectToWifi();
}
// ===== LOOP =====
void loop() {
// ======= PIR MQTT =======
if (pirFlag) {
uint16_t packetIdPub = mqttClient.publish(MQTT_PUB_MOTION, 1, true, “Motion Detected!”);
Serial.printf(“Publishing on topic %s at QoS 1, packetId: %i Motion Detected! \n”, MQTT_PUB_MOTION, packetIdPub);
pirFlag = false;
}
// ======= BME280 MQTT =======
unsigned long currentMillis = millis();
if (currentMillis – previousMillis >= interval) {
previousMillis = currentMillis;
float t = bme.readTemperature();
float h = bme.readHumidity();
float p = bme.readPressure() / 100.0F;
uint16_t id1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(t).c_str());
Serial.printf(“Publishing on topic %s at QoS 1, packetId: %iMessage: %.2f \n”, MQTT_PUB_TEMP, id1, t);
uint16_t id2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(h).c_str());
Serial.printf(“Publishing on topic %s at QoS 1, packetId %i: Message: %.2f \n”, MQTT_PUB_HUM, id2, h);
uint16_t id3 = mqttClient.publish(MQTT_PUB_PRES, 1, true, String(p).c_str());
Serial.printf(“Publishing on topic %s at QoS 1, packetId: %iMessage: %.3f \n”, MQTT_PUB_PRES, id3, p);
}
}

0 Vote Up Vote Down
Sara Santos Staff answered 1 month ago

Hi.
That’s weird… because the only thing that you changed seems to be adding a debounce timer to the PIR sensor, and changing the GPIO.
 
Maybe that GPIO doesn’t work as the one we use in our code (GPIO 26)??…
 
I’m not sure exactly why the other example didn’t work for you…
Regards,
Sara

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 1 month ago

Hello, I changed the GPIO pin to 26, and now it works, detects movement. But, MQTT is disconnecting and connecting frequently, and it reboots. Here is my serial monitor:
09:59:47.214 -> Guru Meditation Error: Core 1 panic’ed (Interrupt wdt timeout on CPU1).
09:59:47.245 ->
09:59:47.245 -> Core 1 register dump:
09:59:47.245 -> PC : 0x4008f8b6 PS : 0x00060c35 A0 : 0x8008e0f2 A1 : 0x3ffbf43c
09:59:47.245 -> A2 : 0x3ffb8314 A3 : 0x3ffb81a4 A4 : 0x00000004 A5 : 0x00060c23
09:59:47.245 -> A6 : 0x00060c23 A7 : 0x00000001 A8 : 0x3ffb81a4 A9 : 0x00000018
09:59:47.277 -> A10 : 0x3ffb81a4 A11 : 0x00000018 A12 : 0x3ffc5054 A13 : 0x00060c23
09:59:47.277 -> A14 : 0x007bf5e8 A15 : 0x003fffff SAR : 0x00000006 EXCCAUSE: 0x00000006
09:59:47.277 -> EXCVADDR: 0x00000000 LBEG : 0x4008a365 LEND : 0x4008a375 LCOUNT : 0xfffffffb
09:59:47.277 -> Core 1 was running in ISR context:
09:59:47.277 -> EPC1 : 0x400e7053 EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4 : 0x00000000
09:59:47.309 ->
09:59:47.309 ->
09:59:47.309 -> Backtrace: 0x4008f8b3:0x3ffbf43c |
09:59:47.309 ->
09:59:47.309 -> Core 0 register dump:
09:59:47.309 -> PC : 0x4008fa4b PS : 0x00060035 A0 : 0x8008dd1b A1 : 0x3ffbed0c
09:59:47.310 -> A2 : 0x3ffbf5e8 A3 : 0xb33fffff A4 : 0x0000abab A5 : 0x00060023
09:59:47.310 -> A6 : 0x00060021 A7 : 0x0000cdcd A8 : 0x0000abab A9 : 0xffffffff
09:59:47.342 -> A10 : 0x3ffc40ec A11 : 0x00000000 A12 : 0x3ffc40e8 A13 : 0x00000007
09:59:47.342 -> A14 : 0x007bf5e8 A15 : 0x003fffff SAR : 0x0000001d EXCCAUSE: 0x00000006
09:59:47.342 -> EXCVADDR: 0x00000000 LBEG : 0x00000000 LEND : 0x00000000 LCOUNT : 0x00000000
09:59:47.342 ->
09:59:47.342 ->
09:59:47.342 -> Backtrace: 0x4008fa48:0x3ffbed0c |
09:59:47.342 ->
09:59:47.342 ->
09:59:47.342 ->
09:59:47.342 -> ELF file SHA256: 8f1a30e1001a2a4d
09:59:47.380 ->
09:59:47.522 -> Rebooting…

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 1 month ago

Update: After I enter Node-RED, it does not detect movement anymore. I think it has to do with Raspberry Pi. After I power off the Raspberry Pi , and upload again the code on ESP32, it detects movement again. The reboot and disconnecting still happens.

0 Vote Up Vote Down
Sara Santos Staff answered 1 month ago

Hi.
Remove the Serial.print from the detectsMovement function, that might be crashing the board.
 
Additionally, can you tell me the versions of the AsyncMQTT and AsyncTCP libraries you’re using?
 
Regards,
Sara

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 4 weeks ago

I am using AsyncTCP 1.1.1 and AsyncMQTT 0.9.0.

0 Vote Up Vote Down
Sara Santos Staff answered 4 weeks ago

You should be using the AsyncTCP library by ESP32Async by mentioned in the ebook. It is currently on version 3.4.9.
 
As for the AsyncMQTT library, you should use our forked version of the library available to download at this link: https://randomnerdtutorials.com/async-mqtt-client-download
 
I’m not sure if this is making any difference for you to have different results, but feel free to change the libraries (or not, if everything is working as expected now.)
 
Regards,
Sara

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 4 weeks ago

Hi, I updated the libraries. The problems persists. It seems that when ESP is connecting to the MQTT Host(Raspberry Pi), the motion detection is not printed in the Serial Monitor. When I power off the Raspberry Pi, the motion detection is printed on Serial Monitor.

0 Vote Up Vote Down
Sara Santos Staff answered 4 weeks ago

Does the issue with the broker only happen now that you introduced the PIR sensor?

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 4 weeks ago

Yes.. but the other topics are publishing, just not the “esp/motion/notification”

0 Vote Up Vote Down
Sara Santos Staff answered 4 weeks ago

Ok. 
Tomorrow I’ll test all our instructions from the start using the PIR motion sensor and try to figure out if there’s anything wrong.
I’ll let you know.
Regards,
Sara

0 Vote Up Vote Down
Sara Santos Staff answered 3 weeks ago

Hi.
 
I just tested everything from scratch and it is working as expected…
 
Can you tell me the version of mosquitto that you’re running?
On the Raspberry Pi console, run
mosquitto -v
 
The constant reboots may be related to the PIR not being connected with a secure cable, which is giving false positives and triggering the ISR constantly, crashing the ESP32.
To fix it, you can try to find a better cable to secure your connection better, or, as you did previously, add some sort of debounce as you would do with a pushbutton.

As for the other issue with the Node-RED, it is very hard to explain what might be causing that issue without more information…
 
 
 
P.S: With the latest version of the Raspberry Pi OS, which was just released a few days ago, and with the latest version with mosquitto, there are now a few new commands we need to run when configuring mosquitto.
I don’t think this is your issue, because your previous projects were working fine…
Either way, we’re currently working on updating the eBook and the newest version will be released in just a few days.
 
 
Regards,
Sara

0 Vote Up Vote Down
Sara Santos Staff answered 3 weeks ago

To test the issue with Node-RED, you can also try to just configure an MQTT IN node that subscribes to esp/motion/notification and connect it to a debug node to see if it prints true on the debugging window, when motion is detected.
 
Regards,
Sara

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 3 weeks ago

I am using mosquitto version 2.0.21

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 3 weeks ago

I tried to test the issue with Node-RED, an it persists. In serial monitor the Motion detection is printed, but on node red flow, in debug console, does not show up. But when I test the example from the course, the Motion detection does not happen.
This is the code that works:
#include <WiFi.h>
#include <AsyncMqttClient.h>
#define PIR_PIN 4 
// WiFi credentials
const char* WIFI_SSID = “YOUR_WIFI”;
const char* WIFI_PASSWORD = “YOUR_PASSWORD”;
// MQTT credentials
const char* MQTT_HOST = “YOUR_MQTT_BROKER_IP”;
const int MQTT_PORT = YOUR_MQTT_PORT; // e.g. 1883 or 1884
const char* MQTT_USER = “YOUR_MQTT_USERNAME”;
const char* MQTT_PASS = “YOUR_MQTT_PASSWORD”;
const char* MQTT_TOPIC = “esp/motion/notification”;
AsyncMqttClient mqttClient;
WiFiEventId_t wifiConnectHandler;
WiFiEventId_t wifiDisconnectHandler;
unsigned long lastMotionState = LOW;
// Reconnect timers
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
// —————- WIFI HANDLERS —————- //
void connectToWifi() {
Serial.println(“Connecting to Wi-Fi…”);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void connectToMqtt() {
Serial.println(“Connecting to MQTT…”);
mqttClient.connect();
}
void WiFiEventConnected(WiFiEvent_t event, WiFiEventInfo_t info) {
Serial.println(“Connected to Wi-Fi”);
connectToMqtt();
}
void WiFiEventDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
Serial.println(“Disconnected from Wi-Fi”);
xTimerStart(wifiReconnectTimer, 0);
}
// —————- MQTT HANDLERS —————- //
void onMqttConnect(bool sessionPresent) {
Serial.println(“Connected to MQTT!”);
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println(“Disconnected from MQTT”);
xTimerStart(mqttReconnectTimer, 0);
}
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
// Timers for reconnecting
mqttReconnectTimer = xTimerCreate(“mqtt”, pdMS_TO_TICKS(2000), pdFALSE, NULL,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate(“wifi”, pdMS_TO_TICKS(2000), pdFALSE, NULL,
reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
// Register WiFi events
WiFi.onEvent(WiFiEventConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);
WiFi.onEvent(WiFiEventDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
// Configure MQTT
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
mqttClient.setCredentials(MQTT_USER, MQTT_PASS);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
// Connect to Wi-Fi
connectToWifi();
}
void loop() {
int currentState = digitalRead(PIR_PIN);
if (currentState != lastMotionState) {
if (currentState == HIGH) {
Serial.println(“Motion detected!”);
mqttClient.publish(MQTT_TOPIC, 0, true, “true”);
} else {
mqttClient.publish(MQTT_TOPIC, 0, true, “false”);
}
lastMotionState = currentState;
}
delay(50); // small debounce
}

0 Vote Up Vote Down
Sara Santos Staff answered 3 weeks ago

Hi.
I think the issue with your code example is that is doesn’t connect to MQTT and thus it doesn’t publish the message.
That example doesn’t use the same functions we use in our examples to connect to MQTT.
Try this code instead: https://gist.github.com/sarasantos/4baeaac051df60c691dcf6adc22ac40e
 
Let me know if this works.
 
Regards,
Sara
 

0 Vote Up Vote Down
Iliuta Ovidiu Dragos answered 3 weeks ago

Hello, your code works, it detects movement in Node-RED.

0 Vote Up Vote Down
Sara Santos Staff answered 3 weeks ago

Great.
Now, you can apply those changes to detect motion (without the ISR) in the other code.
Regards,
Sara

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [eBook Updated] Smart Home with Raspberry Pi, ESP32, and ESP8266 Version 1.7 November 28, 2025
  • [eBook Updated] Smart Home with Raspberry Pi, ESP32, and ESP8266 V1.6 September 9, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.