Communication between two Arduino Nano ESP32 via MQTT

In this tutorial, we'll cover the following:

communication between two arduino via MQTT

Hardware Preparation

2×Arduino Nano ESP32
2×USB Cable Type-C
1×Push Button
1×(Optional) Panel-mount Push Button
1×LED
1×220 ohm resistor
1×Breadboard
1×Jumper Wires
1×(Recommended) Screw Terminal Adapter for Arduino Nano

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. We appreciate your support.

Overview of Arduino Nano ESP32 and MQTT

We have a detailed tutorial on how to use Arduino Nano ESP32 with MQTT here:

Communication between two Arduino Nano ESP32 via MQTT

Two Arduino Nano ESP32 boards can communicate with each other using an MQTT server. If you prefer for them to communicate directly without using an MQTT server, please refer to the tutorial on Arduino Nano ESP32 to Arduino Nano ESP32 TCP Client/Server communication.

When Arduino Nano ESP32 #1 and Arduino Nano ESP32 #2 exchange data via an MQTT broker:

  • Both Arduino Nano ESP32s connect to the MQTT broker.
  • To have Arduino Nano ESP32 #2 send data to Arduino Nano ESP32 #1:
    • Arduino Nano ESP32 #1 subscribes to a topic, for example: arduino-nano-esp32-1/data.
    • Arduino Nano ESP32 #2 can send data to Arduino Nano ESP32 #1 by publishing the data to the topic that Arduino Nano ESP32 #1 is subscribed to.
  • Similarly, to have Arduino Nano ESP32 #1 send data to Arduino Nano ESP32 #2:
    • Arduino Nano ESP32 #2 subscribes to a topic, for example: arduino-nano-esp32-2/data.
    • Arduino Nano ESP32 #1 can send data to Arduino Nano ESP32 #2 by publishing the data to the topic that Arduino Nano ESP32 #2 is subscribed to.

    Following this method, two Arduino Nano ESP32s can exchange data bidirectionally.

Example Use Case

Let's realize the following application: A button/switch connected to Arduino Nano ESP32 #1 controls an LED connected to Arduino Nano ESP32 #2 via MQTT.

communication between two arduino

As mentioned above, there are some application protocols we can use. In this example, to make it simple, we will define a protocol by ourself (a self-defined protocol)

How It Works

Let's establish a simple protocol:

  • Both Arduino Nano ESP32 #1 and Arduino Nano ESP32 #2 connect to an MQTT Broker (MQTT server).
  • For Arduino Nano ESP32 #1:
    • Arduino Nano ESP32 #1 sends an MQTT message to a topic whenever the state of a switch changes.
    • When the button or switch is turned on, the MQTT message payload is set to 1.
    • When the button or switch is turned off, the MQTT message payload is set to 0.
  • For Arduino Nano ESP32 #2:
    • Arduino Nano ESP32 #2 subscribes to the topic.
    • If Arduino Nano ESP32 #2 receives an MQTT message with a payload of 1, it turns on an LED.
    • If Arduino Nano ESP32 #2 receives an MQTT message with a payload of 0, it turns off the LED.

    Wiring Diagram

    • Arduino Nano ESP32 #1 - Wiring diagram between Arduino Nano ESP32 and button
    The wiring diagram between Arduino Nano ESP32 and Button

    This image is created using Fritzing. Click to enlarge image

    • Arduino Nano ESP32 #2 - Wiring diagram between Arduino Nano ESP32 and LED
    The wiring diagram between Arduino Nano ESP32 and LED

    This image is created using Fritzing. Click to enlarge image

Communication between two Arduino Nano ESP32 via MQTT

Arduino Nano ESP32 Code #1

