Introduction: Use MQTT Client in Arduino

In this project we will set up in Arduino a MQTT Client that will receive messages and will be able to turn on and off LED lights.

Due to COVID-19!! I could not have all the equipment at my disposal except one Arduino Mega and One Ethernet Shield (Ethernet_Shield_W5100). But by modifying the code a bit you can add sensors get the values of these sensors and send it to other arduino, or you can send values to turn on lights and whatever else you can think of.

Equipment:

-Mega

-Ethernet Shield

Step 1: Set Up Mqtt Server

I would like to set up the mqtt server on a raspberry but I do not have it in my parent home and I had to set it to a viirtual machine kali linux.
The install mqtt conf set username password and topics

1 step sudo apt-get update sudo apt-get install mosquitto

2. If you have just installed the Mosquitto broker, make sure its stopped (to be in the safe side) sudo stop mosquitto

3. Creating the new password file Password file will contain your username and the encrypted password. Run the following command to create and add a user to this file. sudo mosquitto_passwd -c /etc/mosquitto/passwd 'user_name' sudo mosquitto_passwd -U pps Then, you will be asked for your password twice, enter that too.

add file acl.txt user name topic readwrite nametopic/#

4. Open the mosquitto.conf file using the following command, sudo vim /etc/mosquitto/mosquitto.conf And add following two entries to the mosquitto.conf file,

-allow_anonymous false -password_file /etc/mosquitto/pass.txt -acl_file /etc/mosquitto/acl.txt

5. Now start the broker with the following command, mosquitto -c /etc/mosquitto/mosquitto.conf

6. If you need to verify the authentication, you can use following command, (you have to install mosquitto clients to do this sudo apt-get install mosquitto-client)

mosquitto_sub -h localhost -p 1883 -t myTopic -u 'user_name' -P mosquitto_pub -h localhost -p 1883 -t topic/ -u user -P user -m "message"

Step 2: Now Code for Arduino

The code is simple and can be found here git.

With appropriate changes you can add your own variables and be taken to the arduo and perform actions. For example, send to Arduino the pin in which you have a led and tell him on or off, depending on value it will turn off or on.

Step 3: Finall

In the last minute of the previous video you can see how I send the message from Kali and receive it the Arduino and show in serial monitor the value of message.
to subscribe in topic use this command: mosquitto_sub -h localhost -p 1883 -t myTopic -u 'user_name' -P 'password'

To send a message in topic use this command: mosquitto_pub -h localhost -p 1883 -t topic/ -u 'user_name' -P 'password' -m "message"

Thanks for taking the time to read this short project. Reason COVID-19 I do not have the equipment with me. In the future and at the end of COVID-19 it will become a forerunner with Arduinos and raspberry for home automation.

Be Safe