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

原创首发于CSDN,转载请注明出处,谢谢!
https://blog.csdn.net/weixin_46959681/article/details/115256556



超声波模块

在这里插入图片描述

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 3

void 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; // seconds
	long 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));


参考资料


文章更新记录

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

猜你喜欢

转载自blog.csdn.net/weixin_46959681/article/details/115256556