Overview of HC-SR04 Distance Sensor
HC-SR04 is a ranging module, measuring a distance using sound wave ranging from 20 cm to 400 cm. Its accuracy is 3 mm.
A running program on bread-board |
This sensor come with four pins. The basic components are a mic and speaker built on-board as shown in the picture.
Front Panel Of HC-SR04 I bought from TaydaElectronics |
Device pin diagram from datasheet |
Signal Timing |
To use this device:
- Raise Trigger pin high in TTL 5V for 10 uS.
- The sensor will send back a 40 kHz signal determine the device is working.
- Get the HIGH time response by the sensor, using a the microcontroller timer
- Pull Trigger pin low
- Calculate for distance
The distance formula (in meters) is (high level time * 340m/S)/2
Arduino Interfacing And Programming
Using the Arduino Advanced I/O function, we can get the timing of any input level fed to Arduino digital pins.
The pulseIn() function store the timing in microsecond of any input high or low.
The syntax is:
pulseIn(pin, value)
pulseIn(pin, value, timeout)
Where,
pin is any digital input pin
value is a logic value - HIGH or LOW
Test Program |
Schematic |
#include <SPI.h>
//Select pin 8 for Enable pin
LiquidCrystal lcd(8);
const int trigPin=5;
const int echoPin=3;
/*
PWM OUTPUT 0-25000uS in which 1cm=50uS
*/
long duration;
int distance;
void setup()
{ // put your setup code here, to run once:
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600);
lcd.begin(16,4);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("HC-SR04 Ultra");
lcd.setCursor(0,1);
lcd.print("Sonic Sensor");
delay(2000);
}
void loop()
{ // put your main code here, to run repeatedly:
digitalWrite(trigPin,LOW);
delayMicroseconds(7);
// Set the trigPin high for 10 uS
digitalWrite(trigPin,HIGH);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration=pulseIn(echoPin,HIGH);
// Calculation for distance
if(duration<=25000)
distance = duration * 0.034 / 2;
else
distance=0;
Serial.println("Distance Measured : ");
Serial.print(distance);
Serial.println(" cm");
//lcd.clear();
lcd.setCursor(-4,2);
lcd.print("Distnace: ");
lcd.setCursor(-4,3);
lcd.print(String(distance)+" cm ");
duration=0;
distance=0;
delay(1000);
}
No comments:
Post a Comment