我已将土壤湿度传感器模块和 LDR 连接到 ADS1115 ADC(又连接到我的 R Pi)。我正在使用 Python 2.7。ADC 工作正常,它分别打印来自通道 0 和通道 1 的土壤湿度模块和 LDR 的值。我有以下代码可以使用以下指南将数据从土壤湿度模块发送到 Thingspeak:https ://www.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-发布到频道.html
https://github.com/adafruit/Adafruit_Python_ADS1x15
import time
import sys
from time import sleep
import paho.mqtt.publish as publish
import Adafruit_ADS1x15
#GPIO.setmode(GPIO.BOARD)
#Start of user config
channelID= "377509"
apiKey= "<APIKEY>"
#MQTT Connection Methods
useUnsecuredTCP= True
useUnsecuredWebsockets= False
useSSLWebsockets= False
mqttHost= "mqtt.thingspeak.com"
# You can use any Username.
mqttUsername = "SoilHumidityRpiDemo"
# Your MQTT API Key from Account > My Profile.
mqttAPIKey ="<APIKEY>"
if useUnsecuredWebsockets:
tTransport= "websockets"
tPort= 80
#Create topic string
topic= "channels/" + channelID + "/publish/" + apiKey
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
GAIN = 1
print('Reading ADS1x15 values, press Ctrl-C to quit...')
while True:
m = adc.read_adc(0, gain=GAIN)
print('Moisture Level:{0:>6}'.format(m))
time.sleep(1)
tPayload= "field1=%s" % m
try:
publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, transport= tTransport,auth={'username':mqttUsername,'password':mqttAPIKey})
except KeyboardInterrupt:
break
except:
print ("There was an error publishing the data")
当我执行它时,出现错误消息“发布数据时出错”。然而,当我运行一个脚本从终端上的 ADC 打印土壤湿度值时(没有通过 MQTT 将数据发送到 Thingspeak 的代码),该脚本运行良好。
问题是,因为tPort
和tTransport
如果只定义useUnsecuredWebsockets
为True
由于useUnsecuredWebsockets
设置为False
几行之前这将永远不会发生。
您可以更改useUnsecuredWebsockets
为True
或向 if 语句添加 else 子句以设置默认值。
if useUnsecuredWebsockets:
tTransport= "websockets"
tPort= 80
else:
tTransport = "tcp"
tPort= 1883
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句