Mqtt libraryMqtt examples
Simple LED Control
Basic LED control example using DecentIoT MQTT Library
Simple LED Control
This example demonstrates the most basic usage of the DecentIoT MQTT Library - controlling an LED from your web dashboard.
Hardware Required
- ESP8266 or ESP32 development board
- LED (any color)
- 220Ω resistor
- Breadboard and jumper wires
Wiring
ESP8266/ESP32 LED Circuit
GPIO 2 → LED (+) → 220Ω Resistor → GND
Code
#include <DecentIoT.h>
#include <WiFi.h>
// MQTT Broker settings (using HiveMQ Cloud as example)
#define MQTT_BROKER "your-broker.hivemq.cloud"
#define MQTT_PORT 8883 // SSL port
#define MQTT_USERNAME "your-mqtt-username"
#define MQTT_PASSWORD "your-mqtt-password"
#define PROJECT_ID "my-iot-project"
#define USER_ID "user123"
#define DEVICE_ID "esp32-device-001"
// WiFi credentials
#define WIFI_SSID "your-wifi-ssid"
#define WIFI_PASS "your-wifi-password"
// Pin definitions
const int ledPin = 2;
// LED state handler
DECENTIOT_RECEIVE(P0) {
digitalWrite(ledPin, value);
Serial.printf("[P0] LED state = %s\n", value ? "ON" : "OFF");
}
void setup() {
Serial.begin(115200);
Serial.println("\n--- Initializing DecentIoT Device ---");
// Initialize LED pin
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Ensure LED is off initially
// User handles WiFi connection
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
Serial.println("WiFi connected!");
digitalWrite(LED_BUILTIN, HIGH);
// Now start DecentIoT (cloud connection)
DecentIoT.begin(MQTT_BROKER, MQTT_PORT, MQTT_USERNAME, MQTT_PASSWORD, PROJECT_ID, USER_ID, DEVICE_ID);
}
void loop() {
DecentIoT.run();
delay(10);
}
Dashboard Setup
- Create Project in DecentIoT web dashboard
- Add Widget: Toggle switch named
led1
- Map Widget to virtual pin
P0
- Save and test the toggle
How It Works
- Virtual Pin P0 receives commands from the dashboard
- DECENTIOT_RECEIVE(P0) macro handles incoming commands
- LED state changes based on the received value
- Serial output shows the current LED status
Testing
- Upload the code to your ESP8266/ESP32
- Open Serial Monitor (115200 baud)
- Wait for "WiFi Connected!" and "DecentIoT Initialized!" messages
- Go to your DecentIoT dashboard
- Toggle the LED switch
- Watch the LED turn on/off and see the serial output
Troubleshooting
LED not responding:
- Check wiring connections
- Verify GPIO pin number (D4 = GPIO 2)
- Check Serial Monitor for connection status
Connection issues:
- Verify WiFi credentials
- Check MQTT broker settings
- Ensure SSL/TLS port (8883) is used
Next Steps
- Sensor Monitoring Example - Add sensor readings
- Advanced Control Example - Multiple devices
- Firebase Examples - Alternative to MQTT