logo elektroda
logo elektroda
X
logo elektroda

How to connect Arduino R4 WiFi to Home Assistant via MQTT? ArduinoMqttClient tutorial

p.kaczmarek2 12306 3

TL;DR

  • Arduino R4 WiFi connects to Home Assistant through MQTT using the ArduinoMqttClient library.
  • The sketch joins WiFi, logs into the MQTT broker with username and password, subscribes to a topic, and handles incoming messages in a callback.
  • The first MQTT connection attempt returns error -2.
  • Home Assistant sees the data published by Arduino, and Arduino also receives messages from Home Assistant, so communication works both ways.
  • Without calling subscribe() for a topic, messages sent to it will not be received.
Generated by the language model.
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
📢 Listen (AI):
  • Arduino R4 WiFi with MQTT logo on a wooden table
    I will show here how you can connect Arduino R4 WiFi to Home Assistant via MQTT in order to receive and send data via MQTT publish. I will use the ArduinoMqttClient library for this. The sample code that I will post here first connects to our WiFi network, then connects to our MQTT broker via login and password, and finally subscribes to the given MQTT topic and listens to messages on it, while also publishing data from itself.

    The theme is based on the new Arduino R4 WiFi board:
    Arduino UNO R4 WiFi lying on a wooden surface.
    On the software side I used ArduinoMqttClient:
    https://www.arduino.cc/reference/en/libraries/arduinomqttclient/
    https://github.com/arduino-libraries/ArduinoMqttClient
    The library must be installed via Libraries:
    Screenshot of the Arduino Library Manager with the ArduinoMqttClient library installed.
    Then we can run the sample code that we'll write together in a moment.
    At the beginning, we attach the headers and define the constants (directions for WiFi and MQTT server):
    Code: C / C++
    Log in, to see the code

    Next, we create instances of WiFi and MQTT clients globally:
    Code: C / C++
    Log in, to see the code

    Next, in setup, we run everything:
    Code: C / C++
    Log in, to see the code

    The above code activates the serial port so you can watch what the Arduino is doing in the Serial Monitor.
    Then we start WiFi:
    Code: C / C++
    Log in, to see the code

    In the loop, we try to connect as a client to the wireless network. When the connection is successful, we print our IP:
    Code: C / C++
    Log in, to see the code

    Then we run MQTT:
    Code: C / C++
    Log in, to see the code

    We try to connect in a loop. The first connection fails with error -2. I based the code on ArduinoMqttClient examples and Arduino Forum discussions and it seems that everyone has this problem.
    Then we subscribe to the MQTT topics that interest us and set the callback that the MQTT library will call when it receives some data:
    Code: C / C++
    Log in, to see the code

    Without executing subscribe for a given topic, we will not receive data sent to it!
    The continuation takes place in the aforementioned callback. It is called only when we receive some data:
    Code: C / C++
    Log in, to see the code

    In this callback, you can freely process the received data, switch the relay, etc.

    There is still the main loop - you need to refresh the MQTT client there, I also publish the time from Arduino there:
    Code: C / C++
    Log in, to see the code

    That's all. We save and upload to Arduino. Home Assistant assumes it's already on. We enter the MQTT tool, Home Assistant sees the information published by Arduino:
    Screenshot of MQTT settings in Home Assistant with publishing and listening messages.
    Arduino also sees what HA will post:
    Screenshot showing Arduino R4 WiFi communication with an MQTT broker in Home Assistant.
    Communication works fine both ways.
    Full code:
    Spoiler:
    Code: C / C++
    Log in, to see the code


    Summary
    Arduino R4 WiFi has just entered the market and already offers ready-made mechanisms that allow you to easily connect to an MQTT broker, for example, such as in Home Assistant. Subscribing to an MQTT topic and publishing data on a selected topic also works perfectly fine. Therefore, nothing stands in the way of being able to easily connect our projects to the IoT network and I mean even our older projects, from before R4, because the migration from Uno R3 to R4 WiFi is also not that difficult.
    Do you see any potential uses for MQTT on R4? I invite you to the discussion.

    Cool? Ranking DIY
    Helpful post? Buy me a coffee.
    About Author
    p.kaczmarek2
    Moderator Smart Home
    Offline 
    p.kaczmarek2 wrote 14615 posts with rating 12631, helped 655 times. Been with us since 2014 year.
  • ADVERTISEMENT
  • #2 20696218
    krzbor
    Level 29  
    Posts: 1756
    Help: 41
    Rate: 1064
    I wonder how it will behave in the event of loss of communication with the broker, i.e. in the case of:
    - network (or WiFi) problem
    - problem with the broker itself (e.g. temporary shutdown of the computer with the broker, restart of the broker, etc.)
    I'm afraid that the device with this client will not come back to life without a reboot.

    By the way - what MQTT client do you recommend for ESP8266 (Arduino)? I found something like this link . It has interesting properties:

    Connecting to a WiFi network.
    Connecting to a MQTT broker.
    Automatically detecting connection lost either from the WiFi client or the MQTT broker and it will retry a connection automatically.
    Subscribing/unsubscribing to/from MQTT topics by a friendly callback system.
    Supports wildcards (+, #) in subscriptions
    Provide a callback handling to advise once everything is connected (Wifi and MQTT).
    Provide a function to enable printing of useful debug information related to MQTT and Wifi connections.
    Provide some other useful utilities for MQTT and Wifi management.
    Provide a function to enable an HTTP Update server secured by a password to allow remote update.
    Provide a function to enable OTA secured by a password to allow remote update.

    I would like to create something universal on Arduino based on WiFiManager (it works well for me), OTA (it works well for me too) and of course the MQTT client - here I need a proven, reliable library resistant to everything that may happen (problem with WiFi, network, broker, etc.). If you can recommend something (something that works long and reliably) then write.
  • ADVERTISEMENT
  • #3 21095561
    george7
    Level 1  
    Posts: 1
    Includes are missing.
  • #4 21095569
    p.kaczmarek2
    Moderator Smart Home
    Posts: 14615
    Help: 655
    Rate: 12631
    I apologize for the confusion, it seems that the translation software broke the part of the code.
    I will fix it right away, but you can also check the source material on the polish site:
    https://www.elektroda.pl/rtvforum/topic3996085.html#21095561
    The code is complete there.
    Helpful post? Buy me a coffee.
📢 Listen (AI):

FAQ

TL;DR: With 2 headers and port 1883, “communication works fine both ways.” This FAQ helps Arduino Uno R4 WiFi users connect Home Assistant over MQTT with ArduinoMqttClient: join Wi‑Fi, log in to the broker, subscribe to a topic, call mqttClient.poll(), and publish values such as millis() to ArduinoTime. [#20695180]

Why it matters: It turns a new Uno R4 WiFi into a practical Home Assistant node using a short, readable MQTT sketch.

Cecha ArduinoMqttClient EspMQTTClient
Pokazane w wątku na Uno R4 WiFi ESP8266
Automatyczne ponowne łączenie Nie pokazano Deklarowane w opisie
Wildcards + i # Nie wspomniano Wspomniane
Pomoc dla OTA / HTTP Update Nie wspomniano Wspomniana

Key insight: Publishing alone is not enough. You must subscribe to the topic and call mqttClient.poll() regularly, or incoming Home Assistant messages will not be processed.

Quick Facts

  • The example uses #include <WiFiS3.h> and #include <ArduinoMqttClient.h>, so both headers are required for compilation on Uno R4 WiFi. [#20695180]
  • The MQTT broker settings shown are a local IP 192.168.0.113, port 1883, plus username and password authentication. [#20695180]
  • Serial output starts at 9600 baud, which lets you watch Wi‑Fi join attempts, broker login, and received payloads in Serial Monitor. [#20695180]
  • The sketch retries Wi‑Fi every 1000 ms, retries MQTT connect every 100 ms, and publishes millis() every 10 loop passes with a 100 ms delay. [#20695180]
  • A later reply confirms the originally posted full code had broken include lines after translation, not a library issue. [#21095569]

How do I connect an Arduino Uno R4 WiFi to Home Assistant through MQTT using the ArduinoMqttClient library?

Connect in four parts: Wi‑Fi, broker login, topic subscription, and regular polling. The shown sketch joins Wi‑Fi with WiFi.begin(), connects to broker 192.168.0.113:1883, authenticates with username and password, subscribes to ArduinoR4, and publishes time data to ArduinoTime. Home Assistant then sees published messages, and Arduino receives subscribed ones through the callback. [#20695180]

Why does ArduinoMqttClient sometimes fail on the first MQTT connection attempt with error code -2 on Arduino R4 WiFi?

The thread reports that the first MQTT connection can fail with error -2, even when later attempts succeed. The author says this behavior also appears in ArduinoMqttClient examples and Arduino Forum discussions, so the sketch handles it by retrying mqttClient.connect() in a loop with a 100 ms delay. [#20695180]

What code do I need on Arduino R4 WiFi to connect to Wi‑Fi, log in to an MQTT broker, subscribe to a topic, and publish messages back?

Use this 3-step structure. 1. Include WiFiS3.h and ArduinoMqttClient.h, then define SSID, password, host, port 1883, and topics. 2. In setup(), connect to Wi‑Fi, set client ID test123, set MQTT credentials, and loop until mqttClient.connect() succeeds. 3. Register onMessage, subscribe to ArduinoR4, call mqttClient.poll() in loop(), and publish millis() to ArduinoTime. [#20695180]

How do I subscribe to an MQTT topic on Arduino R4 WiFi so Home Assistant messages are actually received?

Call mqttClient.subscribe(TEST_TOPIC); after the broker connection succeeds and after you register the callback with mqttClient.onMessage(onMqttMessage);. The thread is explicit: without subscribe for that topic, Arduino will not receive the data sent to it, even if publishing works correctly. [#20695180]

What does mqttClient.poll() do in ArduinoMqttClient, and why does the loop need to call it regularly?

mqttClient.poll() keeps the MQTT session alive and lets the library receive incoming messages. The posted code comment says it must run regularly so the client can process MQTT traffic and send keep-alives, which helps avoid broker disconnects during normal operation. [#20695180]

How should I handle lost Wi‑Fi or broker connectivity on Arduino R4 WiFi so the MQTT client reconnects automatically without a reboot?

The posted Uno R4 sketch does not show a full auto-reconnect strategy after runtime failures. A commenter specifically worries that after Wi‑Fi loss, broker restart, or network failure, the device may not recover without rebooting, so you should treat reconnection handling as an open gap in this example. [#20696218]

Which MQTT client library is best for ESP8266 in Arduino: ArduinoMqttClient or EspMQTTClient for long-term reliability and auto-reconnect?

In this thread, EspMQTTClient is the stronger fit for ESP8266 if auto-reconnect is your priority. The post lists automatic Wi‑Fi and broker reconnection, wildcard subscriptions, debug output, OTA, and password-protected HTTP Update, while ArduinoMqttClient is only demonstrated here on Uno R4 WiFi and reconnect resilience is questioned. [#20696218]

What is an MQTT broker in the context of Home Assistant and Arduino communication?

"MQTT broker" is a server component that routes published messages to subscribed clients, centralizing topic-based communication between Home Assistant and Arduino. In the example, Arduino connects to broker 192.168.0.113 on port 1883, authenticates, subscribes to ArduinoR4, and publishes its own data back. [#20695180]

What is OTA on ESP8266 or Arduino, and how does it help with remote updates in MQTT-based projects?

"OTA" is a remote firmware update method that sends new software over the network instead of a USB cable, which is useful for deployed IoT nodes. In the thread, EspMQTTClient is described as supporting password-protected OTA and password-protected HTTP Update for remote maintenance. [#20696218]

How do I troubleshoot Arduino R4 WiFi not receiving MQTT messages even though publishing to Home Assistant works?

Check subscription first, then callback registration, then polling. The working example sets mqttClient.onMessage(onMqttMessage);, subscribes with mqttClient.subscribe(TEST_TOPIC);, and calls mqttClient.poll() in every loop. If any of those three parts is missing, outgoing publishes may still work while incoming Home Assistant messages never reach your code. [#20695180]

What's the purpose of the onMessage callback in ArduinoMqttClient, and how do I process incoming MQTT payloads inside it?

The onMessage callback runs only when Arduino receives subscribed MQTT data. In the example, onMqttMessage(int messageSize) prints the topic, prints the payload length in bytes, reads the payload with mqttClient.readString(), and stores it in a String named message so your code can act on it, such as switching a relay. [#20695180]

How can I publish periodic data like millis() from Arduino R4 WiFi to a topic such as ArduinoTime in Home Assistant?

Publish inside loop() after calling mqttClient.poll(). The sample increments g_loop, and every 10 passes it opens a message for topic ArduinoTime, prints Time= plus millis(), then ends the message. With the shown delay(100), that means a publish roughly every 1000 ms. [#20695180]

Why were the include lines missing in the posted Arduino MQTT example, and which headers are required for the code to compile?

The include lines were missing because translation software broke that part of the code in the posted version. The required headers are #include <WiFiS3.h> and #include <ArduinoMqttClient.h>, and a later reply confirms the full code remained complete on the Polish source page. [#21095569]

How do wildcard subscriptions like + and # work in MQTT clients for ESP8266 and Home Assistant?

This thread only confirms that EspMQTTClient supports wildcard subscriptions with + and #. It does not show matching examples, subscription patterns, or Home Assistant topic layouts, so the safe conclusion here is feature support exists, but the exact behavior is not documented in the thread itself. [#20696218]

What are practical use cases for MQTT on Arduino R4 WiFi, including migrating older Uno R3 projects to Home Assistant?

Use MQTT on Uno R4 WiFi when you want a project to send sensor or timer data to Home Assistant and receive commands back on subscribed topics. The author says the board had just entered the market, communication worked both ways, and even older pre-R4 projects can be moved over because migration from Uno R3 to R4 WiFi is “not that difficult.” [#20695180]
Generated by the language model.
ADVERTISEMENT