Interrupt for motion sensor

Hey guys,
I would use a motion sensor to detect the presence from my cat.
The sensor gives me a HIGH signal when something is detected and in case of nothing detected a LOW signal. Now I thought, it should work a interrupt.
I don´t know, the example from sketchbuilder doesn´t work…

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "xxxxxxxxxxxxxxxxxxxxxxxx";       
char ssid[] = "xxxxxxxxxxx"; 
char pass[] = "xxxxxxxxxxxxxxxxxxxxxxx"; 

WidgetLED led1(V1);

volatile bool pinChanged = false;
volatile int  pinValue   = 0;

void checkPin()
{
  pinValue = !digitalRead(2);
  pinChanged = true;
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), checkPin, CHANGE);
}

void loop()
{
  Blynk.run();
  if (pinChanged) {
    if (pinValue) {
      led1.on();
    } else {
      led1.off();
    }
    pinChanged = false;
  }
}

The widget LED on V1 doesn´t change his status when it should be on

The normal reason for using interrupts is to remove repetitive code in the void loop which constantly checks something (usually the state of the pin that the sensor is connected to).

Instead of using the interrupt function to change the state of the Blynk LED, you’re simply changing a variable, which then has to be checked within the void loop.

Having said that, your approach should work, even though it’s not very efficient and Blynk friendly, but I think the issue is with the variable types.

You probably need to be using volatile variable types within the ISR.
https://www.arduino.cc/reference/en/language/variables/variable-scope--qualifiers/volatile/

But, as I said before, you’d be better doing the Blynk stuff within the ISR function rather than in the void loop.

Pete.

Under the motto “Absolutely not blynk-friendly” I found a solution with works. Why I have not tried it before??

int WemosPinD1 = 5;
bool  State_MotionSensor = 0;            

WidgetLED led1(V50);

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  pinMode(WemosPinD1, INPUT_PULLUP);
}

void loop()
{
  Blynk.run();
  State_MotionSensor = digitalRead(WemosPinD1);
  if (State_MotionSensor == 1){
    led1.on();
  }
  if (State_MotionSensor == 0){
    led1.off();
  }
}

If you’re going to take the approach of polling the PIR pin on a frequent basis to check its state then you’d be far better doing this in a timed routine that is called say every 200ms.
This would add a maximum delay of 200ms between the PIR triggering and the ESP being aware of it, but on average that delay would be 100ms.
I don’t think you’re going to notice that sort of delay, and it will make your code much more robust.
You’re currently updating the LED state to turn it on or off every time the void loop executes (potentially thousands of times per second), which will flood the server

Pete.

1 Like