The provided code is for a DIY Sonoff project, like a remote controlled power switch. It uses the ESP8266 WiFi chip and MQTT protocol to connect to Adafruit.io and control a relay.
Here's a breakdown of the code:
Libraries:
ESP8266WiFi.h
: Provides WiFi connectivity functions for ESP8266 chip.Adafruit_MQTT.h
andAdafruit_MQTT_Client.h
: Libraries for using MQTT protocol with Adafruit.io.
Configuration:
- WiFi SSID and password for connecting to your WiFi network.
- Adafruit.io username, key, and server details for MQTT communication.
- Pin connected to the relay controlling the power.
Objects:
client
: WiFiClient object for connecting to the MQTT server.mqtt
: Adafruit_MQTT_Client object for handling MQTT communication.onoffbutton
: Adafruit_MQTT_Subscribe object for subscribing to the "diysonoff" feed on Adafruit.io.
Functions:
MQTT_connect()
: Function to connect or reconnect to the MQTT server.setup()
: Sets up WiFi connection, serial communication, pin mode for the relay, and subscribes to the "diysonoff" feed.loop()
: Main loop that keeps the connection alive, checks for incoming messages on the subscribed feed, and controls the relay based on received message.
Functionality:
- The code connects to the specified WiFi network.
- It connects to the Adafruit.io MQTT server using the provided credentials.
- It subscribes to a feed named "diysonoff" on Adafruit.io.
- In the loop, it continuously checks for incoming messages on the subscribed feed.
- If a message is received, it converts the message to a number using
atoi
and sets the relay pin high (ON) if the number is 1, or low (OFF) if the number is 0. - It keeps the connection alive by pinging the MQTT server periodically (commented out in this code).
Overall, this code allows you to control a relay (power switch) remotely by publishing messages to the "diysonoff" feed on Adafruit.io. You can use a separate program or smartphone app to publish messages (0 or 1) to that feed to turn the relay on or off.