实现基于树莓派5的温度控制系统,使用AHT10传感器检测环境温度,并通过控制直流小电机和PTC加热块来维持设定温度,按照以下步骤进行设计和实现。
1. 硬件连接
树莓派5。
AHT10温湿度传感器模块。
直流小电机,5V工作电压。
PTC加热块,5V工作电压。
三极管PNP型,用来控制电机和加热块。
AHT10传感器连接:
VCC → 树莓派5V引脚。
GND → 树莓派GND引脚。
SCL → 树莓派GPIO3(I²C时钟线)。
SDA → 树莓派GPIO2(I²C数据线)。
直流小电机连接:
电机正极 → 树莓派5V引脚。
电机负极 → 三极管集电极(C)。
三极管发射极(E)→ 树莓派GND引脚。
三极管基极(B)→ 树莓派GPIO17,通过电阻连接。
PTC加热块连接:
PTC加热块正极 → 树莓派5V引脚。
PTC加热块负极 → 三极管集电极(C)。
三极管发射极(E)→ 树莓派GND引脚。
三极管基极(B)→ 树莓派GPIO27,通过电阻220Ω连接。
2、连接示意图

3、参考代码
import smbus2
import time
import RPi.GPIO as GPIO
# 初始化GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# 定义引脚
MOTOR_PIN = 17
HEATER_PIN = 27
# 设置GPIO为输出
GPIO.setup(MOTOR_PIN, GPIO.OUT)
GPIO.setup(HEATER_PIN, GPIO.OUT)
# 初始化AHT10传感器
class AHT10:
def __init__(self, bus=1, address=0x38):
self.bus = smbus2.SMBus(bus)
self.address = address
self.initialize()
def initialize(self):
config_bytes = [0xE1, 0x08, 0x00]
self.bus.write_i2c_block_data(self.address, 0, config_bytes)
time.sleep(0.1)
def read_data(self):
measure_bytes = [0xAC, 0x33, 0x00]
self.bus.write_i2c_block_data(self.address, 0, measure_bytes)
time.sleep(0.08)
data = self.bus.read_i2c_block_data(self.address, 0, 6)
if not (data[0] & 0x80):
humidity_raw = ((data[1] << 12) | (data[2] << 4) | (data[3] >> 4))
humidity = (humidity_raw / 1048576) * 100
temperature_raw = (((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5])
temperature = (temperature_raw / 1048576) * 200 - 50
return {"temperature": round(temperature, 2), "humidity": round(humidity, 2)}
else:
return None
# 温度控制逻辑
def temperature_control(target_temp):
aht10 = AHT10()
while True:
data = aht10.read_data()
if data:
current_temp = data['temperature']
print(f"Current Temperature: {current_temp}°C")
if current_temp < target_temp - 1: # 如果温度低于设定值-1,开启加热
GPIO.output(HEATER_PIN, GPIO.HIGH)
GPIO.output(MOTOR_PIN, GPIO.LOW)
print("Heating...")
elif current_temp > target_temp + 1: # 如果温度高于设定值+1,开启电机散热
GPIO.output(HEATER_PIN, GPIO.LOW)
GPIO.output(MOTOR_PIN, GPIO.HIGH)
print("Cooling...")
else: # 温度在设定范围内,关闭所有设备
GPIO.output(HEATER_PIN, GPIO.LOW)
GPIO.output(MOTOR_PIN, GPIO.LOW)
print("Temperature stable.")
time.sleep(2) # 每2秒检测一次
if __name__ == "__main__":
try:
target_temperature = 25.0 # 设定目标温度
temperature_control(target_temperature)
except KeyboardInterrupt:
GPIO.cleanup()
print("Program terminated.")4、实物照片
全部连接工作图:


加温工作图:

温度到了后,电机工作图:

5、运行效果视频
我要赚赏金
