Counting motions with motion sensor (Arduino)




You probably wondering how you can count some activities with motion sensor by using Arduino.
Well it's pretty easy to do that by using few lines of sketch below.


int led = 6;                // the pin that the LED is atteched to
int sensor = 7;              // the pin that the sensor is atteched to

int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;

void setup() {
  pinMode(led, OUTPUT);      // initalize LED as an output
  pinMode(sensor, INPUT);    // initialize sensor as an input
  Serial.begin(9600);        // initialize serial
}

void loop(){

  if (digitalRead(sensor)){   // read sensor value
  digitalWrite(led, HIGH);   // turn LED ON
    }
 
 else {
      digitalWrite(led, LOW); // turn LED OFF
    }
   
val = digitalRead(sensor); // read input value
if (val ==  HIGH) { // check if the input is HIGH
currentState = 1;
}
else {
currentState = 0;
}
if(currentState != previousState){
if(currentState == 1){
counter = counter + 1;
Serial.print("Motion has been ditected ");
Serial.print(counter);
Serial.print(" Times.");
Serial.println(" ");
}
}
previousState = currentState;   
       delay(100);
  }

What does the sketch do?
Well the sketch is for PIR motion sensor. It takes the reading from the sensor and when sensor detects a motion it turns on the led (you can turn on anything you want) and at the same time it counts how many times it detected the motion.

I didn't draw a diagram of circuit because I thought it's too easy. Anyway, enjoy! :)

No comments:

Post a Comment



Newly posted:
Reason why rich getting richer and poor getting poorer