失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 树莓派项目实践 [2] —— 编程控制实现超声波测距(C语言)

树莓派项目实践 [2] —— 编程控制实现超声波测距(C语言)

时间:2021-06-15 00:57:14

相关推荐

树莓派项目实践 [2] —— 编程控制实现超声波测距(C语言)

原创首发于CSDN,转载请注明出处,谢谢!/weixin_46959681/article/details/115256556

文章目录

超声波模块树莓派与超声波模块相连超声波测距原理通过树莓派引脚编程操作超声波模块|测距源代码: `chaoShengBo.c`|运行拓展:面向时间的编程参考资料文章更新记录

超声波模块

Q:为什么能发出超声波呢?

树莓派与超声波模块相连

VCC — 5V,Trig — GPIO.2,Echo — GPIO.3。(读者请自行对应树莓派引脚图。)

超声波测距原理

在给出的原理图中可以明确的看到,给设置为输出的触发端一个低电平,紧接着再给一个持续时间10微秒的高电平,就成功地让元器件内部发波了。具体的代码编写在源代码中也有体现。

通过树莓派引脚编程操作超声波模块

|测距源代码:chaoShengBo.c

/* chaoShengBo.c */#include <stdio.h>#include <sys/time.h>#include <wiringPi.h>#define Trig 2 #define Echo 3void chaoShengBoInit(){//超声波接收端设为输入端。pinMode(Echo,INPUT); //超声波触发端设为输出端。pinMode(Trig,OUTPUT);}float disMeasure(){struct timeval tv1;struct timeval tv2;long start;long stop;float dis;//超声波触发端拉高拉低过程。digitalWrite(Trig,LOW);delayMicroseconds(4);digitalWrite(Trig,HIGH);//触发端发出10微秒的超声波脉冲。delayMicroseconds(10);digitalWrite(Trig,LOW);//获取当前时间,开始接收到返回信号的时间点。while(!(digitalRead(Echo) == 1));gettimeofday(&tv1,NULL);//获取当前时间,最后接收到返回信号的时间点。while(!(digitalRead(Echo) == 0));gettimeofday(&tv2,NULL);start = tv1.tv_sec * 1000000 + tv1.tv_usec;stop = tv2.tv_sec * 1000000 + tv2.tv_usec;dis = (float)(stop - start) / 1000000 * 34000 / 2;return dis;}int main(){float dis;if(wiringPiSetup() == -1){printf("Setup wiringPi failed.\n");return -1;}chaoShengBoInit();while(1){dis = disMeasure();printf("distance = %0.2f cm\n",dis);delay(1000);}return 0;}

|运行

终端运行指令gcc chaoShengBo.c -lwiringPi,运行./a.out可以看到超声波模块被激活开始测距,界面终端也返回测量的实测数据。

拓展:面向时间的编程

在 Linux 系统中,struct timeval结构体函数在头文件time.h中的定义为:

//最高精度为微秒。struct timeval {time_t tv_sec; // secondslong tv_usec; // microseconds};

一般由函数int gettimeofday(struct timeval *tv, struct timezone *tz)获取系统的时间,gettimeofday()功能是得到当前时间时区,分别写到 tv 和 tz 中。后者写入 NULL 则表示为空。

函数原型:

/* Get the current time of day and timezone information,putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled.Returns 0 on success, -1 on errors.NOTE: This form of timezone information is obsolete.Use the functions and variables declared in <time.h> instead. */extern int gettimeofday (struct timeval *__restrict __tv,__timezone_ptr_t __tz) __THROW __nonnull ((1));

参考资料

struct timeval结构体struct timespec 和 struct timevalstruct timeval结构体 以及 gettimeofday()函数、struct timespec结构体

文章更新记录

“树莓派与超声波模块连接展示”一节完成。「.3.27 21:46」“拓展:面向时间的编程”一节完成。 「.3.28 16:49」

如果觉得《树莓派项目实践 [2] —— 编程控制实现超声波测距(C语言)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。