
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:

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:

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
Next, we create instances of WiFi and MQTT clients globally:
Code: c
Next, in setup, we run everything:
Code: c
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
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
Then we run MQTT:
Code: c
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
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
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
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:

Arduino also sees what HA will post:

Communication works fine both ways.
Full code:
Spoiler:
Code: c
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