Controlling a RaspberryPi GPIO pin with MQTT

I want most of my sensors that do my enviro monitoring running of my rpi. And comunicate via mqtt. That i have in center of my house. My ligits runs off of sonnof t1
And my other power controls i use esp8266

Or Is there other suggestions on how to do this as the rip that the sensors are connected to is my openhab server aswell.

Check out this link:

perhaps I misunderstand the question, but it is just as always with mqtt, check for the incoming message and then take action on that basis.

The program I provided only checks on Payload ON/OF as I only control one pin and am subscribed to one topic, but if you want to control more pins, you also need to check on ‘Topic’’

So in my program, before the check:
if (msg.payload=='ON'):

you would first check which topic, like so:
if (msg.topic=='mytopic1'):

and then that is followed by the ON/OFF check

You repeat that for the amount of topics you are subscribed to.

so it would be:

check for topic 1
   if payload ==ON ->take action
   if payload==OFF -> take action

check for topic 2
   if payload ==ON ->take action
   if payload==OFF -> take action


Now ofcourse if it is all on the same raspi as your openhab install, you do not need mqtt, then you just let openhab set the desired pins directly, via the GPIO binding, as I explained here:

1 Like

i was thinking if that would not be better doing it direct.
my other question is how would I do analog ?
I ill be using a map 3008 for to mq-05 gas sensors
and 7 x dht 22, and then only one relay that turns a extractor on and off in the bath room.

will draw out a diagram showing my idea and setup.

the raspi is not really great at doing analog signals, as it has no ADC, although it is possible to use an analog signal that charges a capacitor and then measure the time it takes to reach a certain voltage. But I wouldn’t advise to go that way.

I presume you mean the MCP3008, that is certainly an option. I think that one uses SPI. My preference would be an I2C module and there are plenty of those as well
the 7xdht22 can all be handled with the digital pins of the raspberry.Plenty of totorials available and I did one as well here on the forum Reading a DHT11/22 on a raspberry and send the results by MQTT

sorry about the typo.

I would also rather look at using the i2c.
the mQ-x range comes mostly with AQ. and only a few with DQ. the one I am looking at using is analog. for measuring LPG an the kitchen and in the entertainment area .

but I can also read the dht22 directly in openhab no need to use mqtt

consider he ADS1115

You could also use your esp8266, depending where you need the sensors, it has ADC ability. Heres example/guide on how to use:

certainly a possibility
keep in mind the MQ-x sensors need preheating, though some are OK to just remain connected to Vcc, some others need a certain cycling of the applied voltage.Certainly the CO sensor needs that. Not sure about the MQ-5

what other sensors would you recommend for the application ?

well that all depends on what you like to measure.
depending on the purpose (like CO2 for plant growth) I would generally be more interested in CO levels.
LPG, I am not sure. I guess it will also react to the gas you might be cooking on in yr kitchen,

MQ-2 does methane and Butane, LPG and smoke
MQ-4 does methane and CNG
MQ-6 does butane and LPG
MQ-7 does CO
seems only the MQ7 needs to cycle between 5V and 1.4V.the others just need 5 or 6 v
Full summary here

I had a look at this now.

will get one and test. and see what happens. the co I might just leave
as long as I can read lpg and say smoke. like the mq-2

good choice

Thanks for the information and also the tutorials you guys do.
hope fully one day I will get to the point as well . I am still learning the system and all the finer details and working.

thanks for your kind words. good luck and don’t hesitate to ask more questions if needed.
Once you finished your project, consider sharing it, it may help someone else

I will share once I am done and running.

1 Like

Hello .
I trying to continue your script witch ( so far ) two GPIOs - and it looks good and give no errors , but don’t know how to subscribe to more topics ( as many as GPIOs i want to use ).
I don’t know much python. I don’t know that will be better to make several files for every GPIO & topic i want to use or it can be done in one file. So far i have no idea how to subscribe more topics. Any idea ? In general in my house are working two RPI3 and many esp8266 - and actually i wanted to utilize not used gpios from both of RPI.

# MQTT Controll GPIO pin
# Import package
import paho.mqtt.client as mqtt
#add for output
import RPi.GPIO as GPIO

# Define Variables
MQTT_PORT = 1883
MQTT_TOPIC = "cmnd/STouch_BathRoom/power"
MQTT_TOPIC1 = "cmnd/STouchLivRoom1/power"
LED1 = 9
LED2 = 10
LED3 = 11

  # Define on connect event function
  # We shall subscribe to our Topic in this function
  def on_connect(self,mosq, obj, rc):
     mqttc.subscribe(MQTT_TOPIC, 0)
     print("Connect on "+MQTT_HOST)
  # Define on_message event function.
  # This function will be invoked every time,
  # a new message arrives for the subscribed topic
  def on_message(mosq, obj, msg):

     if (msg.topic=='Topic1'):
         if (msg.payload=='ON'):
           print 'Lamp1 ON'
           print "Topic1: " + str(msg.topic)
           print "QoS: " + str(msg.qos)
     if (msg.payload=='OFF'):
           print 'Lamp1 OFF'
           print "Topic1: " + str(msg.topic)
           print "QoS: " + str(msg.qos)

     if (msg.topic=='Topic2'):
         if (msg.payload=='ON'):
            print 'Lamp2 ON'
            print "Topic2: " + str(msg.topic)
            print "Qos: " + str(msg.qos)
     if (msg.payload=='OFF'):
            print 'Lamp2 OFF'
            print "Topic2 " + str(msg.topic)
            print "Qos: " + str(msg.topic1)

  def on_subscribe(mosq, obj, mid, granted_qos):
          print("Subscribed to Topic: " +
          MQTT_TOPIC + " with QoS: " + str(granted_qos))

    # Initiate MQTT Client
  mqttc = mqtt.Client()

    # Assign event callbacks
  mqttc.on_message = on_message
  mqttc.on_connect = on_connect
  mqttc.on_subscribe = on_subscribe

    # Connect with MQTT Broker

    # Continue monitoring the incoming messages for subscribed topic

except KeyboardInterrupt:
    # here you put any code you want to run before the program
    # exits when you press CTRL+C
    #GPIO.cleanup() # this ensures a clean exit

Jerry, subscription can be done with a wildcard if the topics share a common denominator, or by stating the individual topics like this:
the numbers 2,1,0 I added do not stand for any sequence but as examples for the QoS that can be given as second parameter.

handling of the topics then is done with if statements in the callback function.
It is also possible to add a callback function for every topic,

mqttc.message_callback_add('home/light', on_message_light)
mqttc.message_callback_add('home/fan', on_message_fan)
mqttc.message_callback_add('home/heating', on_message_heat)

but i find that less elegant