我已经将土壤湿度传感器模块和LDR连接到ADS1115模数转换器(该模数转换器又连接到我的R Pi)。我使用的是Python 2.7。ADC工作正常,它分别为土壤湿度模块和LDR打印通道0和通道1的值。我有以下代码,可以使用以下指南将数据从土壤湿度模块发送到Thingspeak:https://www.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-to-publish-to-a-channel.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发送数据的代码),这个脚本工作得很好。
发布于 2018-01-17 17:24:00
问题是因为只有在useUnsecuredWebsockets为True时才定义tPort和tTransport
因为在之前的几行中useUnsecuredWebsockets被设置为False,所以这种情况永远不会发生。
您可以将useUnsecuredWebsockets更改为True,也可以在if语句中添加else子句来设置默认值。
if useUnsecuredWebsockets:
tTransport= "websockets"
tPort= 80
else:
tTransport = "tcp"
tPort= 1883https://stackoverflow.com/questions/48291217
复制相似问题