Controlling a RaspberryPi GPIO pin with MQTT

In a recent Tutorial, I explained how to address the GPIO pins on a Raspberry from within Openhab, but that was when Openhab is actually on the same RaspberryPi whose pins you wanted to address.
So what if it is another raspberry, that is not the one that has OpenHAB installed on it?

In that case MQTT is a good solution.

I wrote a Python program (download) that will do exactly that. Python most likely will already be on your Raspberry Pi.

Instaling the libraries
You will need two libraries:
The lightweight MQTT client: Here I describe how to install it

The proces comes down to this:
pip install paho-mqtt

if you don’t have pip, first install pip with:
apt install python-pip #python 2

if for whatever reason this does not work for you, try:

git clone https://github.com/eclipse/paho.mqtt.python.git (=> download the client)
cd paho.mqtt.python (=> go to proper directory)
python setup.py install (=> install the client)

depending on how you are logged in you may need to add ‘sudo’ before the install commands

The second one you need to install is the Rpi.GPIO library to address the GPIO pins.
LadyAda gives a good explanation how to do that, but it basically comes down to issuing the command:
sudo apt-get install python-dev python-rpi.gpio

The actual program
The Python program (download) itself is fairly simple, but there are a few things to point out
The Rpi.GPIO library has two modes to set up the pins. it has ‘BCM mode’ and ‘BOARD mode’
These two modes refer to the numbering of the pin.

The GPIO.BOARD option specifies that you are referring to the pins by the number of the pin the the plug - i.e the numbers printed on the board.

The GPIO.BCM option means that you are referring to the pins by the “Broadcom SOC channel” number, these are the numbers after “GPIO” that can be seen in the various pinout diagrams

Screenshot_2018-03-01_10-39-38

In my program I am using pin 11 according to BCM numbering. that is pin23 in BOARD numbering.
If that is OK with you, you do not need to alter anything. If you want another pin, you just need to change the number after “LED1”, but in its current state the program expects a a BCM number.
If you are still a bit puzzled, you can try and issue the gpio readall command on your terminal and depending on the type of Raspberry you have, you may get outputs like this for the Rpi3:


or this for the B+:
gpiob%20
In my program I used the BCM option but you can easily change that into ‘BOARD’. I use GPIO11 as output, but ofcourse that can also be changed easily.

You will also need to set the IP for your particular MQTT broker. and need to change the topic according to your wishes.

mqttpyconfig

The program currently switches only one pin ON or OFF. it is not particularly hard to expand that for more than one pin. If you venture into that and you are not a crack in Python yet, let me draw your attention to statements like if msg.topic.startswith(“topic1/”):
The workings can be controlled by the gpio readall command (check in the column ‘V’ what the state of the pin is)

In my program I used BCM pin 11 which is equal (on my raspi model) to BOARD pin 23.
The below picture shows the readout of the gpio readall command after issuing an OFF and an ON MQTT payload.
Screenshot_2018-03-01_10-21-36

I saved the program in my home/pi directory. It can be started by
python mqttpublish2.py (or any other name you want to give it)
mqttpublish

If you open the program in an ssh window, it will stop once you close that window. Therefore you could best start the program on boot.
In an earlier Tutorial I explained how to do that.
Make sure you end your file commands in rc.local with a " &" (space and ampersand), otherwise only the first may be executed

OpenHAB
Controlling from OpenHAB is through the familiair MQTT channel:
Itemsfile:
Switch RaspiLight "Raspberry Light [%s]" <light> (GF_Living, Lights) {mqtt=">[mosquitto:raspiB/pin11:command:*:default],<[mosquitto:raspiB/pin11:state:default]"}

To avoid any confusion for people who might just be starting with OpenHAB or MQTT: the “raspiB/pin11” topic is completely random, you may call it anything you want. you don’t have to call it “pin11” just because you use pin 11, you may call it say “home/light

6 Likes

Hi. say I have more then one topic that I want to subscribe to how do I do that ?

usually done with a wildcard: topic/#
I haven’t done that with the paho-mqtt library yet as I didn’t have the need, but that’s how I do it on Arduino/ESP, so I presume it is the same here

Ok. But if I want to send to multipels

Example I have 8 Temp sensors

Bedroom 1 - 3 and so on.

Bathroom

How would that work ?

All connected to RPI gpio pins or just multiple MQTT messages?

Yes all on my rpi

And need to go to 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:

https://github.com/rkoshak/sensorReporter

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

etcetera

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:https://community.openhab.org/t/simple-gpio-example/36062?u=kees_van_gelder

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 Co2.in 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:https://www.instructables.com/id/ESP8266-with-Multiple-Analog-Sensors/

certainly a possibility
@allen
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 http://playground.arduino.cc/Main/MQGasSensors

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