连接5V和GND,超声波模块的Trig和Echo引脚可以连接至树莓派的任意GPIO引脚,连线方式和我们的不一样也没关系,记住Trig和Echo引脚对应的BCM引脚编码
C语言版
#include <wiringPi.h>
#include <stdio.h>
#include <sys/time.h>
#define Trig 3
#define Echo 4
void ultraInit(void)
{
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
}
float disMeasure(void)
{
struct timeval tv1;
struct timeval tv2;
long start, stop;
float dis;
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
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(void)
{
float dis;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
ultraInit();
while(1){
dis = disMeasure();
printf("distance = %0.2f cm\n",dis);
delay(1000);
}
return 0;
}
编译命令:
gcc -Wall -o disMeasure chao.c -lwiringPi
Python版
#coding=utf-8
#导入 GPIO库
import RPi.GPIO as GPIO
import time
#设置 GPIO 模式为 BCM
GPIO.setmode(GPIO.BCM)
#定义 GPIO 引脚
GPIO_TRIGGER = 23
GPIO_ECHO = 22
#设置 GPIO 的工作方式 (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
# 发送高电平信号到 Trig 引脚
GPIO.output(GPIO_TRIGGER, True)
# 持续 10 us
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start_time = time.time()
stop_time = time.time()
# 记录发送超声波的时刻1
while GPIO.input(GPIO_ECHO) == 0:
start_time = time.time()
# 记录接收到返回超声波的时刻2
while GPIO.input(GPIO_ECHO) == 1:
stop_time = time.time()
# 计算超声波的往返时间 = 时刻2 - 时刻1
time_elapsed = stop_time - start_time
# 声波的速度为 343m/s, 转化为 34300cm/s。
distance = (time_elapsed * 34300) / 2
return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print("Measured Distance = {:.2f} cm".format(dist))
time.sleep(1)
# Reset by pressing CTRL + C
except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()