Connecting an Arduino UNO R4 WiFi to Home Assistant with MQTT Source
Markdown source•
1---2title: "Connecting an Arduino UNO R4 WiFi to Home Assistant with MQTT"3date: "2026-09-13"4published: true5tags: ["home-assistant", "arduino", "mqtt", "electronics", "iot", "automation"]6author: "Gavin Jackson"7excerpt: "A complete tutorial for bringing an Arduino UNO R4 WiFi into Home Assistant with ArduinoMqttClient, MQTT discovery, two onboard controls and two useful sensors."8---910# Connecting an Arduino UNO R4 WiFi to Home Assistant with MQTT11121314*The UNO R4 WiFi used in this tutorial, with its onboard LED and 12 × 8 LED matrix illuminated.*1516After using ESPHome to bring three ESP32 devices into Home Assistant, I wanted to understand the more explicit route: have a board describe its own entities, receive commands and report state through MQTT.1718This tutorial connects an Arduino UNO R4 WiFi to Home Assistant using ArduinoMqttClient and MQTT discovery. It needs no external components. By the end, Home Assistant will have two controls for the UNO's onboard hardware and two diagnostic sensors.1920The earlier experiments and their ESPHome source files are in [Three Small ESP32 Devices, One Home Assistant](/post/three-small-esp32-devices-home-assistant). This article concentrates on the Arduino and MQTT setup.2122I run Home Assistant and ESPHome as Docker Compose services with host networking. The tutorial keeps that arrangement and adds a Mosquitto container to provide the broker required by the UNO.2324## Why the UNO R4 WiFi takes a different route2526The [Arduino UNO R4 WiFi](https://docs.arduino.cc/hardware/uno-r4-wifi/) has two processors with different jobs. The Arduino sketch runs on a **Renesas RA4M1**. An **ESP32-S3** provides wireless connectivity through the board's connectivity firmware.2728For this tutorial, select the UNO R4 WiFi in the Arduino IDE and upload a normal Arduino sketch. Leave the connectivity firmware in place; flashing a generic ESP32 ESPHome configuration onto the coprocessor is a different project.2930We will use **ArduinoMqttClient**, Arduino's MQTT library. Its client class is named `MqttClient`, and it works over the `WiFiClient` supplied by the UNO R4's `WiFiS3` library. This is the specific library to install when following the tutorial; other Arduino MQTT libraries have different APIs. [Arduino's library repository](https://github.com/arduino-libraries/ArduinoMqttClient) contains its examples and source.3132MQTT uses a **broker** to pass messages between clients. Both the Arduino and Home Assistant connect to that broker. A **topic** is the address for a message, such as the command to turn an LED on. **Discovery messages** describe the board's entities so Home Assistant can create them automatically.3334{{mermaid:uno-r4-mqtt}}3536Everything in this example runs over the local network. An Arduino Cloud account is not required.3738## What we will expose3940You only need the UNO R4 WiFi and a USB-C data cable for the hardware side. No additional sensors or wiring are required.4142| Home Assistant entity | Type | What it does |43| --- | --- | --- |44| Onboard LED | Switch | Turns the built-in D13 LED on or off. |45| LED matrix | Switch | Shows a pattern on the onboard 12 × 8 LED matrix, or clears it. |46| Wi-Fi signal | Sensor | Reports received signal strength in dBm. |47| Uptime | Sensor | Reports how many seconds the sketch has been running. |4849The LED controls let us test commands going to the board. The two sensors demonstrate information coming back. They are board diagnostics rather than environmental measurements.5051You will also need a working Home Assistant installation, a 2.4 GHz Wi-Fi network, and an MQTT broker reachable from both the board and Home Assistant.5253## 1. Set up the MQTT broker5455If you already have a working MQTT broker connected to Home Assistant, reuse it and move to the Arduino setup. The examples below assume a fresh broker.5657### Add Mosquitto to docker-compose.yml5859Here is the complete `docker-compose.yml` for the Linux host, with the Mosquitto MQTT broker added alongside Home Assistant and ESPHome:6061```yaml62services:63 homeassistant:64 container_name: homeassistant65 image: "ghcr.io/home-assistant/home-assistant:stable"66 volumes:67 - /opt/home-assistant/config:/config68 - /etc/localtime:/etc/localtime:ro69 - /run/dbus:/run/dbus:ro70 restart: unless-stopped71 stop_grace_period: 60s72 privileged: true73 network_mode: host74 environment:75 TZ: Australia/Sydney7677 esphome:78 container_name: esphome79 image: ghcr.io/esphome/esphome:stable80 volumes:81 - /opt/home-assistant/esphome-config:/config82 - /etc/localtime:/etc/localtime:ro83 restart: unless-stopped84 network_mode: host8586 mosquitto:87 container_name: mosquitto88 image: eclipse-mosquitto:289 volumes:90 - /opt/home-assistant/mosquitto/config:/mosquitto/config91 - /opt/home-assistant/mosquitto/data:/mosquitto/data92 - /opt/home-assistant/mosquitto/log:/mosquitto/log93 restart: unless-stopped94 network_mode: host95```9697All three services use host networking, so Mosquitto listens directly on the Docker host without a `ports:` mapping. ESPHome continues to provide Device Builder for the earlier projects; the UNO communicates through Mosquitto.9899### Prepare the broker configuration and accounts100101Before starting Mosquitto, create its directories and configuration. These mount points follow the [official Eclipse Mosquitto container layout](https://hub.docker.com/_/eclipse-mosquitto/):102103```bash104sudo mkdir -p /opt/home-assistant/mosquitto/{config,data,log}105106sudo tee /opt/home-assistant/mosquitto/config/mosquitto.conf >/dev/null <<'EOF'107persistence true108persistence_location /mosquitto/data/109log_dest stdout110111listener 1883112allow_anonymous false113password_file /mosquitto/config/password_file114EOF115116sudo chown -R 1883:1883 /opt/home-assistant/mosquitto117```118119The official image runs Mosquitto as user and group ID `1883`, so that ownership lets it write retained data and read its configuration through the bind mounts. The image's [Docker README](https://github.com/eclipse-mosquitto/mosquitto/blob/master/docker/generic/README.md) documents the container user and mount points.120121Create separate broker accounts for the UNO and Home Assistant. Each command prompts for a password, so the passwords do not appear in shell history:122123```bash124sudo docker run --rm -it --user 1883:1883 \125 -v /opt/home-assistant/mosquitto/config:/mosquitto/config \126 --entrypoint mosquitto_passwd \127 eclipse-mosquitto:2 \128 -c /mosquitto/config/password_file uno_r4129130sudo docker run --rm -it --user 1883:1883 \131 -v /opt/home-assistant/mosquitto/config:/mosquitto/config \132 --entrypoint mosquitto_passwd \133 eclipse-mosquitto:2 \134 /mosquitto/config/password_file ha_mqtt135136sudo chmod 600 /opt/home-assistant/mosquitto/config/password_file137```138139Use `-c` only for the first account because it creates or overwrites the file. The second command adds another user. These are MQTT broker accounts, separate from Home Assistant users; the [Mosquitto password utility documentation](https://mosquitto.org/man/mosquitto_passwd-1.html) explains the distinction and options.140141### Start Mosquitto and connect Home Assistant142143From the directory containing `docker-compose.yml`, start the new broker service:144145```bash146sudo docker compose up -d mosquitto147sudo docker compose logs --tail=50 mosquitto148```149150The broker log should show a listener on port `1883`. Because all three containers use host networking, Home Assistant can reach Mosquitto at `127.0.0.1:1883`. In **Settings → Devices & services**, choose **Add integration → MQTT** and enter that address with the `ha_mqtt` credentials. MQTT discovery is enabled by default. The [Home Assistant MQTT documentation](https://www.home-assistant.io/integrations/mqtt/) covers the same manual broker setup.151152The Arduino is outside Docker, so it must use the **LAN IP address of the Docker host**, port `1883`, and the `uno_r4` credentials. Allow TCP 1883 from the trusted LAN if the host has a firewall. A DHCP reservation for the Docker host keeps that address stable.153154> **Keep this example on your local network**155>156> The sketch uses authenticated MQTT on port 1883 without TLS, so MQTT credentials and messages are not encrypted in transit. Keep that listener restricted to your trusted LAN and do not forward it from the internet. TLS requires a suitable client and certificate configuration as well as a broker listener; changing the port alone does not enable it.157158## 2. Prepare the Arduino IDE159160Install the [Arduino IDE](https://www.arduino.cc/en/software), connect the UNO R4 WiFi with a data-capable USB cable, and then:1611621. Open **Boards Manager** and install **Arduino UNO R4 Boards** by Arduino (also known as the Arduino Renesas UNO board package).1632. Select **Arduino UNO R4 WiFi** and its USB port in the board selector.1643. Open **Library Manager** and install **ArduinoMqttClient** by Arduino.165166`WiFiS3` and `Arduino_LED_Matrix` come with the board package. The sketch uses the matrix library directly, so it does not need a graphics library. Arduino documents the board's [Wi-Fi examples](https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples/) and [LED matrix](https://docs.arduino.cc/tutorials/uno-r4-wifi/led-matrix/) separately if you want to explore either feature.167168## 3. Download the sketch and add your credentials169170Download the [complete UNO R4 WiFi sketch](/assets/code/uno-r4-wifi-home-assistant/uno-r4-wifi-home-assistant.ino) and the [example credentials header](/assets/code/uno-r4-wifi-home-assistant/arduino_secrets.h.example). If your browser displays either file as text, save it using the filename shown below.171172Keep the sketch in a folder with the same name, and rename the example header to `arduino_secrets.h`:173174```text175uno-r4-wifi-home-assistant/176├── uno-r4-wifi-home-assistant.ino177└── arduino_secrets.h178```179180Edit `arduino_secrets.h` with your own details:181182```cpp183#pragma once184185#define SECRET_SSID "YOUR_WIFI_NAME"186#define SECRET_PASS "YOUR_WIFI_PASSWORD"187#define SECRET_MQTT_HOST "192.168.1.10"188#define SECRET_MQTT_PORT 1883189#define SECRET_MQTT_USER "uno_r4"190#define SECRET_MQTT_PASS "YOUR_MQTT_PASSWORD"191```192193Use the broker's LAN IP address for `SECRET_MQTT_HOST`. `localhost` would mean the Arduino itself. If Mosquitto runs separately from Home Assistant, use that broker machine's address. A DHCP reservation for the broker avoids having to update and re-upload the sketch when its address changes.194195Keep your filled-in credentials file out of source control and out of any public web directory. Open the sketch from your local Arduino projects folder.196197The sketch has a device ID of `uno_r4_wifi_01`. Leave that alone for your first board. For a second board, change `DEVICE_ID` before uploading; each board needs its own MQTT client ID, discovery IDs and topics. The example derives those from this one value.198199## 4. Understand the useful parts of the sketch200201The download contains the complete program, including connection recovery. These excerpts explain its main jobs; upload the downloaded sketch rather than assembling the excerpts into a new program.202203```cpp204#include <WiFiS3.h>205#include <ArduinoMqttClient.h>206#include <Arduino_LED_Matrix.h>207#include "arduino_secrets.h"208209WiFiClient wifiClient;210MqttClient mqttClient(wifiClient);211ArduinoLEDMatrix matrix;212```213214`WiFiClient` provides the network connection. `MqttClient` handles publishing and subscribing. The LED matrix object controls the board's display.215216### Discovery creates one device with four entities217218On connecting, the board publishes a configuration for each entity under Home Assistant's default `homeassistant` discovery prefix. For example, the LED configuration goes to:219220```text221homeassistant/switch/uno_r4_wifi_01/led/config222```223224Each entity has its own `unique_id`, while all four share a device identifier. That groups the switches and sensors under a single UNO device in Home Assistant. The sketch publishes these configurations automatically; there is no manual entity YAML to add. Home Assistant describes the message format in its [MQTT discovery documentation](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery).225226### Commands and reported state use separate topics227228For the onboard LED, the topic pair is:229230```text231arduino/uno_r4_wifi_01/led/set Home Assistant sends ON or OFF232arduino/uno_r4_wifi_01/led/state Arduino reports ON or OFF233```234235The board handles the command, changes the output, and publishes its resulting state. The matrix follows the same pattern. This uses Home Assistant's [MQTT switch state confirmation](https://www.home-assistant.io/integrations/switch.mqtt/) so the dashboard reflects the board's reply.236237The message handler updates the LED and flags that there is a new state to publish:238239```cpp240if (topic == ledCommandTopic) {241 ledOn = turnOn;242 digitalWrite(LED_BUILTIN, ledOn ? HIGH : LOW);243 stateDirty = true;244}245```246247For the matrix, the sketch uses an 8-row, 12-column bitmap of a little house:248249```cpp250if (matrixOn) {251 matrix.renderBitmap(house, 8, 12);252} else {253 matrix.clear();254}255```256257The `house` array is included in the download. Change its zeroes and ones to draw your own pattern.258259### Recovery is part of the example260261Discovery and reported states are **retained**: the broker stores their most recent values for new subscribers. Commands are **not retained**, so an old command is not replayed when a board reconnects.262263The sketch also registers an MQTT **Last Will** of `offline`, publishes `online` when ready, and listens for Home Assistant's birth message on `homeassistant/status` so it can announce its entities again. Home Assistant documents these [startup and availability behaviours](https://www.home-assistant.io/integrations/mqtt/#birth-and-last-will-messages).264265The main loop polls the MQTT client frequently and spaces out reconnection attempts. A long `delay()` between sensor readings would also delay incoming commands and connection maintenance. Sensor updates use a 30-second timer instead. Connection and acknowledgement waits still use synchronous library calls; this is a small tutorial sketch, not a real-time controller.266267## 5. Upload and find the device268269Click **Verify** in the IDE, then **Upload**. Open **Serial Monitor** at **115200 baud** to follow the Wi-Fi and MQTT connection messages.270271Once the board connects, open **Settings → Devices & services → MQTT** in Home Assistant and look for the UNO device. Open it to find the two switches and two diagnostic sensors. Assign it to an area such as Study, then add the entities to a dashboard if desired.272273Try each control:2742751. Turn **Onboard LED** on and off, and check the D13 LED on the board.2762. Turn **LED matrix** on to show the pattern, then off to clear it.2773. Watch **Uptime** increase and **Wi-Fi signal** update. A value closer to zero means a stronger received signal: `-50 dBm` is stronger than `-75 dBm`.278279Reset the board and confirm that it reconnects. Both outputs start off after a reset; the sketch reports that fresh state to Home Assistant. A temporary network reconnection does not itself reset the outputs.280281Unplug the board to check availability. Home Assistant should eventually mark its entities unavailable after the broker detects the lost connection; this is not necessarily immediate. Reconnect the USB cable and check that the board returns. Restarting Home Assistant's MQTT integration is another useful check that discovery and state recover.282283> **Example validation**284>285> The downloadable sketch has been compiled for `arduino:renesas_uno:unor4wifi` using board package 1.6.0 and ArduinoMqttClient 0.1.8. The screenshots below show the UNO's two controls, diagnostic readings and state changes in Home Assistant. Use the checks above to verify reconnection and availability on your own network.286287## If something does not appear288289| Symptom | What to check |290| --- | --- |291| `WiFiS3.h` or `Arduino_LED_Matrix.h` is missing | Install the UNO R4 board package and select UNO R4 WiFi, not UNO R3 or a generic ESP32. |292| `ArduinoMqttClient.h` is missing | Install ArduinoMqttClient by Arduino in Library Manager. |293| Wi-Fi never connects | Check the SSID, password, 2.4 GHz coverage and the connection messages in Serial Monitor. |294| Wi-Fi connects but MQTT fails | Check the broker's LAN IP, port, username and password. Allow TCP 1883 between the board and broker; guest Wi-Fi isolation can block it. Check the broker logs for authentication failures. |295| MQTT connects but no device appears | Confirm Home Assistant uses the same broker and that MQTT discovery is enabled with the default `homeassistant` prefix. |296| Switches appear but do not respond | Listen to the command and state topics, check the board is online, and confirm it is receiving `ON` or `OFF`. |297| Two boards keep disconnecting | Give each board a different `DEVICE_ID`; MQTT client IDs must be unique. |298| Old entities return after renaming a device | The broker still holds the old retained discovery messages. Stop the old publisher and publish an empty retained payload to each old entity's exact `.../config` topic. |299300The MQTT integration's **Configure** screen includes **Listen to a topic**. Listening to `arduino/uno_r4_wifi_01/#` lets you see the example's traffic. To inspect discovery, listen to `homeassistant/+/uno_r4_wifi_01/+/config`. The `#` wildcard includes all topics below a prefix; `+` matches one topic level.301302You can also use that screen to publish `ON` to `arduino/uno_r4_wifi_01/led/set`. Leave **Retain** off for this command. The LED should change and the board should publish `ON` on its state topic.303304If the IDE reports that the UNO's connectivity firmware needs updating, use Arduino's [Firmware Updater instructions](https://support.arduino.cc/hc/en-us/articles/9670986058780-Update-the-connectivity-module-firmware-on-UNO-R4-WiFi). The update overwrites the current sketch. **Disconnect and reconnect the board after the firmware update**, then upload the tutorial sketch again.305306## From an LED to something useful307308An LED is a good first test because the result is visible. Once the two-way connection works, the same approach can publish readings from an attached sensor or show an automation's status on the matrix. Give each new entity a unique ID, define its command or state topic, and let discovery describe it to Home Assistant.309310Writing this small MQTT client shows what an integration needs to do: describe the device's features, receive commands, report the resulting state and recover when either end restarts. There is plenty to learn from making a board on the bench respond to a switch on the phone.311312313314*It's a beautiful thing when a plan comes together!*315316317318*The UNO R4 WiFi joins the LILYGO T-Embed, Nano ESP32 and Waveshare RLCD on the Study dashboard.*319