写出树莓派温湿度蜂鸣器和烟雾报警代码
时间: 2024-05-13 20:16:24 浏览: 179
树莓派温湿度蜂鸣器代码:
```python
import Adafruit_DHT
import RPi.GPIO as GPIO
import time
# 设置 DHT11 传感器的引脚
DHT11_pin = 4
# 设置蜂鸣器的引脚
buzzer_pin = 17
# 初始化蜂鸣器引脚
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer_pin, GPIO.OUT)
# 循环读取温湿度数据并控制蜂鸣器
while True:
# 读取温湿度数据
humidity, temperature = Adafruit_DHT.read_retry(11, DHT11_pin)
# 如果读取成功
if humidity is not None and temperature is not None:
# 打印温湿度数据
print('Temperature: {0:0.1f}C, Humidity: {1:0.1f}%'.format(temperature, humidity))
# 如果温度超过 25C 或者湿度超过 60%
if temperature > 25 or humidity > 60:
# 控制蜂鸣器响起
GPIO.output(buzzer_pin, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(buzzer_pin, GPIO.LOW)
time.sleep(0.5)
else:
# 如果读取失败,打印错误信息
print('Failed to read DHT11 sensor data')
```
树莓派烟雾报警代码:
```python
import RPi.GPIO as GPIO
import time
# 设置烟雾传感器的引脚
smoke_sensor_pin = 18
# 设置蜂鸣器的引脚
buzzer_pin = 17
# 初始化烟雾传感器引脚
GPIO.setmode(GPIO.BCM)
GPIO.setup(smoke_sensor_pin, GPIO.IN)
# 初始化蜂鸣器引脚
GPIO.setup(buzzer_pin, GPIO.OUT)
# 循环检测烟雾传感器状态并控制蜂鸣器
while True:
# 读取烟雾传感器状态
smoke_sensor_state = GPIO.input(smoke_sensor_pin)
# 如果检测到烟雾
if smoke_sensor_state == GPIO.HIGH:
# 控制蜂鸣器响起
GPIO.output(buzzer_pin, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(buzzer_pin, GPIO.LOW)
time.sleep(0.5)
else:
# 如果没有检测到烟雾,关闭蜂鸣器
GPIO.output(buzzer_pin, GPIO.LOW)
```
阅读全文