MQTT on Arduino

MQTT is essentially a simple format for sending small data packages back and forth. It can be used with or without password and the passwords can be simple or encrypted. The information out there is not easy to understand for beginners.

Essentially you have a BROKER (some may think of it as a server). This program accepts messages and dishes out messages.  It handles them in the form of topics and messages.

Imagine you wanted to turn a relay on and off remotely with your Arduino.  Let’s pick a topic name out of thin air… “listentome”.

So – your Arduino needs an Ethernet client connected an MQTT broker and the client needs to be “subscribed” to topic “listentome”. In the simplest case with no passwords, if anyone sends a message such as “turnrelay1on” to the topic “listentome” on the broker – your Arduino will get that message.

Of course with a username and password, only those clients with that username and password will receive that message.

So let’s get a working example so you can see this. And this is where it gets painful unless you’re reading this – where do I find an MQTT “Broker” – what about clients?

Ok, so first things first – on Android there’s a simple server package called Servers Ultimate Pro. This does not YET have the passworded version of the broker but it does have a simple version.  Better – but more complicated – is Mosquitto.  Basically install this from here… open up a command line (yes, I know, how awful but hey, it’s free) and go to the Mosquitto directory and simply type “Mosquitto” in the command line – you’ll see the program is running but with no visible output. Actually it has installed a “service” and you could run it that way but lets stick with the simplest solution first.

Before we start messing with code that might or might not work first time you’ll want to make sure your Mosquitto or Android broker is working – and for that you might want to use an external test program… such as this… the only issue there being – how does it know what your internal IP address is?  Well, to test, I simply put a port redirect on my router.  The standard port used is 1883. Point that external port to the same port on your PC or WIFI-enabled phone or whatever is running the above.

tmp627CAssuming you know how to do that – and with Mosquitto running – you should be able to plug in your external IP address and connect using the tool at

Assuming that works – at the bottom – send a message to topic, oh…. “mytest”.


Won’t work – because no-one is listening. In the window called “subscribe to topics” – SUBSCRIBE to mytest and try again. You’ll see your message come in.

Ok, so how do we get from there to sending messages to and from your Arduino?


You will need your Arduino, the Ethernet shield (don’t use the cheaper ENC boards, they are just so much hard work and I’ve never managed to get them to run reliably – get proper Ethernet cards and if cost is an issue – try Ebay and China). You need to get this library and install it.  unzip the file and there’s a pubsubclient INSIDE the outer one – you need to copy that into your LIBRARY directory for Arduino. Clean start the Arduino IDE for this to take effect.

Examples out there put the setup in the setup routine – great – but what if you lose the connection – so I’ve taken a fairly standard example and moved that setup into the main loop – so that should for any reason you lose the connection – it will reconnect automatically.

Once you get this up and running and understand what you’re doing – moving to the password protected version should be easy enough (read the Mosquitto docs) and actually using this to control relays etc and return status results should be equally easy.

Basic MQTT example

– connects to an MQTT server
– publishes “hello world” to the topic “outTopic”
– subscribes to the topic “inTopic”
int sendit=0;
char msg[20];

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h> // only non-standard library – the rest come with Arduino IDE

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; // make this unique
// internal address of your MQTT broker… or see examples forusing address lookup etc.
byte server[] = { 192,168, 0, 24 };
// internal IP your want this board to be
byte ip[]     = { 192,168, 0, 100 };//

byte mydns[] = { 192, 168, 0, 138 };       // your router
byte gateway[] = { 192, 168, 0, 138 };     // your router
byte subnet[] = { 255,255,255,0 };          // your IP address mask – usually this value

// this routine is called automatically when something comes in. I’ve used serial.print to let you see it. Also use this to prepare a response.
void callback(char* topic, byte* payload, unsigned int length) {*(payload+length)=0;
Serial.print((char *)topic); Serial.print(” : “); Serial.println((char *)payload);
strcpy(msg,”Sorted”); sendit=1;

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

void setup()
Ethernet.begin(mac, ip, dns,gateway,subnet);
Serial.print(“Got IP… “);

void loop()

// this checks to see if you’re connected and connects – will retry forever if need be.
if (!client.connected())  {
Serial.print(“Connecting… “);
if (client.connect(“arduinoClient”)) {
client.publish(“outTopic”,”hello world”);

if (sendit) { sendit=0;   Serial.println(“Sending”); client.publish(“outTopic”,msg); }

I’ve not tried the link below out but it looks like there is some new code for Mosquitto here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s