- 确保Raspberry Pi上有最新的更新
sudo apt-get update
- 安装python 3-dev和python3-pip使用这两个包来与湿度传感器进行交互
sudo apt-get install python3-dev python3-pip
- 安装最新版本的setuptools、wheel和pip python包。
sudo python3 -m pip install --upgrade pip setuptools wheel
- 将DHT库安装到Raspberry Pi上
sudo pip3 install Adafruit_DHT
- 下载库
pip install paho-mqtt
基于MQTT协议在树莓派上利用DHT22温湿度传感器测量温湿度,并且持续发布主题为:temphum,内容为温湿度的消息。
发布端程序(文件名.py):
import paho.mqtt.publish as publish
import Adafruit_DHT
import time
sensor = Adafruit_DHT.DHT22
pin = 27
while True:
hu,temp =Adafruit_DHT.read_retry(sensor,pin) //测量
humtemp = 'temp:{0:0.1f}*C hu:{1}%'.format(temp,hu)
publish.single("temphum",payload=humtemp,qos=0,
hostname="***.***.***.***") //edge节点ip或者localhost
time.sleep(2)
订阅端程序(文件名.py):
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import RPi.GPIO as GPIO
import json
import time
def on_connect(client,userdata,flags,rc):
print("Connected with result code " + str(rc))
def on_message(client,userdata,msg):
print(msg.topic+" "+str(msg.payload))
def on_subscribe(client,userdata,mid,granted_qos):
print("Subscribed: " + str(mid) + str(granted_qos))
if __name__=='__main__':
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.connect("***.***.***.***",1883,60) //edge节点ip或者localhost
client.subscribe("temphum",0)
client.loop_forever()
服务器使用:mosquitto
程序全部在树莓派上运行
- 先运行订阅端脚本
python3 name.py
- 运行发布端脚本
python3 name.py
注意事项: 确保raspberrypi作为edge节点,并处于ready状态。
|