0

I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 HIGH ex. HIGH...LOW...HIGH...LOW...HIGH (The LOW == no movement) it will trigger and alarm.

I want to reset the counter of HIGHs if there's no movement detected. The problem is the loop will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)

int calibrationTime = 30;
int pirPin = 5;
int ledPin = 6;
int sensorState;
int stateCount = 0; //How much movement is detected
int stateThreshold = 3; //THRESHOLD
bool isSensorHigh;

void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  digitalWrite(pirPin, LOW);
  Serial.print("calibrating sensor ");
  for (calibrationTime; calibrationTime > 0; calibrationTime--) {
    Serial.print(calibrationTime);
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}
void loop() {
  sensorState = digitalRead(pirPin);
  //Serial.println(sensorState);
  if (sensorState == 1) {
    isSensorHigh = true;
  }
  if (sensorState == 0 && isSensorHigh == true) {
    isSensorHigh = false;
    stateCount++;
  }
  //Set pins 2,3,4 here to LOW if there's no movement detected over time
  if (stateThreshold == 3) {
    switch (stateCount) {
      case 1:
        digitalWrite(2, HIGH);
        break;
      case 2:
        digitalWrite(3, HIGH);
        break;
      case 3:
        digitalWrite(4, HIGH);
        break;
    }
  }
  if (stateCount == stateThreshold) {
    blinkLeds();
    delay(3000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(ledPin, LOW);
    stateCount = 0;
  }
  Serial.println(stateCount);
  delay(150);
}

void blinkLeds() {
  for (int x = 4; x > 0; x--) {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    delay(1000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    delay(1000);
  }
}
1

Use millis() instead on delay. Ref: https://www.arduino.cc/en/reference/millis

  • I could get the span between the millis() and use that value. Pretty much all I need. Thanks – conquistador Jan 14 '17 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.