Welcome to another tutorial of the How to MQTT series. In this tutorial, we will learn to make an android application for controlling the LED and showing the sensor data (DHT11) using the MQTT protocol. We will be using MIT app inventor to create our android application.
One of the main aims of the internet of things is to make connectivity with all intelligent devices. Android devices are convenient to control appliances from anywhere around the world.
The data we will be showing on the MQTT android application will come from ESP8266, DHT11 sensor, which we programmed in our last tutorials.
Revision
If you have been following my MQTT series or youtube channel. You will be familiar with What is MQTT protocol?
If not, here is a short introduction to the MQTT protocol.
MQTT protocol is an IoT ( Internet of things) lightweight protocol that uses publish/subscribe to communicate between devices.
MQTT works well at unreliable networks.
There are a few MQTT terminologies that you should know, which are as follows.
- Publish / Subscribe
- Messages
- Topics
- Broker
We already discussed brokers in the “Mosquitto MQTT Broker Raspberry Pi” blog. In which we made our cheap MQTT broker.
Also, we have covered how to use the MQTT protocol in MATLAB, Python and how to make real time plotting using python and MQTT protocol.
Also, PCBWay.com are the sponsor of this video. Who are experts at providing PCB, 3D, CNC services. Make sure to check their website.
Why MIT app inventor ?
MIT app inventor is very simple to use, and you can build any android application in minutes by just dragging and dropping components. Also, the MIT app inventor has been very popular among the young kids who start with STEM education, as block programming helps them understand the programming concept.
So, lets start our project by creating a new project in MIT app inventor.
Buying guide
Development board | Amazon (US) | Ali express |
---|---|---|
ESP32 | ||
Raspberry pi zero | ||
Raspberry pi 4 | ||
ESP8266 | ||
DHT11 |
Starting a new project and introduction to MIT app inventor
First, when you are on the MIT app inventor website, click on create apps, it will ask you to log in; you can log in using a Google account, and then you will see a bunch of projects if you have created before or you can create a new project and name it.
Then you will see a mobile screen where you will drag and drop items from the left menu, and on the right menu, you can change the parameters of those components.
You can do the back-end development in the block menu, like how a specific button will behave when clicking on it.
Creating Layout
Ok, lets start by dragging a vertical layout in our screen, so all the items are in vertical arrangement and set the width of layout to fill-parent.
Then we will add a horizontal layout, and inside it, we will add a label to show the title MQTT dashboard, and in the right menu, you can play with parameters to adjust the size, width, height alignment, etc.
Now let’s import our media that we will be using in our app. I have downloaded some images that I want to place in the app . Let’s import them by clicking on upload file in the right menu.
Now let’s add another horizontal layout inside the vertical one and add image and label components to it.
Then, from the right side menu, change the picture and set the label text and sizing, etc. Also, we will make the first image clickable. So, when we press it, the picture changes and it can send an MQTT message.
Now let’s copy the whole horizontal layout, place it under the first, change the image to temperature and text. Similarly, copy-paste again for the humidity part.
We need to add a button for connecting to the MQTT broker. So, I will copy the same horizontal layout, and instead of the image, i will put a button. Then rename it to “connect” and change the label text as well.
Finally, I want to place an image to fill the space and publicize my channel. Also, if you have not liked and subscribed, please do so I can make more such videos.
Then we will drag a notifier component so we can generate notification alerts in certain cases.
Also, we need to download the MQTT extension, which we can download from ullis robotor seite. You will find detailed documentation of the MQTT extension as well. After downloading, extract the extension and import it in the MIT app inventor and drag it down on the screen.
When you drag the MQTT extension, you will see many values that you need to put to use the MQTT protocol.
So, set the broker, port, user name, password, client ID, etc.
and the layout is ready now , we need to do the programming part.
ESP8266 code
Let me show you the esp8266 code I am using for this; we wrote that program in our last tutorials. So, I want to show that we are sending sensor data to the Tempdata topic. And we are subscribing to the “lights” topic in esp8266 and the ON message turns on the LED.
#include <Adafruit_Sensor.h> //Library for Adafruit sensors , we are using for DHT #include <DHT_U.h> //DHT library which uses some func from Adafruit Sensor library #include <ESP8266WiFi.h> //library for using ESP8266 WiFi #include <PubSubClient.h> //library for MQTT #include <ArduinoJson.h> //library for Parsing JSON //defining Pins #define DHTPIN 5 #define LED D2 //DHT parameters #define DHTTYPE DHT11 // DHT 11 DHT_Unified dht(DHTPIN, DHTTYPE); uint32_t delayMS; //MQTT Credentials const char* ssid = "ssid";//setting your ap ssid const char* password = "password";//setting your ap psk const char* mqttServer = "iot.reyax.com"; //MQTT URL const char* mqttUserName = "mqtt username"; // MQTT username const char* mqttPwd = "mqtt password"; // MQTT password const char* clientID = "username0001"; // client id username+0001 const char* topic = "Tempdata"; //publish topic //parameters for using non-blocking delay unsigned long previousMillis = 0; const long interval = 5000; String msgStr = ""; // MQTT message buffer float temp, hum; //setting up wifi and mqtt client WiFiClient espClient; PubSubClient client(espClient); void setup_wifi() { delay(10); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void reconnect() { while (!client.connected()) { if (client.connect(clientID, mqttUserName, mqttPwd)) { Serial.println("MQTT connected"); client.subscribe("lights"); Serial.println("Topic Subscribed"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); // wait 5sec and retry } } } //subscribe call back void callback(char*topic, byte* payload, unsigned int length) { Serial.print("Message arrived in topic: "); Serial.println(topic); Serial.print("Message:"); String data = ""; for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); data += (char)payload[i]; } Serial.println(); Serial.print("Message size :"); Serial.println(length); Serial.println(); Serial.println("-----------------------"); Serial.println(data); if(data=="ON"){ Serial.println("LED"); digitalWrite(LED, HIGH); } else{ digitalWrite(LED, LOW); } } void setup() { Serial.begin(115200); // Initialize device. dht.begin(); // get temperature sensor details. sensor_t sensor; dht.temperature().getSensor(&sensor); dht.humidity().getSensor(&sensor); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); setup_wifi(); client.setServer(mqttServer, 1883); //setting MQTT server client.setCallback(callback); //defining function which will be called when message is received. } void loop() { if (!client.connected()) { //if client is not connected reconnect(); //try to reconnect } client.loop(); unsigned long currentMillis = millis(); //read current time if (currentMillis - previousMillis >= interval) { //if current time - last time > 5 sec previousMillis = currentMillis; //read temp and humidity sensors_event_t event; dht.temperature().getEvent(&event); if (isnan(event.temperature)) { Serial.println(F("Error reading temperature!")); } else { Serial.print(F("Temperature: ")); temp = event.temperature; Serial.print(temp); Serial.println(F("°C")); } // Get humidity event and print its value. dht.humidity().getEvent(&event); if (isnan(event.relative_humidity)) { Serial.println(F("Error reading humidity!")); } else { Serial.print(F("Humidity: ")); hum = event.relative_humidity; Serial.print(hum); Serial.println(F("%")); } msgStr = String(temp) +","+String(hum); byte arrSize = msgStr.length() + 1; char msg[arrSize]; Serial.print("PUBLISH DATA:"); Serial.println(msgStr); msgStr.toCharArray(msg, arrSize); client.publish(topic, msg); msgStr = ""; delay(50); } }
Programming MQTT android app
Now let’s be a kid and program our application using block programming.
Firstly, we will use the button event when the button clicks for connect button. Then we will use if and else block to see state of connection to MQTT broker. If the current state is “connected to the broker” we will disconnect from MQTT broker.
Otherwise, we will connect and use a clean session, which means MQTT does not store any information about subscriptions, etc.
Then from the MQTT extension, we will use the event block when the connection state has changed. Using the if and else block, we will see if we are now “connected” or “disconnected”.
If we are connected now, we will modify the button text to disconnect and change the label’s text; we will subscribe to our topic using QoS 0. Wildcards are also accepted. Otherwise, we will change the button and label text if we are disconnected.
Then we will use the event of bulb image; when it clicks, we will see if we are connected to the broker or not; if we are connected, and the current image is “off.png” the bulb, we will publish a message ON on topic lights and change the button image and label. Otherwise, we will publish an “off” message and change the picture and label.
If we are not connected to the broker and are pressing that button, we will alert that we are not connected to the MQTT broker using the notifier extension.
Then we will use the MQTT extension event when we receive the message, and using if and else block, we will check if we have received notification on the temp data topic.
Then, we will create a list to store temperature and humidity data; from esp8266, we are sending data comma separated.
So we will split the data using “,” as a separator and store both values in the data list at index 1 and 2. Then in the label three texts, which is for temperature, we will show the value of temperature, and here we are using join block to combine value and the degree symbol.
Similarly, we will add text to label four which is for humidity.
And our application is ready.
Get ESP8266 code and MIT app inventor *.aia file from this github repository.
Building APK and running it
Click on build and then android app (apk) , you will get two options either to dowload it or you can directly download from your android device by scanning the QR code.
here is the final look of the application.
I hope you liked this tutorial, if you do so, please like, share and subscribe.