在树莓派中运用四位按键、红黄绿LED灯、光照小球和DHT11温湿度感应器写出一个程序
时间: 2024-12-17 08:17:08 浏览: 12
在树莓派(Raspberry Pi)上,要编写一个程序控制四位按键(Knobs),红黄绿LED灯(LEDs),光照传感器(Light Sensor)以及DHT11温湿度感应器,你可以使用Python语言配合GPIO模块。以下是基本的步骤和代码框架:
首先,安装必要的库:
```bash
pip install RPi.GPIO adafruit-circuitpython-dht pigpio gpiozero
```
然后,创建一个Python文件,比如`raspberry_pi_control.py`,并导入所需的库:
```python
import RPi.GPIO as GPIO
from gpiozero import Button, LED, DistanceSensor
import Adafruit_DHT
import time
```
定义GPIO配置,包括按键和LED:
```python
led_red = LED(17) # 红色LED
led_yellow = LED(18) # 黄色LED
led_green = LED(27) # 绿色LED
button1 = Button(4)
button2 = Button(17)
button3 = Button(27)
button4 = Button(22)
# DHT11 GPIO配置
dht11_pin = 4
```
设置按钮事件监听和LED状态更新:
```python
def button_event(pin):
if pin == button1:
print("Button 1 pressed")
led_red.on()
elif pin == button2:
print("Button 2 pressed")
led_yellow.on()
elif pin == button3:
print("Button 3 pressed")
led_green.on()
else:
print("Button 4 pressed")
led_red.off()
led_yellow.off()
led_green.off()
GPIO.setup(button1.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(button2.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(button3.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(button4.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(button1.pin, GPIO.FALLING, callback=button_event)
GPIO.add_event_detect(button2.pin, GPIO.FALLING, callback=button_event)
GPIO.add_event_detect(button3.pin, GPIO.FALLING, callback=button_event)
GPIO.add_event_detect(button4.pin, GPIO.FALLING, callback=button_event)
```
读取DHT11数据并打印温度和湿度:
```python
def read_dht11():
humidity, temperature = Adafruit_DHT.read_retry(DHT11, dht11_pin)
if humidity is not None and temperature is not None:
print(f"Temperature: {temperature}°C, Humidity: {humidity}%")
else:
print("Failed to read from DHT11 sensor.")
while True:
read_dht11()
time.sleep(5) # 每隔5秒读一次DHT11
```
记得在程序结束前关闭GPIO资源:
```python
def cleanup():
GPIO.cleanup()
try:
# 主程序运行部分
except KeyboardInterrupt:
cleanup()
```
将上述代码粘贴到`raspberry_pi_control.py`中,并在树莓派上运行。这个程序会监听四个按键,当按键按下时相应的LED亮起;同时定期读取并打印DHT11的温湿度数据。
阅读全文