Arduino UNO R4 - MQTT

In this tutorial, we will learn how to use the Arduino UNO R4 to send and receive data to an MQTT broker using the MQTT protocol. We'll cover the following details:

Arduino UNO R4 MQTT

We will look into two various examples:

Hardware Preparation

1×Arduino UNO R4 WiFi
1×USB Cable Type-C
1×(Recommended) Screw Terminal Block Shield for Arduino UNO R4
1×(Recommended) Breadboard Shield For Arduino UNO R4
1×(Recommended) Enclosure For Arduino UNO R4
1×(Recommended) Power Splitter For Arduino UNO R4

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Arduino UNO R4 and MQTT

We will learn how to program an Arduino UNO R4 to send and receive data through MQTT broker (alse called MQTT server). MQTT broker can be:

  • MQTT broker on the Internet, such as Mosquitto or AWS IoT.
  • MQTT broker set up on your computer, like Mosquitto or HiveMQ.
  • MQTT broker running on your Raspberry Pi, for example, Mosquitto.
  • MQTT broker on the cloud, such as Mosquitto or HiveMQ on AWS EC2.

In this guide, we will start by checking if Arduino UNO R4 can connect to an online Mosquitto broker. Arduino UNO R4 will send and receive messages to and from this broker over the internet.

Next, we will install the Mosquitto broker on our computer. After that, we will connect the Arduino UNO R4 to the MQTT broker on our computer. We will use it to send and receive data through this local broker.

Connect Arduino UNO R4 to an online MQTT broker

In this section, we'll understand how to link Arduino UNO R4 with test.mosquitto.org, an online MQTT service provided by Mosquitto. Remember, this service is meant only for testing.

Arduino UNO R4 Code

This Arduino UNO R4 code performs the following tasks:

  • Connect to the MQTT broker
  • Subscribe to a topic
  • Regularly send messages to the same topic you subscribed to
/* * This Arduino UNO R4 code was developed by newbiely.com * * This Arduino UNO R4 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-mqtt */ #include <WiFiS3.h> #include <MQTTClient.h> #include <ArduinoJson.h> const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // CHANGE TO YOUR WIFI SSID const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // CHANGE TO YOUR WIFI PASSWORD const char MQTT_BROKER_ADRRESS[] = "test.mosquitto.org"; // CHANGE TO MQTT BROKER'S ADDRESS const int MQTT_PORT = 1883; const char MQTT_CLIENT_ID[] = "YOUR-NAME-arduino-uno-r4"; // CHANGE IT AS YOU DESIRE const char MQTT_USERNAME[] = ""; // CHANGE IT IF REQUIRED, empty if not required const char MQTT_PASSWORD[] = ""; // CHANGE IT IF REQUIRED, empty if not required // The MQTT topics that Arduino should publish/subscribe const char PUBLISH_TOPIC[] = "YOUR-NAME-arduino-uno-r4/loopback"; // CHANGE IT AS YOU DESIRE const char SUBSCRIBE_TOPIC[] = "YOUR-NAME-arduino-uno-r4/loopback"; // CHANGE IT AS YOU DESIRE const int PUBLISH_INTERVAL = 5000; // 5 seconds WiFiClient network; MQTTClient mqtt = MQTTClient(256); unsigned long lastPublishTime = 0; void setup() { Serial.begin(9600); int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { Serial.print("Arduino UNO R4 - Attempting to connect to SSID: "); Serial.println(WIFI_SSID); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // wait 5 seconds for connection: delay(5000); } // print your board's IP address: Serial.print("IP Address: "); Serial.println(WiFi.localIP()); connectToMQTT(); } void loop() { mqtt.loop(); if (millis() - lastPublishTime > PUBLISH_INTERVAL) { sendToMQTT(); lastPublishTime = millis(); } } void connectToMQTT() { // Connect to the MQTT broker mqtt.begin(MQTT_BROKER_ADRRESS, MQTT_PORT, network); // Create a handler for incoming messages mqtt.onMessage(messageHandler); Serial.print("Arduino UNO R4 - Connecting to MQTT broker"); while (!mqtt.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("."); delay(100); } Serial.println(); if (!mqtt.connected()) { Serial.println("Arduino UNO R4 - MQTT broker Timeout!"); return; } // Subscribe to a topic, the incoming messages are processed by messageHandler() function if (mqtt.subscribe(SUBSCRIBE_TOPIC)) Serial.print("Arduino UNO R4 - Subscribed to the topic: "); else Serial.print("Arduino UNO R4 - Failed to subscribe to the topic: "); Serial.println(SUBSCRIBE_TOPIC); Serial.println("Arduino UNO R4 - MQTT broker Connected!"); } void sendToMQTT() { StaticJsonDocument<200> message; message["timestamp"] = millis(); message["data"] = analogRead(0); // Or you can read data from other sensors char messageBuffer[512]; serializeJson(message, messageBuffer); mqtt.publish(PUBLISH_TOPIC, messageBuffer); Serial.println("Arduino UNO R4 - sent to MQTT:"); Serial.print("- topic: "); Serial.println(PUBLISH_TOPIC); Serial.print("- payload:"); Serial.println(messageBuffer); } void messageHandler(String &topic, String &payload) { Serial.println("Arduino UNO R4 - received from MQTT:"); Serial.println("- topic: " + topic); Serial.println("- payload:"); Serial.println(payload); }

