Controlling an LED with the Pi 4 using ThingSpeak MQTT subscribe.

205 views
Skip to first unread message

Tejaswini Suriyanarayanan

unread,
Feb 22, 2021, 8:58:58 AM2/22/21
to MQTT
Hello,
I was working on a project to contol an LED connected to the Pi 4 using the subscribe feature in ThingSpeak MQTT. While I was able to publish data to ThingSpeak MQTT using the Pi 4 without any issues, I faced trouble while trying to subscribe to a channel in ThingSpeak MQTT to read data from a field to control an LED connected to the Pi.
Initially, I had interfaced both the LED and a BMP180 sensor to the same Pi and wanted to publish data from the BMP180 to a ThingSpeak channel and subscribe to the channel to control my LED based on the temperature values (I ran seperate scripts on the Pi 4 for the Publish and subscribe simuntaneously). Though the publish part worked, the subscribe part did not. I thought this was because I was using the same device (the Pi) to publish and subscribe to the channel.
So later, I installed the MQTT.fx app in my PC and used it to publish values to a new private ThingSpeak channel. I then used the Pi to subscribe to the same channel, receive values and control the LED that was interfaced to it. This did not work either. I am unable to receive messages from the ThingSpeak MQTT channel when I subscribe to it from the Pi 4.
I double checked the Channel ID and API keys were correct. I'm using the Paho MQTT library for publish and subscribe to ThingSpeak MQTT. I used port 1883.
I will share the python code I used to subscribe to the ThingSpeak MQTT channel. I have the following doubts:
  1. Please help me resolve the above issue. (highlighted)
  2. Is it possible to use the same device to publish and subscribe to ThingSpeak MQTT, as I did in the first case? If yes, how?
Publish_code:

from __future__ import print_function

import paho.mqtt.publish as publish

from bmp180 import bmp180

from time import sleep

import smbus

import sys


channelID = "1304227"  #Enter your Channel ID here


apiKey = "XXXXXXXXXXXX"  #Enter your WriteAPI key here



useUnsecuredTCP = False

useUnsecuredWebsockets = False

useSSLWebsockets = True

mqttHost = "mqtt.thingspeak.com"

if useUnsecuredTCP:

    tTransport = "tcp"

    tPort = 1883

    tTLS = None


if useUnsecuredWebsockets:

    tTransport = "websockets"

    tPort = 80

    tTLS = None


if useSSLWebsockets:

    import ssl

    tTransport = "websockets"

    tTLS = {'ca_certs':"/etc/ssl/certs/ca-certificates.crt",'tls_version':ssl.PROTOCOL_TLSv1}

    tPort = 443       

topic = "channels/" + channelID + "/publish/" + apiKey

sensor = bmp180(0x77)

temp = ""

pressure = ""

while(True):   

    temp = sensor.get_temp()

    pressure = sensor.get_pressure() 

    print (" Temperature =",temp ,"   Pressure =", pressure)

    tPayload = "field1=" + str(temp) + "&field2=" + str(pressure)

    try:

        publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport)

    except (KeyboardInterrupt):

        break

    except:

        print ("There was an error while publishing the data.")


Subscribe code:

import paho.mqtt.subscribe as subscribe

from bmp180 import bmp180

from time import sleep

import smbus

import sys

from gpiozero import LED


channelID = "1304227"


READapiKey = "YYYYYYYYYYYY"


useUnsecuredTCP = False


useUnsecuredWebsockets = False


useSSLWebsockets = True


mqttHost = "mqtt.thingspeak.com"


if useUnsecuredTCP:

    tTransport = "tcp"

    tPort = 1883

    tTLS = None


if useUnsecuredWebsockets:

    tTransport = "websockets"

    tPort = 80

    tTLS = None


if useSSLWebsockets:

    import ssl

    tTransport = "websockets"

    tTLS = {'ca_certs':"/etc/ssl/certs/ca-certificates.crt",'tls_version':ssl.PROTOCOL_TLSv1}

    tPort = 443



# Create the topic string

topicR = "channels/" + channel1ID + "/subscribe/field/field1/" + READapiKey


led = LED(27)


while(True):

    

    temp_data = subscribe.simple(topicR, hostname = mqttHost)

    print(temp_data.payload)

    

    if (temp_data.payload >=32):

        led.on()

    else:

        led.off()

  



Shubham godbole

unread,
Feb 22, 2021, 11:15:03 PM2/22/21
to MQTT

Hello, I am facing the same issue. I am working on a project to interface the BME 280 sensor with ESP32 and use the publish-subscribe operation of MQTT using ThinSpeak as the broker. I could easily publish to the ThingSpeak channel, but I am facing some issues while trying to subscribe to the channel in order to get data from the ThingSpeak server to my ESP32. I am able to connect to the MQTT server, but unable to subscribe and receive any messages from the ThingSpeak MQTT.

I am posting my subscribe code along with the query, please help me resolve the above highlighted issue.


CODE:

#include <WiFi.h>

#include <PubSubClient.h>

#include <Wire.h>


const char ssid[] = "xyz"; //Insert your SSID

const char pass [] = "xyz";  //Insert Your password

const char* mqtt_server = "mqtt.thingspeak.com";

const char* mqttUserName = " xyz"; // Thingspeak username.

const char* mqttPass = "xyz"; // Change to your MQTT API Key from Account > MyProfile.

const char* ChannelID = " xyz"; // Thingspeak Channel ID

const char* APIKey = "xyz"; // Thingspeak Channel Read API Key

String Temp_String;



WiFiClient espClient;

PubSubClient client(espClient);


void callback(char* topic, byte* payload, unsigned int length) {

  Serial.println("Data received: ");

  Serial.println("Temperature ");

  for (int i = 0; i < length; i++) {

    char receivedChar = (char)payload[i];

    Temp_String += (char)payload[i];

  }

  float TS_Temp = Temp_String.toFloat();

  Serial.print(TS_Temp);

  TS_Temp = 0;

  Temp_String = "";

  Serial.println();

}

void reconnect() {

  // Loop until we're reconnected

  while (!client.connected()) {

    Serial.print("Attempting MQTT connection...");

    // Attempt to connect

    if (client.connect("ESP8266", mqttUserName, mqttPass)) {

      Serial.println("connected");

      // ... and subscribe to topic

      client.subscribe("channels/ChannelID/subscribe/fields/field1/APIKey");

    } else {

      Serial.print("failed, rc=");

      Serial.print(client.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}

void setup()

{

  Serial.begin(115200);

  delay(250);

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);

  WiFi.disconnect();

  delay(100);

  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {

    Serial.print(".");

    delay(500);

  }

  Serial.print("OK");

  Serial.println();

}

void loop()

{

  if (!client.connected()) {

    reconnect();

  }

  client.loop();

Reply all
Reply to author
Forward
0 new messages