DecentIoT Logo
DecentIoT Docs
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

  1. Create Project in DecentIoT web dashboard
  2. Add Widget: Toggle switch named led1
  3. Map Widget to virtual pin P0
  4. Save and test the toggle

How It Works

  1. Virtual Pin P0 receives commands from the dashboard
  2. DECENTIOT_RECEIVE(P0) macro handles incoming commands
  3. LED state changes based on the received value
  4. Serial output shows the current LED status

Testing

  1. Upload the code to your ESP8266/ESP32
  2. Open Serial Monitor (115200 baud)
  3. Wait for "WiFi Connected!" and "DecentIoT Initialized!" messages
  4. Go to your DecentIoT dashboard
  5. Toggle the LED switch
  6. 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