PIR sensor with Arduino; can't incorporate Blynk

Hi. I took a series of codes from CircuitMagic to run a PIR sensor with an Arduino; works without a hitch. I try to incorporate Blynk so I can view on my phone whether the LED is on or off; once I do that, the sensor doesn’t work and the LED on the Arduino board remains ON. What am I doing wrong? Thanks for looking through this.

#define BLYNK_PRINT Serial //I added this line
#include <SPI.h> //I added this line
#include <Ethernet.h> //I added this line
#include <BlynkSimpleEthernet.h> //I added this line

char auth[] = "auth code"; //I added this line

int calibrationTime = 30;       
long unsigned int lowIn;        
long unsigned int pause = 5000; 
 
boolean lockLow = true;
boolean takeLowTime; 
 
int pirPin = 3;  
int ledPin = 13;
 
void setup(){
  Serial.begin(9600);
  Blynk.begin(auth); //I added this line
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);
 
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
  }
 
void loop(){

     Blynk.run(); //I added this line
 
     if(digitalRead(pirPin) == HIGH){
       digitalWrite(ledPin, HIGH);
       Blynk.virtualWrite(V14, HIGH); //I added this line
       if(lockLow){ 
         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, LOW);  
       Blynk.virtualWrite(V14, LOW); //I added this line
       if(takeLowTime){
        lowIn = millis();          
        takeLowTime = false;       
        }
       if(!lockLow && millis() - lowIn > pause){ 
           lockLow = true;                       
           Serial.print("motion ended at ");     
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
  }

Please move your code out of loop and use simple timer library. This should fix your problem. Please see the example sketch here

1 Like

Hi,

Do you have anything to stop it trying to do a Blynk.virtualWrite every time it goes around the loop?

Try moving the Blynk.virtualWrite just above the delay(50) for high and low.