import RPi.GPIO as GPIO from LCD1602 import LCD_1602 import time BtnPin = 13 R = 4 G = 12 B = 6 TRIG = 17 ECHO = 18 flag = 2 buzzer = 20 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG,GPIO.OUT,initial=GPIO.LOW) GPIO.setup(ECHO,GPIO.IN) GPIO.setup(R,GPIO.OUT) GPIO.setup(B, GPIO.OUT) GPIO.setup(G, GPIO.OUT) GPIO.setup(buzzer, GPIO.OUT) GPIO.setup(BtnPin,GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(buzzer,GPIO.HIGH) m_lcd = LCD_1602(Address=0x27, bus_id=1, bl=1) flag = m_lcd.lcd_init() while True: if GPIO.input(BtnPin) == 0: flag += 1 elif GPIO.input(BtnPin) == 1: pass if flag % 2 == 0: for i in range(10): GPIO.output(G,GPIO.LOW) GPIO.output(B,GPIO.LOW) GPIO.output(buzzer,GPIO.HIGH) GPIO.output(TRIG,GPIO.HIGH) time.sleep(0.000015) GPIO.output(TRIG,GPIO.LOW) while not GPIO.input(ECHO): pass t1 = time.time() while GPIO.input(ECHO): pass t2 = time.time() distance = round((t2-t1) * 340 / 2,5) if distance < 0.2: GPIO.output(B,GPIO.HIGH) GPIO.output(buzzer,GPIO.LOW) print("当前的距离为:",distance) a = '%f'%distance m_lcd.lcd_display_string(0, 0, 'The distance is') m_lcd.lcd_display_string(0, 1, a) m_lcd.lcd_display_string(8, 1, 'm') time.sleep(1) elif flag % 2 == 1: GPIO.output(G,GPIO.HIGH) GPIO.cleanup() ,我需要把灯和蜂鸣器还有其他的代码都用函数封装起来
时间: 2023-07-16 08:15:10 浏览: 101
import RPIO.GPIO as GPIO.py
好的,你可以尝试以下的代码:
```python
import RPi.GPIO as GPIO
from LCD1602 import LCD_1602
import time
BtnPin = 13
R = 4
G = 12
B = 6
TRIG = 17
ECHO = 18
buzzer = 20
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(R, GPIO.OUT)
GPIO.setup(B, GPIO.OUT)
GPIO.setup(G, GPIO.OUT)
GPIO.setup(buzzer, GPIO.OUT)
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(buzzer, GPIO.HIGH)
m_lcd = LCD_1602(Address=0x27, bus_id=1, bl=1)
flag = m_lcd.lcd_init()
def get_distance():
GPIO.output(TRIG, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(TRIG, GPIO.LOW)
while not GPIO.input(ECHO):
pass
t1 = time.time()
while GPIO.input(ECHO):
pass
t2 = time.time()
distance = round((t2-t1) * 340 / 2, 5)
return distance
def display_distance(distance):
a = '%f'%distance
m_lcd.lcd_display_string(0, 0, 'The distance is')
m_lcd.lcd_display_string(0, 1, a)
m_lcd.lcd_display_string(8, 1, 'm')
def turn_on_red():
GPIO.output(R, GPIO.HIGH)
def turn_on_green():
GPIO.output(G, GPIO.HIGH)
def turn_on_blue():
GPIO.output(B, GPIO.HIGH)
def turn_off_leds():
GPIO.output(R, GPIO.LOW)
GPIO.output(G, GPIO.LOW)
GPIO.output(B, GPIO.LOW)
def turn_on_buzzer():
GPIO.output(buzzer, GPIO.LOW)
def turn_off_buzzer():
GPIO.output(buzzer, GPIO.HIGH)
def main():
while True:
if GPIO.input(BtnPin) == 0:
flag += 1
elif GPIO.input(BtnPin) == 1:
pass
if flag % 2 == 0:
turn_off_leds()
turn_on_buzzer()
distance = get_distance()
if distance < 0.2:
turn_on_blue()
turn_off_buzzer()
display_distance(distance)
time.sleep(1)
elif flag % 2 == 1:
turn_on_green()
if __name__ == '__main__':
main()
GPIO.cleanup()
```
这个代码将灯和蜂鸣器的控制代码都封装成了函数,使代码更加模块化。
阅读全文