Friday, May 11, 2018

Security system with arduino and ultrasonic sensor

In this arduino tutorial we will learn how to make an Security system with arduino and ultrasonic sensor.




Component needed for this tutorial :

  • Arduino board
  • buzzer
  • Ultrason
  • Breadbord and wires


Circuit schematics :


What is ultrason? :

it emits an ultrasound at 40 000 Hz which travels through the air and if there is an if there is an object on its path it will bounce back to the module. Considering the travel time and the speed of the sound you can calculate the distance.

The HC-SR04 Ultrasonic module has 4 pins, ground, vcc, trig and echo. The ground and the vcc pins of the module needs to be connected to the ground and the 5 volts pins on the arduino board respectively and the trig and echo pins to any digital pin on the arduino board.


In order to generate the ultrasound you need to set the trig on a high state for 10 microseconds. That will send out an 8 cycle sonic burst which will travel at the speed sound and it will be received in the echo pin. The echo pin will output the time in microseconds the sound wave traveled.



Source code :

Now let's see the arduino sketsh. I will use the pins 3,5,9 and 10 and I will name them redpin, buzpin , trigpin and echopin. In setup section we need to define them as output except echopin. In the void loop I will clear the trigpin and sets it on high state for 10 micro seconds, and I will make the echopin in reading status for return the sound wave travel time in microseconds. If the distance is less than or equal 100 the buzzer and the led will be high , else they be low. You can change the 100 by the distance you want.

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
int redpin = 3;
int buzpin = 5; //the buzzer
// defines variables
long duration;
int distance;
  
void setup() {
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(redpin, OUTPUT); // Sets the redPin as an Input
pinMode(buzpin, OUTPUT); // Sets the buzPin as an Input
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);

if(distance <= 100){
  analogWrite(redpin, 100);
  analogWrite(buzpin, 100);
}

else{
  digitalWrite(redpin, LOW);
  digitalWrite(buzpin, LOW);
}
} 




Realization video :



No comments:

Post a Comment