Internet of Things – Publish Sensor Data

Today I will talk about how you can publish your sensor data to an MQTT broker. I will publish information about the temperature and level of light in my room, but the same approach can be used to publish any sensory data.

By publishing the sensor data using an MQTT broker, the information can be made available to a number of different consumers. It could be a physical panel showing the readings on a LED display or a dashboard on a web page, and it could even be a mobile app that is available on different mobile platforms. The interesting thing is that the publishing of the data is disconnected from the consumption of the data, and that opens up many opportunities on how the data can be used.

All the hardware that you need to perform this lab is the same as in my previous video called “Internet of Things – Sensors”, so please check that out for the details. The difference this time is that I will add a publication of the data to an MQTT broker, so that it can be consumed by any client.

Here is the Arduino code (sketch)…

…and after the initial includes, constants for the two analogue input pins are defined (on lines 4-5). The MQTT client object is defined and created (on lines 6-7), followed by the declaration of a number of variables (on line 8-12). In the setup, we initialize the bridge (on line 16), which allows communication between the microcontroller (32U4) and the microprocessor (AR9331, with Linux), and then we connect the MQTT client to the server (on line 17). The eternal loop starts by checking if a five second interval has passed, and if so, read the value from the temperature sensor (on line 25), and since that value is a raw value (in the range 0-1023) it needs to be converted (on lines 26-28 and 30) to a temperature using a formula (it’s called the Steinhart-Hart Thermistor Equation, and you can read more about it on Wikipedia, http://en.wikipedia.org/wiki/Thermistor). The first temperature captured to be published (on line 29) is in Celsius, and the second (on line 31) is in Fahrenheit. The light sensor value is read (on line 32) and added to the published data (on line 33), and the data is published (on lines 34-35) to the MQTT broker.

To see the published data, connect to the server (replace AwsKeyPar.pem with your key file, and 0.0.0.0 with the IP address of your server)…

ssh -i AwsKeyPair.pem ubuntu@0.0.0.0

…and then run the command:

mosquitto_sub -d -t arduino/sensors

This starts a subscription to the topic “arduino/sensors” where you can see the published sensor data, and the output should look something like this.

That is how you can publish your sensor data to an MQTT broker.