Mqtt libraryMqtt examples
Advanced Control
Multiple sensors and actuators with bidirectional control
Advanced Control
This example demonstrates a complete IoT system with multiple virtual pins, LED control, and sensor simulation using MQTT real-time synchronization. Perfect for learning the virtual pin architecture and testing your setup.
Hardware Required
- ESP8266 or ESP32 development board
- LED (any color)
- RGB LED or PWM-controlled LED
- 220Ω resistor for LED
- Breadboard and jumper wires
Wiring
ESP8266/ESP32 Components
GPIO 12 (D6) → LED (+) → 220Ω → GND
GPIO 13 (D7) → RGB LED (PWM control)
3.3V → LED VCC
GND → LED 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"
// Project settings
#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
#define LED_PIN D6
#define TEMP_SENSOR 36 // ADC1_CH0 on ESP32
// LED state handler
DECENTIOT_RECEIVE(P0) {
digitalWrite(LED_PIN, value);
Serial.printf("[P0] LED state = %s\n", value ? "ON" : "OFF");
}
DECENTIOT_SEND(P1, 15000) {
// Generate random temperature value between 0-100
int temperature = random(0, 101);
DecentIoT.write(P1, temperature);
Serial.printf("[P1] Temperature = %d\n", temperature);
}
DECENTIOT_SEND(P2, 15000) {
// Generate random humidity value between 0-100
int humidity = random(0, 101);
DecentIoT.write(P2, humidity);
Serial.printf("[P2] Humidity = %d\n", humidity);
}
DECENTIOT_RECEIVE(P3) {
int sliderValue = value;
int pwmValue = sliderValue * 255 / 100;
analogWrite(rgbPin, pwmValue);
Serial.printf("[P3] RGB Brightness = %d (slider: %d)\n", pwmValue, sliderValue);
}
// Sending a message from device to cloud
DECENTIOT_SEND(P4, 10000) {
static int count = 0;
String message = "ESP8266 Connected! Count: " + String(count++);
DecentIoT.write(P4, message.c_str());
Serial.println("[P4] Sent: " + message);
}
void setup() {
Serial.begin(115200);
Serial.println("\n--- Initializing DecentIoT Device ---");
// Initialize LED pin
pinMode(ledPin, OUTPUT);
pinMode(rgbPin, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(ledPin, LOW); // Ensure LED is off initially
digitalWrite(LED_BUILTIN, LOW);
// 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() {
// User checks WiFi and reconnects if needed
if (WiFi.status() != WL_CONNECTED) {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("[WiFi] Disconnected! Reconnecting...");
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASS);
// Optionally: wait for connection, show status, etc.
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("WiFi reconnected! Restarting device...");
delay(1000);
ESP.restart();
}
}
DecentIoT.run();
delay(10);
}
Dashboard Setup
- Create Project in DecentIoT web dashboard
- Add Widgets:
- Switch named
led_control
(maps to P0) - Gauge named
temperature
(maps to P1, range 0-100) - Gauge named
humidity
(maps to P2, range 0-100) - Slider named
rgb_brightness
(maps to P3, range 0-100) - Label named
status_message
(maps to P4)
- Switch named
- Configure Layout:
- Group controls together
- Group sensors together
- Add status message at the bottom
- Save and test all functions
How It Works
Virtual Pin Architecture
Pin | Function | Type | Description |
---|---|---|---|
P0 | LED Control | bool | Manual LED on/off control |
P1 | Temperature | int | Simulated temperature (0-100) |
P2 | Humidity | int | Simulated humidity (0-100) |
P3 | RGB Brightness | int | PWM brightness control (0-100) |
P4 | Status Message | string | Device status messages |
System Features
- LED Control: P0 provides simple on/off control
- Sensor Simulation: P1 and P2 send random values every 15 seconds
- PWM Control: P3 provides brightness control with slider
- WiFi Reconnection: Automatic WiFi reconnection with device restart
- Status Messages: P4 sends connection status every 10 seconds
Advanced Scheduling
// Different reading intervals for different sensors
DECENTIOT_SEND(P1, 10000) { // Temperature every 10 seconds
// Temperature reading code
}
DECENTIOT_SEND(P2, 10000) { // Humidity every 10 seconds
// Humidity reading code
}
DECENTIOT_SEND(P3, 5000) { // Light level every 5 seconds
// Light reading code
}
Advanced Features
Conditional Control
// Only send data when system is enabled
DECENTIOT_SEND(P1, 10000) {
if (systemEnabled) {
float temperature = dht.readTemperature();
if (!isnan(temperature)) {
DecentIoT.write(P1, temperature);
}
}
}
Error Handling
// Enhanced error handling
DECENTIOT_SEND(P1, 10000) {
if (systemEnabled) {
float temperature = dht.readTemperature();
if (!isnan(temperature)) {
DecentIoT.write(P1, temperature);
Serial.printf("[P1] Temperature: %.1f°C\n", temperature);
} else {
DecentIoT.write(P1, -999); // Error value
Serial.println("[P1] Sensor error - check connections");
}
}
}
Troubleshooting
System not responding:
- Check system status switch (P0) in dashboard
- Verify all wiring connections
- Check Serial Monitor for error messages
Sensors not reading:
- Verify sensor connections
- Check power supply (3.3V)
- Ensure pull-up resistors are connected
Controls not working:
- Check system is enabled (P0)
- Verify output pin assignments
- Check relay module connections
Required Libraries
Install these libraries via Arduino Library Manager:
- DHT sensor library by Adafruit
- Adafruit Unified Sensor (dependency)
Next Steps
- Firebase Examples - Alternative to MQTT
- Scheduling Guide - Advanced scheduling features
- API Reference - Complete method documentation