Detailed Instructions

Follow these instructions step by step:

  • If this is your first time using the Arduino Uno R4 WiFi/Minima, refer to the tutorial on setting up the environment for Arduino Uno R4 WiFi/Minima in the Arduino IDE.
  • Connect the Arduino Uno R4 board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate Arduino Uno R4 board (e.g., Arduino Uno R4 WiFi) and COM port.
  • Click on the "Library Manager" icon found on the left side of Arduino IDE to open it.
  • In the search box, enter MQTT and search for the MQTT library by Joel Gaehwiler.
  • Click the Install button to add the MQTT library.
Arduino UNO R4 MQTT library
  • Search for ArduinoJson in the search box and find the ArduinoJson library by Benoit Blanchon. Then, click on the Install button to install the library.
Arduino UNO R4 Json library
  • Copy the code and open it in the Arduino IDE.
  • Change the WiFi details (SSID and password) in the code to yours.
  • You'll find 'YOUR-NAME' three times in the code. Replace it with your name or any letters (no spaces). This change is important to avoid conflicts from multiple users running the same code.
  • Click the Upload button in Arduino IDE to upload the code to your Arduino UNO R4.
  • Open the Serial Monitor.
  • Check the results on the Serial Monitor.
COM6
Send
IP Address: 192.168.0.2 Arduino UNO R4 - Connecting to MQTT broker Arduino UNO R4 - Subscribed to the topic: YOUR-NAME-arduino-uno-r4/loopback Arduino UNO R4 - MQTT broker Connected! Arduino UNO R4 - sent to MQTT: - topic: YOUR-NAME-arduino-uno-r4/loopback - payload:{"timestamp":11757,"data":255} Arduino UNO R4 - received from MQTT: - topic: YOUR-NAME-arduino-uno-r4/loopback - payload: {"timestamp":11757,"data":255} Arduino UNO R4 - sent to MQTT: - topic: YOUR-NAME-arduino-uno-r4/loopback - payload:{"timestamp":16896,"data":259} Arduino UNO R4 - received from MQTT: - topic: YOUR-NAME-arduino-uno-r4/loopback - payload: {"timestamp":16896,"data":259}
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

The Arduino UNO R4 sends messages to the MQTT broker and then gets the same message back. This happens because it is set to receive messages from the same topic it sends them to. If you do not want the Arduino UNO R4 to receive its own messages, just use different topics for sending and receiving.

Connect Arduino UNO R4 to the MQTT broker installed on your PC

Installing Mosquitto MQTT Broker

  • Install it on the D: drive, not the C: drive. This helps avoid possible problems.

Run Mosquitto MQTT broker

Now, let's see if the MQTT broker is working correctly by taking these steps:

  • Navigate to the folder where you installed Mosquitto, such as D:\Draft\mosquitto. Create a file called test.conf, paste the following details into it, and save the file in this folder.
listener 1883 allow_anonymous true
  • Open a Command Prompt as Administrator on your computer. Refer to it as "Broker Window." Remember not to close this window until you finish the tutorial.
Windows command prompt administrator
  • Execute the following commands sequentially:
