Version: 1
Status: Beta
License: GPL
The Ultrasonic Distance Module HC-SR04 is popular with hobbyist for obstacle avoidance and ranging. It is commonly used with the Arduino. I have used it with the Arduino and with the RaspberryPi.
I recently received the startKIT and was looking a quick learning project for intefacing with sensors. So, after soldering all the header pins, I connected up the HC-SR04. The below sample code runs fine in the xTIMEcomposer Studio.
/* Quick test for using the HC-SR04 Ultrasonic Distance Sensor
* HC-SR04 is a 5V device
* Used a voltage divider on Echo to bring down to 3.3V
* app_HC-SR04.xc
*
* Created on: Jan 5, 2014
* Author: NickE
*/
#include <xs1.h>
#include <timer.h>
#include <stdio.h>
in port inP = XS1_PORT_1I; //Echo - Pin D24
out port outP = XS1_PORT_1O; //Trigger - Pin D25
int echo_time(void){
timer t; //10ns increments
unsigned int start_time,stop_time;
outP <: 0; //make sure is low
delay_milliseconds(50);
//trigger pulse
outP <: 1;
delay_microseconds(10); //datasheet indicate minimum of 2us
outP <: 0;
//wait for echo
inP when pinseq(0x1) :> void; //rising edge of echo - will wait forever
t :> start_time;
inP when pinseq(0x0) :> void; //falling edge of echo - will wait forever
t :> stop_time;
return (stop_time - start_time); //elapsed 10ns timer ticks
}
int main(void){
unsigned int elapsed;
float dist_cm;
while (1)
{
elapsed = echo_time();
dist_cm = (float)elapsed * 0.000170145; //speed of sound 340.29 m/s - divide by 2 for round trip
printf("Distance %0.2f cm, %0.2f in, %0.2f ft\n",dist_cm,dist_cm/2.54,dist_cm/30.48);
delay_milliseconds(250);
}
return 0;
}
Images:
Ultrasonic Distance Module HC-SR04
-
- Member
- Posts: 10
- Joined: Sun Dec 22, 2013 11:09 pm