栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Raspberry pi 4b 读取DHT22数据

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Raspberry pi 4b 读取DHT22数据

Raspberry pi 4b 读取DHT22数据

  1. 确保Raspberry Pi上有最新的更新
sudo apt-get update
  1. 安装python 3-dev和python3-pip使用这两个包来与湿度传感器进行交互
sudo apt-get install python3-dev python3-pip
  1. 安装最新版本的setuptools、wheel和pip python包。
sudo python3 -m pip install --upgrade pip setuptools wheel 
  1. 将DHT库安装到Raspberry Pi上
sudo pip3 install Adafruit_DHT
  1. 制作python脚本读取温度和湿度数据
import Adafruit_DHT
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
        print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(temperature, humidity))

或者

import os
import time
import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

try:
    f = open('/home/pi/humidity.csv', 'a+')
    if os.stat('/home/pi/humidity.csv').st_size == 0:
            f.write('Date,Time,Temperature,Humidityrn')
except:
    pass

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        f.write('{0},{1},{2:0.1f}*C,{3:0.1f}%rn'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M'), temperature, humidity))
    else:
        print("Failed to retrieve data from humidity sensor")

    time.sleep(30)
  1. 运行脚本,测试一下效果
python3 ~/humidity_logger.py
  1. (可选:如果采用第一种方式读取数据请忽略)
cat ~/humidity.csv

参考连接:https://www.labno3.com/2021/03/21/raspberry-pi-humidity-sensor-using-the-dht22/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/331448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号