/* * This Arduino Nano ESP32 code was developed by newbiely.com * * This Arduino Nano ESP32 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-nano-esp32/communication-between-two-arduino-nano-esp32-via-mqtt */ // ESP32 #1: CONNECTED TO A BUTTON/SWITCH, ACTED AS A MQTT PUBLISHER #include <WiFi.h> #include <MQTTClient.h> #include <ezButton.h> #define BUTTON_PIN D2 // The Arduino Nano ESP32 pin connected to the button 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.5"; // CHANGE TO MQTT BROKER'S IP ADDRESS const int MQTT_PORT = 1883; const char MQTT_CLIENT_ID[] = "esp32-001"; // 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 ESP32 should publish/subscribe const char MQTT_TOPIC[] = "esp32/command"; // CHANGE IT AS YOU DESIRE WiFiClient network; MQTTClient mqtt = MQTTClient(256); ezButton button(BUTTON_PIN); // create ezButton that attach to pin 7 void setup() { Serial.begin(9600); button.setDebounceTime(100); // set debounce time to 100 milliseconds Serial.println("Arduino Nano ESP32 #1: CONNECTED TO A BUTTON/SWITCH, ACTED AS A MQTT PUBLISHER"); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.println("Arduino Nano ESP32 - Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); connectToMQTT(); } void loop() { mqtt.loop(); button.loop(); // MUST call the loop() function first if (button.isPressed()) { Serial.println("- The button is pressed, send command: 1"); sendToMQTT('1'); } if (button.isReleased()) { Serial.println("- The button is released, send command: 0"); sendToMQTT('0'); } } void connectToMQTT() { // Connect to the MQTT broker mqtt.begin(MQTT_BROKER_ADRRESS, MQTT_PORT, network); Serial.print("Arduino Nano ESP32 - 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 Nano ESP32 - MQTT broker Timeout!"); return; } Serial.println("Arduino Nano ESP32 - MQTT broker Connected!"); } void sendToMQTT(char command) { char messageBuffer[1]; messageBuffer[0] = command; mqtt.publish(MQTT_TOPIC, messageBuffer); Serial.println("Arduino Nano ESP32 - sent to MQTT:"); Serial.print("- topic: "); Serial.println(MQTT_TOPIC); Serial.print("- payload:"); Serial.println(messageBuffer); }

Arduino Nano ESP32 Code #2

/* * This Arduino Nano ESP32 code was developed by newbiely.com * * This Arduino Nano ESP32 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-nano-esp32/communication-between-two-arduino-nano-esp32-via-mqtt */ // ESP32 #2: CONNECTED TO A LED, ACTED AS A MQTT SUBSCRIBER #include <WiFi.h> #include <MQTTClient.h> #define LED_PIN D5 // The Arduino Nano ESP32 pin connected to LED 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.5"; // CHANGE TO MQTT BROKER'S IP ADDRESS const int MQTT_PORT = 1883; const char MQTT_CLIENT_ID[] = "esp32-002"; // 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 ESP32 should publish/subscribe const char MQTT_TOPIC[] = "esp32/command"; // CHANGE IT AS YOU DESIRE WiFiClient network; MQTTClient mqtt = MQTTClient(256); void setup() { Serial.begin(9600); pinMode(LED_PIN, OUTPUT); Serial.println("Arduino Nano ESP32 #2: CONNECTED TO A LED, ACTED AS A MQTT SUBSCRIBER"); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.println("Arduino Nano ESP32 - Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); connectToMQTT(); } void loop() { mqtt.loop(); } void connectToMQTT() { // Connect to the MQTT broker mqtt.begin(MQTT_BROKER_ADRRESS, MQTT_PORT, network); // Create a handler for incoming messages mqtt.onMessage(messageReceived); Serial.print("Arduino Nano ESP32 - 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 Nano ESP32 - MQTT broker Timeout!"); return; } // Subscribe to a topic, the incoming messages are processed by messageReceived() function if (mqtt.subscribe(MQTT_TOPIC)) Serial.print("Arduino Nano ESP32 - Subscribed to the topic: "); else Serial.print("Arduino Nano ESP32 - Failed to subscribe to the topic: "); Serial.println(MQTT_TOPIC); Serial.println("Arduino Nano ESP32 - MQTT broker Connected!"); } void messageReceived(String &topic, String &payload) { Serial.println("Arduino Nano ESP32 - received from MQTT:"); Serial.println("- topic: " + topic); Serial.print("- payload: "); Serial.println(payload); char command = payload[0]; if (command == '1') { Serial.print("- Received command: "); Serial.print(command); Serial.println(" => Turned LED on"); digitalWrite(LED_PIN, HIGH); // Turn LED on } else if (command == '0') { Serial.print("- Received command: "); Serial.print(command); Serial.println(" => Turned LED off"); digitalWrite(LED_PIN, LOW); // Turn LED off } else { Serial.print("- Received an unsupported command: "); Serial.println(command); } }

