您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python怎么实现温度传感器
## 引言
在物联网(IoT)和智能家居快速发展的今天,温度传感器作为最基础的环境监测设备之一,被广泛应用于各种场景。Python凭借其简洁的语法和丰富的库生态,成为与硬件交互的理想选择。本文将详细介绍如何用Python实现温度传感器数据采集,涵盖从硬件选型到软件实现的完整流程。
---
## 一、温度传感器硬件选型
### 1.1 常见温度传感器类型
| 传感器型号 | 接口类型 | 精度范围 | 适用场景 |
|------------|----------|----------|----------|
| DS18B20 | 1-Wire | ±0.5℃ | 防水探头 |
| DHT11 | 数字信号 | ±2℃ | 低成本方案 |
| LM35 | 模拟信号 | ±0.5℃ | 工业环境 |
| BME280 | I2C/SPI | ±1℃ | 气象站 |
### 1.2 推荐选择DS18B20的原因
- 独特的1-Wire总线可并联多个设备
- 防水封装适合潮湿环境
- 测量范围-55℃~+125℃
- 直接输出数字信号避免ADC转换
---
## 二、硬件连接与配置
### 2.1 所需材料清单
- Raspberry Pi 4B(任何Linux SBC均可)
- DS18B20温度传感器
- 4.7kΩ电阻(上拉电阻)
- 面包板和跳线
### 2.2 电路连接示意图
```python
DS18B20引脚说明:
1. GND(黑线) → Pi的GND
2. VDD(红线) → Pi的3.3V
3. DQ(黄线) → Pi的GPIO4
└── 并联4.7kΩ电阻到VDD
启用1-Wire接口:
sudo raspi-config
# 选择Interface Options → 1-Wire → 启用
# 或手动添加到/boot/config.txt:
dtoverlay=w1-gpio,gpiopin=4
import os
import glob
import time
class DS18B20:
def __init__(self):
self.device_folder = glob.glob('/sys/bus/w1/devices/28*')[0]
self.device_file = f"{self.device_folder}/w1_slave"
def read_temp(self):
while True:
with open(self.device_file, 'r') as f:
lines = f.readlines()
if lines[0].strip()[-3:] == 'YES':
temp_pos = lines[1].find('t=')
if temp_pos != -1:
temp = float(lines[1][temp_pos+2:])/1000.0
return temp
time.sleep(0.2)
if __name__ == '__main__':
sensor = DS18B20()
print(f"当前温度: {sensor.read_temp():.2f}℃")
def detect_sensors():
return glob.glob('/sys/bus/w1/devices/28*')
def read_all_sensors():
sensors = {}
for dev in detect_sensors():
serial = dev.split('/')[-1]
with open(f"{dev}/w1_slave", 'r') as f:
data = f.read()
temp = float(data.split('t=')[1])/1000
sensors[serial] = temp
return sensors
使用Matplotlib实时绘图:
import matplotlib.pyplot as plt
from collections import deque
history = deque(maxlen=100)
def live_plot():
plt.ion()
fig, ax = plt.subplots()
line, = ax.plot([], [])
ax.set_ylim(0, 50)
while True:
history.append(sensor.read_temp())
line.set_xdata(range(len(history)))
line.set_ydata(history)
ax.relim()
ax.autoscale_view()
fig.canvas.draw()
plt.pause(1.0)
import sqlite3
from datetime import datetime
def init_db():
conn = sqlite3.connect('temps.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS temperatures
(timestamp DATETIME, sensor_id TEXT, temp REAL)''')
conn.commit()
return conn
def log_temp(conn, temp):
c = conn.cursor()
c.execute("INSERT INTO temperatures VALUES (?, ?, ?)",
(datetime.now(), "28-0316a1e0d3ff", temp))
conn.commit()
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.connect("iot.eclipse.org", 1883, 60)
while True:
temp = sensor.read_temp()
client.publish("home/sensor/temperature",
payload=f'{{"temp":{temp},"unit":"C"}}')
time.sleep(300) # 每5分钟上报
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
fan_pin = 17
GPIO.setup(fan_pin, GPIO.OUT)
def control_fan(temp):
if temp > 28:
GPIO.output(fan_pin, True)
elif temp < 25:
GPIO.output(fan_pin, False)
import smtplib
from email.mime.text import MIMEText
def send_alert(temp):
msg = MIMEText(f"温度异常!当前温度:{temp}℃")
msg['Subject'] = '高温警报'
msg['From'] = 'sensor@home.com'
msg['To'] = 'admin@home.com'
with smtplib.SMTP('smtp.server.com') as s:
s.login('user', 'pass')
s.send_message(msg)
sudo modprobe w1-therm strong_pullup=1
dmesg | grep w1
输出
sudo modprobe -r w1_therm && sudo modprobe w1_therm
本文详细介绍了Python在温度传感器应用中的完整实现方案。通过这个基础项目,可以进一步扩展: - 结合其他传感器构建环境监测站 - 开发Flask/Django web控制界面 - 实现机器学习预测温度变化趋势
Python在物联网领域的优势在于其快速原型开发能力,配合树莓派等硬件平台,能让想法快速转化为实际应用。
资源推荐: - w1thermsensor库 - RPi.GPIO文档 - MQTT协议规范 “`
注:实际文章需要根据具体硬件型号和Python版本进行调整,以上代码在Raspberry Pi 4B + Python 3.7环境下测试通过。建议在正式项目中使用gpiod
替代已弃用的RPi.GPIO库。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。