cd /d D:\Draft\mosquitto mosquitto -v -c test.conf
  • You will notice:
Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\Draft\mosquitto D:\Draft\mosquitto>mosquitto -v -c test.conf 1710918939: mosquitto version 2.0.18 starting 1710918939: Config loaded from test.conf. 1710918939: Opening ipv6 listen socket on port 1883. 1710918939: Opening ipv4 listen socket on port 1883. 1710918939: mosquitto version 2.0.18 running
  • Open a new Command Prompt as Administrator on your computer.
  • To find your computer's IP address, run this command:
ipconfig
Command Prompt
C:\WINDOWS\system32>ipconfig Windows IP Configuration Ethernet adapter: Subnet Mask . . . . . . . . . . . : 255.0.0.0 IPv4 Address. . . . . . . . . . . : 192.168.0.11 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . :
  • Please note the IP address for future reference. In the example provided: 192.168.0.11.

Test if the Mosquitto Broker works

  • Open another Command Prompt as Administrator on your computer. We will refer to it as "Subscriber Window."
  • To subscribe to a topic, enter the following commands one at a time, replacing "your IP address" with your actual IP address:
cd /d D:\Draft\mosquitto mosquitto_sub -h 192.168.0.11 -p 1883 -t arduino-uno-r4/send
  • Open an additional Command Prompt with Administrator rights on your computer. Name it Publisher Window.
  • To publish a message to the same topic, execute the following commands one after another (substitute with your IP address):
cd /d D:\Draft\mosquitto mosquitto_pub -h 192.168.0.11 -p 1883 -t arduino-uno-r4/send -m "Hello, MQTT!"
  • You will notice:
Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\Draft\mosquitto D:\Draft\mosquitto>mosquitto_pub -h 192.168.0.11 -p 1883 -t arduino-uno-r4/send -m "Hello, MQTT!" D:\Draft\mosquitto>

The message is sent to the Subscriber Window like this:

Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\Draft\mosquitto D:\Draft\mosquitto>mosquitto_sub -h 192.168.0.11 -p 1883 -t arduino-uno-r4/send Hello, MQTT!

You have successfully installed the Mosquitto MQTT broker on your PC. Please do not close three windows: Broker Window, Subscriber Window, and Publisher Window. We will use them next.

Arduino UNO R4 Code

The following code is for Arduino UNO R4 and it does the following:

  • Connect to the MQTT broker
  • Subscribe to a topic
  • Regularly send messages to a different topic
/* * This Arduino UNO R4 code was developed by newbiely.com * * This Arduino UNO R4 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-mqtt */ #include <WiFiS3.h> #include <MQTTClient.h> #include <ArduinoJson.h> const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // CHANGE TO YOUR WIFI SSID const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // CHANGE TO YOUR WIFI PASSWORD //const char MQTT_BROKER_ADRRESS[] = "test.mosquitto.org"; // CHANGE TO MQTT BROKER'S ADDRESS const char MQTT_BROKER_ADRRESS[] = "192.168.0.11"; // CHANGE TO MQTT BROKER'S IP ADDRESS const int MQTT_PORT = 1883; const char MQTT_CLIENT_ID[] = "arduino-uno-r4"; // CHANGE IT AS YOU DESIRE const char MQTT_USERNAME[] = ""; // CHANGE IT IF REQUIRED, empty if not required const char MQTT_PASSWORD[] = ""; // CHANGE IT IF REQUIRED, empty if not required // The MQTT topics that Arduino should publish/subscribe const char PUBLISH_TOPIC[] = "arduino-uno-r4/send"; // CHANGE IT AS YOU DESIRE const char SUBSCRIBE_TOPIC[] = "arduino-uno-r4/receive"; // CHANGE IT AS YOU DESIRE const int PUBLISH_INTERVAL = 5000; // 5 seconds WiFiClient network; MQTTClient mqtt = MQTTClient(256); unsigned long lastPublishTime = 0; void setup() { Serial.begin(9600); int status = WL_IDLE_STATUS; while (status != WL_CONNECTED) { Serial.print("Arduino UNO R4 - Attempting to connect to SSID: "); Serial.println(WIFI_SSID); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // wait 10 seconds for connection: delay(10000); } // print your board's IP address: Serial.print("IP Address: "); Serial.println(WiFi.localIP()); connectToMQTT(); } void loop() { mqtt.loop(); if (millis() - lastPublishTime > PUBLISH_INTERVAL) { sendToMQTT(); lastPublishTime = millis(); } } void connectToMQTT() { // Connect to the MQTT broker mqtt.begin(MQTT_BROKER_ADRRESS, MQTT_PORT, network); // Create a handler for incoming messages mqtt.onMessage(messageHandler); Serial.print("Arduino UNO R4 - Connecting to MQTT broker"); while (!mqtt.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("."); delay(100); } Serial.println(); if (!mqtt.connected()) { Serial.println("Arduino UNO R4 - MQTT broker Timeout!"); return; } // Subscribe to a topic, the incoming messages are processed by messageHandler() function if (mqtt.subscribe(SUBSCRIBE_TOPIC)) Serial.print("Arduino UNO R4 - Subscribed to the topic: "); else Serial.print("Arduino UNO R4 - Failed to subscribe to the topic: "); Serial.println(SUBSCRIBE_TOPIC); Serial.println("Arduino UNO R4 - MQTT broker Connected!"); } void sendToMQTT() { StaticJsonDocument<200> message; message["timestamp"] = millis(); message["data"] = analogRead(0); // Or you can read data from other sensors char messageBuffer[512]; serializeJson(message, messageBuffer); mqtt.publish(PUBLISH_TOPIC, messageBuffer); Serial.println("Arduino UNO R4 - sent to MQTT:"); Serial.print("- topic: "); Serial.println(PUBLISH_TOPIC); Serial.print("- payload:"); Serial.println(messageBuffer); } void messageHandler(String &topic, String &payload) { Serial.println("Arduino UNO R4 - received from MQTT:"); Serial.println("- topic: " + topic); Serial.println("- payload:"); Serial.println(payload); // You can process the incoming data as json object, then control something /* StaticJsonDocument<200> doc; deserializeJson(doc, payload); const char* message = doc["message"]; */ }