Detailed Instructions

To get started with Arduino Nano ESP32, follow these steps:

  • If you are new to Arduino Nano ESP32, refer to the tutorial on how to set up the environment for Arduino Nano ESP32 in the Arduino IDE.
  • Wire the components according to the provided diagram.
  • Connect the Arduino Nano ESP32 board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the Arduino Nano ESP32) board and its corresponding COM port.
  • Wire a button/switch to Arduino Nano ESP32 #1
  • Wire an LED to Arduino Nano ESP32 #2
  • Open Arduino IDE (called Arduino IDE #1)
  • Open another Arduino IDE window (called Arduino IDE #2) by clicking on Arduino IDE icon on your PC (important!(**))
  • Open the Library Manager by clicking on the Library Manager icon on the left navigation bar of Arduino IDE
  • Type MQTT on the search box, then look for the MQTT library by Joel Gaehwiler.
  • Click Install button to install MQTT library.
Arduino Nano ESP32 MQTT library
  • Type ezButton on the search box, then find the button library by Arduino Nano ESP32GetStarted
  • Click Install button to install ezButton library.
Arduino Nano ESP32 button library
  • Connect Arduino Nano ESP32 #1 to PC via USB cable and select COM port of Arduino Nano ESP32 #1 on Arduino IDE #1
  • Connect Arduino Nano ESP32 #2 to PC via USB cable and select COM port of Arduino Nano ESP32 #2 on Arduino IDE #2
  • Copy Arduino Nano ESP32 #1 code, paste to Arduino IDE #1 and save it (named Arduino Nano ESP32-1)
  • Copy Arduino Nano ESP32 #2 code, paste to Arduino IDE #2 and save it (named Arduino Nano ESP32-2)
  • Replace the WiFi information (SSID and password) in both codes with your own.
  • Replace the MQTT broker address in both codes (domain name or IP address).
  • Upload Arduino Nano ESP32 #1 code to Arduino Nano ESP32 #1
  • Upload Arduino Nano ESP32 #2 code to Arduino Nano ESP32 #2
  • Open Serial Monitor on Arduino IDE #1
  • Open Serial Monitor on Arduino IDE #2
  • Press and hold the button on Arduino Nano ESP32 #1 → see LED's state on Arduino Nano ESP32 #2 (ON)
  • Release button on Arduino Nano ESP32 #1 → see LED's state on Arduino Nano ESP32 #2 (OFF)
  • Press, hold, and release the button several times.
  • See output on both Serial Monitors
    • Serial Monitor of Arduino Nano ESP32 #1
    COM6
    Send
    Arduino Nano ESP32 #1: CONNECTED TO A BUTTON/SWITCH, ACTED AS A MQTT PUBLISHER Arduino Nano ESP32 - Attempting to connect to SSID: YOUR_WIFI_SSID Arduino Nano ESP32 - Connecting to MQTT broker Arduino Nano ESP32 - MQTT broker Connected! - The button is pressed, send command: 1 Arduino Nano ESP32 - sent to MQTT: - topic: arduino/command - payload:1 - The button is released, send command: 0 Arduino Nano ESP32 - sent to MQTT: - topic: arduino/command - payload:0
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  
    • Serial Monitor of Arduino Nano ESP32 #2
    COM6
    Send
    Arduino Nano ESP32 #2: CONNECTED TO A LED, ACTED AS A MQTT SUBSCRIBER Arduino Nano ESP32 - Attempting to connect to SSID: YOUR_WIFI_SSID Arduino Nano ESP32 - Connecting to MQTT broker Arduino Nano ESP32 - Subscribed to the topic: arduino/command Arduino Nano ESP32 - MQTT broker Connected! Arduino Nano ESP32 - received from MQTT: - topic: arduino/command - payload: 1 - Received command: 1 => Turned LED on Arduino Nano ESP32 - received from MQTT: - topic: arduino/command - payload: 0 - Received command: 0 => Turned LED off
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  

※ 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!