因为作业要求使用c语言代码,这里先附上一段摘自网上的代码
感谢KalaerSun的c语言代码,摘自https://blog.csdn.net/qq_25247589/article/details/62892140
1 #include
2 #include
3 #include
4 #define Trig 4
5 #define Echo 5
6
7 void ultraInit(void)8 {9 pinMode(Echo, INPUT); //设置端口为输入
10 pinMode(Trig, OUTPUT); //设置端口为输出
11 }12
13 float disMeasure(void)14 {15 struct timeval tv1; //timeval是time.h中的预定义结构体 其中包含两个一个是秒,一个是微秒
16 /*
17 struct timeval18 {19 time_t tv_sec; //Seconds.20 suseconds_t tv_usec; //Microseconds.21 };22 */
23
24 structtimeval tv2;25 longstart, stop;26 floatdis;27
28 digitalWrite(Trig, LOW);29 delayMicroseconds(2);30
31 digitalWrite(Trig, HIGH);32 delayMicroseconds(10); //发出超声波脉冲
33 digitalWrite(Trig, LOW);34
35 while(!(digitalRead(Echo) == 1));36 gettimeofday(&tv1, NULL); //获取当前时间 开始接收到返回信号的时候
37
38 while(!(digitalRead(Echo) == 0));39 gettimeofday(&tv2, NULL); //获取当前时间 最后接收到返回信号的时候
40 /*
41 int gettimeofday(struct timeval *tv, struct timezone *tz);42 The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone.43 The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.44 */
45 start = tv1.tv_sec * 1000000 + tv1.tv_usec; //微秒级的时间
46 stop = tv2.tv_sec * 1000000 +tv2.tv_usec;47
48 dis = (float)(stop - start) / 1000000 * 34000 / 2; //计算时间差求出距离
49
50 returndis;51 }52
53 int main(void)54 {55 floatdis;56
57 if(wiri