Unleash Your Inner Developer: Easy steps to Learn to Build MQTT Apps with MIT App Inventor 2

Unleash Your Inner Developer: Learn to Build MQTT Apps with MIT App Inventor
0
0

Introduction

Are you ready to unleash your inner developer and build powerful MQTT (Message Queuing Telemetry Transport) apps? In this tutorial, we will explore how to create interactive MQTT apps using the MIT App Inventor platform, along with the NodeMCU board programmed using the Arduino IDE. MQTT is a lightweight messaging protocol that enables communication between devices, making it ideal for IoT (Internet of Things) applications. Let’s dive in and learn how to harness the power of MQTT with MIT App Inventor and NodeMCU!

Prerequisites:
To follow along with this tutorial, ensure you have the following:

  1. NodeMCU board (ESP8266-based development board)
  2. Arduino IDE (Integrated Development Environment)
  3. USB cable for NodeMCU board
  4. A computer with a stable internet connection
  5. MQTT broker (e.g., Mosquitto, Cloud-based MQTT services like Adafruit IO or AWS IoT)
  6. MIT App Inventor (web-based development platform)

Step 1: Set Up Arduino IDE and NodeMCU:

  1. Download and install the Arduino IDE from the official Arduino website.
  2. Connect the NodeMCU board to your computer using the USB cable.
  3. Open the Arduino IDE and navigate to “File” -> “Preferences”.
  4. In the “Additional Boards Manager URLs” field, enter the following URL:
    http://arduino.esp8266.com/stable/package_esp8266com_index.json
  5. Click “OK” to save the preferences.
  6. Go to “Tools” -> “Board” -> “Boards Manager” and search for “esp8266”. Install the “esp8266 by ESP8266 Community” board package.
  7. Select the NodeMCU board from “Tools” -> “Board” menu.

Step 2: Install Required Libraries:

  1. Go to “Sketch” -> “Include Library” -> “Manage Libraries” in the Arduino IDE.
  2. Search for and install the following libraries:
  • PubSubClient by Nick O’Leary (for MQTT communication)
  • ArduinoJson by Benoit Blanchon (for JSON data handling)

Step 3: Write the Arduino Sketch:

  1. Open a new sketch in the Arduino IDE.
  2. Import the required libraries at the beginning of your sketch:
   #include <ESP8266WiFi.h>
   #include <PubSubClient.h>
  1. Set up your Wi-Fi and MQTT broker details:
   const char* ssid = "YOUR_WIFI_SSID";
   const char* password = "YOUR_WIFI_PASSWORD";
   const char* mqttServer = "MQTT_BROKER_IP";
   const int mqttPort = 1883;
   const char* mqttUser = "MQTT_USERNAME";
   const char* mqttPassword = "MQTT_PASSWORD";
  1. Set up the necessary objects and functions for MQTT communication:
   WiFiClient espClient;
   PubSubClient client(espClient);
   void setupWiFi();
   void reconnect();
   void callback(char* topic, byte* payload, unsigned int length);
  1. Implement the setup and loop functions:
   void setup() {
     Serial.begin(115200);
     setupWiFi();
     client.setServer(mqttServer, mqttPort);
     client.setCallback(callback);
   }
   void loop() {
     if (!client.connected()) {
       reconnect();
     }
     client.loop();
   }
  1. Implement the WiFi setup and MQTT reconnect functions:
   void setupWiFi() {
     delay(10);
     Serial.println();
     Serial.print("Connecting to ");
     Serial.println(ssid);
     WiFi.begin(ssid, password);
     while (WiFi.status() != WL_CONNECTED) {
       delay(500);
       Serial.print(".");
     }
     Serial.println("");
     Serial.println("WiFi connected");
   }
   void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      
      // ... and resubscribe
      client.subscribe("device/led");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
  1. Add the callback function to handle incoming MQTT messages:
 void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character

  if ((char)payload[0] == '0') {
    digitalWrite(D6, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else if ((char)payload[0] == '1') {
    digitalWrite(D6, HIGH);  // Turn the LED off by making the voltage HIGH
  }
  else if ((char)payload[0] == '2') {
    digitalWrite(D7, HIGH);  // Turn the LED off by making the voltage HIGH
  }
  else if ((char)payload[0] == '3') {
    digitalWrite(D7, LOW);  // Turn the LED off by making the voltage HIGH
  }
  else if ((char)payload[0] == '4') {
    digitalWrite(D8, HIGH);  // Turn the LED off by making the voltage HIGH
  }
  else if ((char)payload[0] == '5') {
    digitalWrite(D8, LOW);  // Turn the LED off by making the voltage HIGH
  }
  else if ((char)payload[0] == '6') {
    digitalWrite(D4, HIGH);  // Turn the LED off by making the voltage HIGH
  }
  else if ((char)payload[0] == '7') {
    digitalWrite(D4, LOW);  // Turn the LED off by making the voltage HIGH
  }
}

DOWNLOAD FULL CODE

  1. Upload the sketch to the NodeMCU board.

Step 4: Create an MQTT App with MIT App Inventor:

  1. Open the MIT App Inventor website (http://appinventor.mit.edu) in your web browser.
  2. Create a new project by clicking on “Projects” -> “Start new project”.
  3. Design the user interface by adding components such as buttons, sliders, labels, etc.
  4. Drag and drop the MQTT component from the “Connectivity” section of the palette onto the screen.
  5. Set up the MQTT component by providing the broker details and event handlers for connecting, disconnecting, and receiving messages.
  6. Write the app logic using blocks to send commands and receive data from the NodeMCU via MQTT.

Step 5: Test and Deploy the App:

  1. Connect your phone or tablet to the same Wi-Fi network as your NodeMCU board.
  2. Go to “Build” -> “App (provide QR code for .apk)” in MIT App Inventor to generate the APK file.
  3. Scan the QR code with your phone’s camera or download the APK file and install it on your device.
  4. Open the app on your device and test the functionality.
  • Check if the MQTT connection is established.
  • Verify if the commands sent from the app are received and executed by the NodeMCU.

Unleash Your Inner Developer: Learn to Build MQTT Apps with MIT App Inventor

Conclusion

Congratulations! You have learned how to build MQTT apps using the MIT App Inventor platform and the NodeMCU board programmed with the Arduino IDE. By combining the power of MQTT, NodeMCU, and MIT App Inventor, you can create interactive and customizable IoT applications. Now, it’s time to unleash your inner developer and explore the endless possibilities of MQTT in your own projects!

Also, check out our other playlist Rasa ChatbotInternet of thingsDockerPython ProgrammingMQTT, etc.
Become a member of our social family on youtube here.

Stay tuned and Happy Learning. ✌🏻😃

Leave a Reply