0
votes

I have connected a soil moisture sensor module and an LDR to an ADS1115 ADC (which is in turn connected to my R Pi). Am using Python 2.7. The ADC works fine and it prints values from channel 0 and channel 1 for the soil moisture module and the LDR respectively. I have the following codes to send data from the soil moisture module to Thingspeak using the following guides: 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")

When I execute it, the error message "There was an error publishing the data" shows up. However when I just run a script to print the soil moisture values from the ADC on the terminal(without the codes to send data to Thingspeak via MQTT), that script works well.

1
Please change your except clause to except Exception as e: print(e) so you can learn more about what goes wrong.nos
Thanks. I did as you said. I am getting this error: name 'tPort' is not definedTia

1 Answers

1
votes

The problem is because tPort and tTransport are only defined if useUnsecuredWebsockets is True

Since useUnsecuredWebsockets is set to False a few lines before this will never happen.

You can either change useUnsecuredWebsockets to True or add a else clause to the if statement to set the default values.

if useUnsecuredWebsockets:
 tTransport= "websockets"
 tPort= 80
else:
 tTransport = "tcp"
 tPort= 1883