我使用的传感器是HC-SR04。 我用它来把显示器调到睡眠模式,当它感觉到物体超过30厘米时。 当感测物体小于或等于30厘米时,它就会打开。 它在进入睡眠模式时工作良好,但当它变成闪烁时开,拜托帮帮我~~~ 下面是我的代码
import time
import RPi.GPIO as GPIO
import os
import subprocess
import sys
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO = 24
print "Ultrasonic Measurement"
while True:
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# Allow module to settle
time.sleep(2)
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000
# That was the distance there and back so halve the value
distance = distance / 2
print "Distance : %.1f" % distance
if(distance > 30):
time.sleep(3)
subprocess.call("sudo /opt/vc/bin/tvservice -o",shell=True)
os.system('clear')
if(distance <= 30):
subprocess.call("sudo /opt/vc/bin/tvservice -p",shell=True)
# Reset GPIO settings
GPIO.cleanup()
你的测量有误差或噪音导致它波动。这可能部分是由于尝试使用Python GPIO模块来测量它,这可能有点慢。有两种方法可以尝试:
在触发点添加一些hysteresis
给你的阅读添加一些过滤。你可以使用一个moving average过滤器
^{2美元或者,用微控制器更精确地测量时间可能会有所帮助。在
你可能还应该跟踪屏幕是否已经打开或关闭,只在需要时进行切换
相关问题 更多 >
编程相关推荐