超声波距离模块HC-SR04
状态:beta
下载: 0
许可证:
最后更新:12个/ 1月/ 2014 05:26点
Wiki条目:
项目概述
超声波距离模块HC-SR04是避障和测距的爱好者的欢迎。 Arduino是常用的。 我已经使用它与Arduino和RaspberryPi。
我最近收到了startKIT和正在寻找一个快速学习项目为intefacing传感器。 所以,焊头针后,我联系了HC-SR04。 下面的示例代码运行好xTIMEcomposerStudio.
/* 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;
}