The HC-SR04 module is easy to use and we has a simple Aruduino demo for the beginning user.
Soon, we will provide another Ultar Sonic Modules SDM-IO, which has faster response and no Blind Area. Stay tuned.
First, it should define two kinds of pins for trigger, 8 for trigger and 9 for echo.
Code: Select all
#define CM 1 //Centimeter
#define INC 0 //Inch
#define TP 8 //Trig_pin
#define EP 9 //Echo_pin
void setup()
{
pinMode(TP,OUTPUT); // set TP output pin for trigger
pinMode(EP,INPUT); // set EP input pin for echo
Serial.begin(9600); // init serial 9600
Serial.println("-------------------Ultra_Demo_Start---------------------------------");
}
void loop()
{
long microseconds = TP_init(); // trigger and receive
Serial.print("microseconds = ");
Serial.println(microseconds);
long distacne_cm = Distance(microseconds, CM); // Calculating the distance
Serial.print("Distacne_CM = ");
Serial.println(distacne_cm); // printf the distance about CM
delay(3000);
}
Second, init the trigger signal, you only need to supply a short 10uS pulse to the trigger input to start the ranging, and then the module will send out an 8 cycle burst of ultrasound at 40 kHz and raise its echo.You can calculate the range through the time interval between sending trigger signal and receiving echo signal. the range = high level time * velocity (340M/S) / 2; we suggest to use over 60ms measurement cycle, in order to prevent trigger signal to the echo signal.Then we could Calculating the distance, because we have the pulse width and ues Formula:
Distance_CM= ((Duration of high level)*(Sonic :340m/s))/2.
So, we have bellow othre two function:
Code: Select all
<span style="color: #888888;"> long Distance(long time, int flag) { long distacne; if(flag) distacne = time /29 / 2 ; // Distance_CM = ((Duration of high level)*(Sonic :340m/s))/2 // = ((Duration of high level)*(Sonic :0.034 cm/us))/2 // = ((Duration of high level)/(Sonic :29.4 cm/us))/2 else distacne = time / 74 / 2; // INC return distacne; } long TP_init() { digitalWrite(TP, LOW); delayMicroseconds(2); digitalWrite(TP, HIGH); // pull the Trig pin to high level for more than 10us impulse delayMicroseconds(10); digitalWrite(TP, LOW); long microseconds = pulseIn(EP,HIGH); // waits for the pin to go HIGH, and returns the length of the pulse in microseconds return microseconds; // return microseconds }</span></pre>
<pre>
The more information is the datasheet:
Download the Datasheet from here.
Download the Demo for Arduino.
Article courtesy of elecfreaks.com