HC-SR04 模块
电器参数
电器参数
|
HC-SR04超声波模块
|
工作电压
|
DC5V
|
工作电流
|
15mA
|
工作频率
|
40Hz
|
最远射程
|
4m
|
最近射程
|
2cm
|
测量角度
|
15度
|
输入触发信号
|
10us的TTL脉冲
|
输出回响信号
|
输出TTL电平信号,与射程成比例
|
规格尺寸
|
452015mm
|
引脚
VCC、trig(控制端)、echo(接收端)、GND
引脚:
引脚
|
BCM 编码
|
Vcc
|
5V
|
Trig
|
23
|
Echo
|
24
|
Gnd
|
GND
|
红色:5V----Vcc (2或4 引脚)
蓝色:GND----GND (6或9 引脚)
黄色:GPIO14----Echo(接收端 16引脚)
绿色:GPIO15----Trig(控制端 18引脚)
关于 音速. 参考下面(这里以 340米/秒 为例 )
当气温是0℃时,音速是331米/秒;
当气温是5℃时,音速是334米/秒;
当气温是10℃时,音速是337米/秒;
气温是15℃时,音速是340米/秒;
气温是20℃时,音速是343米/秒;
气温是25℃时,音速是346米/秒;
气温是30℃时,音速是349米/秒.
HC-SR04.py
# coding=gbk import RPi.GPIO as GPIO import time # GPIO Mode (BOARD / BCM) GPIO.setmode(GPIO.BCM) # set GPIO Pins and speed GPIO_TRIGGER = 23 GPIO_ECHO = 24 GPIO_SPEED = 340 # set GPIO direction (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def distance(): # set Trigger to HIGH GPIO.output(GPIO_TRIGGER, True) # set Trigger after 0.01ms to LOW time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) StartTime = time.time() StopTime = time.time() # save StartTime while GPIO.input(GPIO_ECHO) == GPIO.LOW: StartTime = time.time() # save time of arrival while GPIO.input(GPIO_ECHO) == GPIO.HIGH: StopTime = time.time() # time difference between start and arrival TimeElapsed = StopTime - StartTime # multiply with the sonic speed (34000 cm/s) # and divide by 2, because there and back distance = (TimeElapsed * GPIO_SPEED * 100) / 2 return distance if __name__ == ‘__main__‘: try: while True: dist = distance() print(" Measured Distance = %.1f cm" % dist) time.sleep(1) # Reset by pressing CTRL + C except KeyboardInterrupt: print(" Measurement stopped by User") GPIO.cleanup()
如果 出现 SyntaxError: Non-UTF-8 code starting with ‘\xb7‘ in file xxx ,在首行 前加入 # coding=gbk
测试结果 如下