Tuesday, 15 March 2016

How to count something with ultrasonic sensor (Arduino)



If you are turning on and off something with ultrasonic sensor and you want to keep a record of something that how many times the ultrasonic sensor has turned on that thing than this sketch can do the job for you.


int ledPin = 7; // pin for the LED
int trigPin = 8;
int echoPin = 9;

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

void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
Serial.begin(9600);
}

void loop(){
delay(500);// reading will be taken after ....miliseconds
Serial.println("\n");

int duration, distance;
    digitalWrite (trigPin, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin, LOW);
    duration = pulseIn (echoPin, HIGH);
    distance = (duration/2) / 29.1;
  
    if (distance < 15) {  // Change the number for long or short distances.
      digitalWrite (ledPin, HIGH);

    }
 else {
      digitalWrite (ledPin, LOW);
    } 

val = digitalRead(ledPin); // read input value
if (val ==  HIGH) { // check if the input is HIGH (led on)
currentState = 1;
}
else {
currentState = 0;
}
if(currentState != previousState){
if(currentState == 1){
counter = counter + 1;
Serial.print("Led has been turned on ");
Serial.println(counter);
Serial.print("times.");
}
}
previousState = currentState;
}


Remember the led is just an example. You can count many more things like how many times it (sensor) turned on the relay and so on... A screenshot can be seen below.


What do you need:
1x Led
1x 10k ohm resistor (optional) it might be be very bright without it.
1x Ultrasonic sensor
1x Arduino board
and few wires.

Note:
This works only when you keep the serial monitor open on your PC or phone, if you close it and open again than the sketch will start from one again.
Enjoy!!!

No comments:

Post a Comment