Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
// P2: Using Ultrasonic sensor measure the distance *//
static int Eco=8;
static int Trig=9;
static int Switch=10;
void setup() // setup fuction to set mode of pins
{
Serial.begin(9600); // Baud rate that means amout of bits transfer per second
pinMode(Eco,INPUT); // declare Eco pin as INPUT pin
pinMode(Trig,OUTPUT); // declare Trig pin as OUTPUT pin
pinMode(Switch,INPUT); // declare Switch pin as INPUT pin
}
void loop() // continuous folling loop after start program
{
if(digitalRead(Switch)==1); // swich to activate utrasonic sensor
{
int count,Distance; // variable to store mesured distance
digitalWrite(Trig,LOW); // make Trig pin as LOW
delay(5);
digitalWrite(Trig,HIGH); // making Trig pin as HIGH to pass signal
delay(10);
digitalWrite(Trig,LOW); // make Trig as LOW
count=pulseIn(Eco,HIGH); // waite to catch that bounceback that signal
Distance=(count/2)*0.0343; // calculate the exact distance using formula
Serial.print("Distance="); // print string on serial monitor
Serial.print(Distance); // print distance on serial monitor
}
}