Code explanation
The hardware setup is complete and the PCB is ready. It is time to write some code for our project. This code will be written in the Arduino IDE for our ESP32 development board.
The code will have the following tasks to perform:
- Connect to the pre-configured Wi-Fi network.
- Connect to the MQTT broker hosted on the same network (on the Pi, in our case).
- Pin initialization for the GPIO pins we will be using in this project.
- Subscribe to various switch topics.
- Reconnect to the MQTT server if it disconnects.
- Develop a logic to control the relays based on the payload received on those topics (in the callback function).
Points 4, 5, and 6 will run indefinitely (part of the loop()
function). The code is available on the GitHub repository of this project. Now, we will divide the code into parts to make it easier to understand, as we did before.
To import the required libraries use this code:
// Importing the required Libraries #include...