Wednesday, September 18, 2013

Interfacing HC-SR04 Ultrasonic Module with Arduino Pro Mini

SR04 is a module that can detect distance between 2cm to 400cm by sending out ultrasonic waves and calculating the time between the sent signal and echo received.


Steps:
  1. Send the trigger signal - a TTL 10us signal
  2. Wait for the echo pin to get high.
  3. Calculate the time for which the echo pin is high using a timer.
  4. Calculate the distance using 
Distance = high level time * velocity (340M/S) / 2



Here is the code for Arduino Pro Mini -


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const int echo = 11;
const int trig = 10;
long duration;
long dist;
void setup()
{
  pinMode(echo,INPUT);
  pinMode(trig,OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);
  duration=pulseIn(echo,HIGH);
  dist =  duration / 58;
  Serial.println(dist);
  Serial.println(duration);
  delay(1000);
}
  
  


The above code is very basic and does not have the out of range or too close feature. Hopefully I will update it in the next post.

No comments :

Post a Comment