树莓派温湿度发布到百度云MQTT

xiaoxiao2021-02-28  57

树莓派温湿度发布到百度云MQTT:

继上一篇文章( 树莓派与DHT-11温湿度传感器):修改Collect.py(collect函数返回温湿度信息) 如下: Collect.py:

import RPi.GPIO as GPIO import time def collect(): THdata = [] channel = 4 data = [] GPIO.setmode(GPIO.BCM) time.sleep(2) GPIO.setup(channel, GPIO.OUT) GPIO.output(channel, GPIO.LOW) time.sleep(0.02) GPIO.output(channel, GPIO.HIGH) GPIO.setup(channel, GPIO.IN) while GPIO.input(channel) == GPIO.LOW: continue while GPIO.input(channel) == GPIO.HIGH: continue j = 0 while j < 40: k = 0 while GPIO.input(channel) == GPIO.LOW: continue while GPIO.input(channel) == GPIO.HIGH: k += 1 if k > 100: break if k < 8: data.append(0) else: data.append(1) j += 1 # print("sensor is working.") # print(data) humidity_bit = data[0:8] humidity_point_bit = data[8:16] temperature_bit = data[16:24] temperature_point_bit = data[24:32] check_bit = data[32:40] humidity = 0 humidity_point = 0 temperature = 0 temperature_point = 0 check = 0 for i in range(8): humidity += humidity_bit[i] * 2 ** (7 - i) humidity_point += humidity_point_bit[i] * 2 ** (7 - i) temperature += temperature_bit[i] * 2 ** (7 - i) temperature_point += temperature_point_bit[i] * 2 ** (7 - i) check += check_bit[i] * 2 ** (7 - i) tmp = humidity + humidity_point + temperature + temperature_point if check == tmp: print("temperature :", temperature, "*C", " humidity :", humidity, "%") THdata.append(temperature) THdata.append(humidity) return THdata else: # print("wrong") time.sleep(1) return collect()

Publish.py:(change,topic为修改的部分,改成你自己的百度云MQTT实例即可)

import paho.mqtt.client as mqtt import sys import uuid import Collect import time broker = change0' port = 1883 username = 'change1'# 修改 password = 'change2'# 修改 clientid = 'temperature_publish' + str(uuid.uuid4()) topic = 'temperature'# 修改 def on_connect(client, userdata, rc): print('Connected. Client id is: ' + clientid) def on_message(client, userdata, msg): msg = str(msg.payload, 'utf-8') print('MQTT message received: ' + msg) if msg == 'exit': sys.exit() client = mqtt.Client(clientid) # client.will_set('temperature', 'last will', 0, False) client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username, password) print('Connecting to broker: ' + broker) client.connect(broker, port) client.loop_start() time.sleep(3) # client.loop_forever() while True: rTHdata = test1.Collect.collect() client.publish(topic, "temperture :" + str(rTHdata[0]) + " *C " + "humidity :" + str(rTHdata[1]) + " %") #设置发布间隔时间 time.sleep(3)
转载请注明原文地址: https://www.6miu.com/read-78500.html

最新回复(0)