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 07:15:02 浏览: 116
Sure, here's the code wrapped in a function:
```python
import RPi.GPIO as GPIO
from LCD1602 import LCD_1602
import time
def run_distance_sensor():
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()
```
You can call the `run_distance_sensor()` function to start running the distance sensor code.
阅读全文