HC-SR04与python不兼容RPi2

时间:2016-03-06 12:58:03

标签: python raspberry-pi

我正在尝试使用python在我的RPi 2 Model B上运行HC-SR04模块,尽管我没有成功。接线似乎很好,编码也是如此,但要么脉冲永远不发送也不接收,任何人都可以帮忙吗?

import RPi.GPIO as GPIO
import time

#GPIO Operandi (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

# Set the GPIO pins
TRIG = 35
ECHO = 37 
# Define the direction in which the pins are working 
# If they send a signal OUT or recieve a signal IN
# ultrasonic sensor pins for TRIG and ECHO
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
#Allowing sensor to settle
GPIO.output(TRIG, False)
time.sleep(2)
# TRIG HIGH
GPIO.output(TRIG, True)
# TRIG LOW after 0.01ms
time.sleep(0.00001)
GPIO.output(TRIG, False)
# Define start time
while GPIO.input(ECHO) == 0:
        StartTime = time.time()
# Define end time
while GPIO.input(ECHO) == 1:
        StopTime = time.time()
# Calculate the difference between the StartTime and the StopTime
TimeElapsed = StopTime - StartTime
# Multiply by speed of sound
# Divide by  2 for one direction
distance = (TimeElapsed * 34300) / 2
print(distance)`

1 个答案:

答案 0 :(得分:0)

首先,操作数需要为BOARD,其次需要将ECHO连接到GND