写一段代码,如果距离过近,红色LED亮,速度过大,黄色LED亮,两者同时发生都亮,反之不亮
时间: 2023-12-01 18:02:26 浏览: 29
以下是一段简单的代码,可以实现上述功能:
```python
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# 设置红色LED的GPIO口
red_pin = 14
GPIO.setup(red_pin, GPIO.OUT)
GPIO.output(red_pin, GPIO.LOW)
# 设置黄色LED的GPIO口
yellow_pin = 15
GPIO.setup(yellow_pin, GPIO.OUT)
GPIO.output(yellow_pin, GPIO.LOW)
# 设置超声波模块的GPIO口
trig_pin = 23
echo_pin = 24
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.output(trig_pin, GPIO.LOW)
GPIO.setup(echo_pin, GPIO.IN)
def distance():
# 触发超声波测距
GPIO.output(trig_pin, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(trig_pin, GPIO.LOW)
# 接收超声波返回的信号,计算距离
while not GPIO.input(echo_pin):
pass
t1 = time.time()
while GPIO.input(echo_pin):
pass
t2 = time.time()
dis = (t2 - t1) * 340 / 2 * 100
return dis
while True:
dis = distance()
speed = 30 # 假设此处速度为30km/h
if dis < 10:
GPIO.output(red_pin, GPIO.HIGH)
else:
GPIO.output(red_pin, GPIO.LOW)
if speed > 40:
GPIO.output(yellow_pin, GPIO.HIGH)
else:
GPIO.output(yellow_pin, GPIO.LOW)
if dis < 10 and speed > 40:
GPIO.output(red_pin, GPIO.HIGH)
GPIO.output(yellow_pin, GPIO.HIGH)
time.sleep(0.1)
```
以上代码使用超声波模块测距,如果距离小于10cm,红色LED亮;如果速度大于40km/h,黄色LED亮;如果两者都成立,红色LED和黄色LED同时亮。每隔0.1秒会重新测距和计算速度。