Detailed Instructions

  • Copy the code above and open it using Arduino IDE
  • Change the WiFi details (SSID and password) in the code to yours.
  • Change the MQTT broker address in the code (either domain name or IP address).
  • Click the Upload button in Arduino IDE to send the code to your Arduino UNO R4.

Send message from Arduino UNO R4 to PC via MQTT

The Arduino UNO R4 sends information to the MQTT topic named arduino-uno-r4/send. On a computer, the Subscriber Window subscribes to that topic to receive the data.

  • Open the Serial Monitor to see that the Arduino UNO R4 regularly sends a message to a topic.
COM6
Send
IP Address: 192.168.0.2 Arduino UNO R4 - Connecting to MQTT broker Arduino UNO R4 - Subscribed to the topic: arduino-uno-r4/receive Arduino UNO R4 - MQTT broker Connected! Arduino UNO R4 - sent to MQTT: - topic: arduino-uno-r4/send - payload:{"timestamp":10708,"data":311} Arduino UNO R4 - sent to MQTT: - topic: arduino-uno-r4/send - payload:{"timestamp":15837,"data":298} Arduino UNO R4 - sent to MQTT: - topic: arduino-uno-r4/send - payload:{"timestamp":20965,"data":291} Arduino UNO R4 - sent to MQTT: - topic: arduino-uno-r4/send - payload:{"timestamp":26094,"data":286}
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Look at the Subscriber Window and you'll notice it shows the message sent by the Arduino UNO R4 like this:
Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\Draft\mosquitto D:\Draft\mosquitto>mosquitto_sub -h 192.168.0.11 -p 1883 -t arduino-uno-r4/send Hello, MQTT! {"timestamp":10708,"data":311} {"timestamp":15837,"data":298} {"timestamp":20965,"data":291} {"timestamp":26094,"data":286}

Send message from PC to Arduino UNO R4 via MQTT

The Arduino UNO R4 is set to receive messages from the topic arduino-uno-r4/receive. The Publisher Window on the PC sends messages to this topic to communicate with the Arduino UNO R4.

  • Send a message to the topic subscribed by Arduino UNO R4 using this command in the Publisher Window:
mosquitto_pub -h 192.168.0.11 -p 1883 -t arduino-uno-r4/receive -m "Hello, Arduino UNO R4!"
  • You will notice that Arduino UNO R4 receives this message, as shown on the Serial Monitor:
COM6
Send
Arduino UNO R4 - received from MQTT: - topic: arduino-uno-r4/receive - payload: Hello, Arduino UNO R4!
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!