Last active
September 11, 2026 12:14
-
-
Save andrewflash/c0b7301dddcb91eaf1939c4e5e822963 to your computer and use it in GitHub Desktop.
Exilir AIoT Bootcamp Batch 1 - Chapter 2 - MQTT Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * ============================================================ | |
| * MQTT WiFi Hands-On - Exilir ESP32-C5 / DFRobot C5 | |
| * ============================================================ | |
| * | |
| * Hardware: | |
| * Board : DFRobot FireBeetle 2 ESP32-C5 | |
| * WS2812B : GPIO27 | |
| * HW-508 Buzzer : GPIO23 (PASSIVE buzzer) | |
| * | |
| * Library: | |
| * - WiFi (built-in Arduino ESP32) | |
| * - PubSubClient by Nick O'Leary | |
| * - Adafruit NeoPixel | |
| * | |
| * Public MQTT Broker: | |
| * broker.hivemq.com | |
| * TCP port 1883 | |
| * | |
| * MQTT topic dibuat unik dari MAC address board. | |
| * | |
| * Contoh: | |
| * exilir/training/c5-A1B2C3/cmd/led | |
| * exilir/training/c5-A1B2C3/cmd/buzzer | |
| * exilir/training/c5-A1B2C3/status/led | |
| * exilir/training/c5-A1B2C3/status/buzzer | |
| * exilir/training/c5-A1B2C3/telemetry | |
| */ | |
| #include <WiFi.h> | |
| #include <PubSubClient.h> | |
| #include <Adafruit_NeoPixel.h> | |
| // ============================================================ | |
| // 1. WIFI CONFIGURATION | |
| // ============================================================ | |
| const char* WIFI_SSID = "NAMA_WIFI"; | |
| const char* WIFI_PASSWORD = "PASSWORD_WIFI"; | |
| // ============================================================ | |
| // 2. MQTT CONFIGURATION | |
| // ============================================================ | |
| const char* MQTT_BROKER = "broker.hivemq.com"; | |
| const uint16_t MQTT_PORT = 1883; | |
| // Prefix topic. | |
| // Device ID akan ditambahkan otomatis dari MAC address. | |
| const char* MQTT_TOPIC_ROOT = "exilir/training"; | |
| // ============================================================ | |
| // 3. HARDWARE CONFIGURATION | |
| // ============================================================ | |
| // ---------- WS2812B ---------- | |
| const uint8_t LED_PIN = 27; | |
| const uint8_t LED_COUNT = 8; | |
| const uint8_t BRIGHTNESS = 60; | |
| Adafruit_NeoPixel strip( | |
| LED_COUNT, | |
| LED_PIN, | |
| NEO_GRB + NEO_KHZ800 | |
| ); | |
| // ---------- HW-508 PASSIVE BUZZER ---------- | |
| const uint8_t BUZZER_PIN = 23; | |
| // Default tone ketika menerima command "ON" | |
| const uint16_t BUZZER_DEFAULT_FREQ = 2000; | |
| // LEDC Arduino ESP32 3.x | |
| const uint8_t BUZZER_RESOLUTION = 8; | |
| // ============================================================ | |
| // 4. NETWORK OBJECT | |
| // ============================================================ | |
| WiFiClient wifiClient; | |
| PubSubClient mqtt(wifiClient); | |
| // ============================================================ | |
| // 5. DEVICE & MQTT TOPICS | |
| // ============================================================ | |
| String deviceId; | |
| String topicBase; | |
| String topicLedCommand; | |
| String topicBuzzerCommand; | |
| String topicLedStatus; | |
| String topicBuzzerStatus; | |
| String topicTelemetry; | |
| // ============================================================ | |
| // 6. DEVICE STATE | |
| // ============================================================ | |
| bool ledState = false; | |
| bool buzzerState = false; | |
| uint16_t buzzerFrequency = 0; | |
| // Untuk beep non-blocking | |
| bool buzzerTimed = false; | |
| uint32_t buzzerOffAt = 0; | |
| // MQTT retry | |
| uint32_t lastMqttReconnect = 0; | |
| // Telemetry | |
| uint32_t lastTelemetry = 0; | |
| const uint32_t MQTT_RECONNECT_INTERVAL = 5000; | |
| const uint32_t TELEMETRY_INTERVAL = 5000; | |
| // ============================================================ | |
| // 7. LED FUNCTIONS | |
| // ============================================================ | |
| void setLedColor(uint8_t r, uint8_t g, uint8_t b) { | |
| uint32_t color = strip.Color(r, g, b); | |
| for (uint8_t i = 0; i < LED_COUNT; i++) { | |
| strip.setPixelColor(i, color); | |
| } | |
| strip.show(); | |
| ledState = (r != 0 || g != 0 || b != 0); | |
| } | |
| void ledOff() { | |
| strip.clear(); | |
| strip.show(); | |
| ledState = false; | |
| } | |
| void ledRandom() { | |
| // Sama seperti konsep random HSV pada kode referensi LED | |
| uint16_t hue = random(0, 65536); | |
| uint32_t color = | |
| strip.gamma32( | |
| strip.ColorHSV(hue, 255, 255) | |
| ); | |
| for (uint8_t i = 0; i < LED_COUNT; i++) { | |
| strip.setPixelColor(i, color); | |
| } | |
| strip.show(); | |
| ledState = true; | |
| } | |
| // ============================================================ | |
| // 8. BUZZER FUNCTIONS | |
| // ============================================================ | |
| void buzzerOn(uint16_t frequency) { | |
| ledcWriteTone(BUZZER_PIN, frequency); | |
| buzzerState = true; | |
| buzzerFrequency = frequency; | |
| } | |
| void buzzerOff() { | |
| // Frequency 0 = output PWM berhenti | |
| ledcWriteTone(BUZZER_PIN, 0); | |
| buzzerState = false; | |
| buzzerFrequency = 0; | |
| buzzerTimed = false; | |
| } | |
| void buzzerBeep( | |
| uint16_t frequency = BUZZER_DEFAULT_FREQ, | |
| uint16_t durationMs = 250 | |
| ) { | |
| buzzerOn(frequency); | |
| buzzerTimed = true; | |
| buzzerOffAt = millis() + durationMs; | |
| } | |
| // Dipanggil terus di loop(), sehingga tidak perlu delay() | |
| void updateBuzzer() { | |
| if (!buzzerTimed) { | |
| return; | |
| } | |
| if ((int32_t)(millis() - buzzerOffAt) >= 0) { | |
| buzzerOff(); | |
| } | |
| } | |
| // ============================================================ | |
| // 9. MQTT STATUS PUBLISH | |
| // ============================================================ | |
| void publishLedStatus() { | |
| if (!mqtt.connected()) { | |
| return; | |
| } | |
| mqtt.publish( | |
| topicLedStatus.c_str(), | |
| ledState ? "ON" : "OFF" | |
| ); | |
| } | |
| void publishBuzzerStatus() { | |
| if (!mqtt.connected()) { | |
| return; | |
| } | |
| char payload[64]; | |
| if (buzzerState) { | |
| snprintf( | |
| payload, | |
| sizeof(payload), | |
| "{\"state\":\"ON\",\"frequency\":%u}", | |
| buzzerFrequency | |
| ); | |
| } else { | |
| snprintf( | |
| payload, | |
| sizeof(payload), | |
| "{\"state\":\"OFF\",\"frequency\":0}" | |
| ); | |
| } | |
| mqtt.publish( | |
| topicBuzzerStatus.c_str(), | |
| payload | |
| ); | |
| } | |
| // ============================================================ | |
| // 10. MQTT CALLBACK | |
| // ============================================================ | |
| void mqttCallback( | |
| char* topic, | |
| byte* payload, | |
| unsigned int length | |
| ) { | |
| // Ubah payload byte[] menjadi String | |
| String message; | |
| for (unsigned int i = 0; i < length; i++) { | |
| message += (char)payload[i]; | |
| } | |
| message.trim(); | |
| String command = message; | |
| command.toUpperCase(); | |
| Serial.println(); | |
| Serial.println("========== MQTT MESSAGE =========="); | |
| Serial.print("Topic : "); | |
| Serial.println(topic); | |
| Serial.print("Payload : "); | |
| Serial.println(message); | |
| Serial.println("=================================="); | |
| // ---------------------------------------------------------- | |
| // LED COMMAND | |
| // ---------------------------------------------------------- | |
| if (String(topic) == topicLedCommand) { | |
| if (command == "ON") { | |
| // LED hijau | |
| setLedColor(0, 255, 0); | |
| } | |
| else if (command == "OFF") { | |
| ledOff(); | |
| } | |
| else if (command == "RED") { | |
| setLedColor(255, 0, 0); | |
| } | |
| else if (command == "GREEN") { | |
| setLedColor(0, 255, 0); | |
| } | |
| else if (command == "BLUE") { | |
| setLedColor(0, 0, 255); | |
| } | |
| else if (command == "RANDOM") { | |
| ledRandom(); | |
| } | |
| else { | |
| Serial.println( | |
| "LED command: ON | OFF | RED | GREEN | BLUE | RANDOM" | |
| ); | |
| return; | |
| } | |
| publishLedStatus(); | |
| } | |
| // ---------------------------------------------------------- | |
| // BUZZER COMMAND | |
| // ---------------------------------------------------------- | |
| else if (String(topic) == topicBuzzerCommand) { | |
| if (command == "ON") { | |
| // Passive buzzer membutuhkan frekuensi. | |
| buzzerOn(BUZZER_DEFAULT_FREQ); | |
| } | |
| else if (command == "OFF") { | |
| buzzerOff(); | |
| } | |
| else if (command == "BEEP") { | |
| buzzerBeep( | |
| BUZZER_DEFAULT_FREQ, | |
| 250 | |
| ); | |
| } | |
| else { | |
| // Payload angka dianggap sebagai frekuensi. | |
| // | |
| // Contoh: | |
| // 262 -> Do | |
| // 440 -> La | |
| // 1000 -> tone 1 kHz | |
| // 2000 -> tone 2 kHz | |
| int frequency = message.toInt(); | |
| if (frequency >= 100 && frequency <= 5000) { | |
| buzzerOn(frequency); | |
| } else { | |
| Serial.println( | |
| "Buzzer command: ON | OFF | BEEP | 100..5000 Hz" | |
| ); | |
| return; | |
| } | |
| } | |
| publishBuzzerStatus(); | |
| } | |
| } | |
| // ============================================================ | |
| // 11. WIFI CONNECTION | |
| // ============================================================ | |
| void connectWiFi() { | |
| Serial.println(); | |
| Serial.print("Connecting WiFi: "); | |
| Serial.println(WIFI_SSID); | |
| WiFi.mode(WIFI_STA); | |
| WiFi.begin(WIFI_SSID, WIFI_PASSWORD); | |
| while (WiFi.status() != WL_CONNECTED) { | |
| delay(500); | |
| Serial.print("."); | |
| } | |
| Serial.println(); | |
| Serial.println("WiFi connected."); | |
| Serial.print("IP Address : "); | |
| Serial.println(WiFi.localIP()); | |
| Serial.print("MAC : "); | |
| Serial.println(WiFi.macAddress()); | |
| Serial.print("RSSI : "); | |
| Serial.print(WiFi.RSSI()); | |
| Serial.println(" dBm"); | |
| } | |
| // ============================================================ | |
| // 12. CREATE DEVICE ID & TOPICS | |
| // ============================================================ | |
| void createMqttTopics() { | |
| String mac = WiFi.macAddress(); | |
| // AA:BB:CC:11:22:33 | |
| // menjadi | |
| // AABBCC112233 | |
| mac.replace(":", ""); | |
| String suffix = | |
| mac.substring(mac.length() - 6); | |
| deviceId = "c5-" + suffix; | |
| topicBase = | |
| String(MQTT_TOPIC_ROOT) | |
| + "/" | |
| + deviceId; | |
| topicLedCommand = | |
| topicBase + "/cmd/led"; | |
| topicBuzzerCommand = | |
| topicBase + "/cmd/buzzer"; | |
| topicLedStatus = | |
| topicBase + "/status/led"; | |
| topicBuzzerStatus = | |
| topicBase + "/status/buzzer"; | |
| topicTelemetry = | |
| topicBase + "/telemetry"; | |
| Serial.println(); | |
| Serial.println("=========== MQTT TOPICS ==========="); | |
| Serial.print("Device ID : "); | |
| Serial.println(deviceId); | |
| Serial.print("LED Command : "); | |
| Serial.println(topicLedCommand); | |
| Serial.print("Buzzer Command : "); | |
| Serial.println(topicBuzzerCommand); | |
| Serial.print("LED Status : "); | |
| Serial.println(topicLedStatus); | |
| Serial.print("Buzzer Status : "); | |
| Serial.println(topicBuzzerStatus); | |
| Serial.print("Telemetry : "); | |
| Serial.println(topicTelemetry); | |
| Serial.println("==================================="); | |
| } | |
| // ============================================================ | |
| // 13. MQTT CONNECTION | |
| // ============================================================ | |
| bool connectMQTT() { | |
| if (WiFi.status() != WL_CONNECTED) { | |
| return false; | |
| } | |
| Serial.println(); | |
| Serial.print("Connecting MQTT broker: "); | |
| Serial.println(MQTT_BROKER); | |
| String clientId = | |
| "exilir-" + deviceId; | |
| if (mqtt.connect(clientId.c_str())) { | |
| Serial.println("MQTT connected!"); | |
| // Subscribe command topics | |
| mqtt.subscribe( | |
| topicLedCommand.c_str() | |
| ); | |
| mqtt.subscribe( | |
| topicBuzzerCommand.c_str() | |
| ); | |
| Serial.println("Subscribed:"); | |
| Serial.println(topicLedCommand); | |
| Serial.println(topicBuzzerCommand); | |
| // Publish initial state | |
| publishLedStatus(); | |
| publishBuzzerStatus(); | |
| return true; | |
| } | |
| Serial.print("MQTT connection failed. state="); | |
| Serial.println(mqtt.state()); | |
| return false; | |
| } | |
| // ============================================================ | |
| // 14. TELEMETRY | |
| // ============================================================ | |
| void publishTelemetry() { | |
| if (!mqtt.connected()) { | |
| return; | |
| } | |
| char payload[160]; | |
| snprintf( | |
| payload, | |
| sizeof(payload), | |
| "{" | |
| "\"device\":\"%s\"," | |
| "\"uptime_s\":%lu," | |
| "\"rssi\":%d" | |
| "}", | |
| deviceId.c_str(), | |
| millis() / 1000UL, | |
| WiFi.RSSI() | |
| ); | |
| mqtt.publish( | |
| topicTelemetry.c_str(), | |
| payload | |
| ); | |
| Serial.print("Publish telemetry: "); | |
| Serial.println(payload); | |
| } | |
| // ============================================================ | |
| // 15. SETUP | |
| // ============================================================ | |
| void setup() { | |
| Serial.begin(115200); | |
| delay(1000); | |
| Serial.println(); | |
| Serial.println("==============================="); | |
| Serial.println(" EXILIR ESP32-C5 MQTT HANDS-ON "); | |
| Serial.println("==============================="); | |
| // ---------------------------------------------------------- | |
| // RGB LED | |
| // ---------------------------------------------------------- | |
| strip.begin(); | |
| strip.setBrightness(BRIGHTNESS); | |
| ledOff(); | |
| randomSeed(esp_random()); | |
| // ---------------------------------------------------------- | |
| // PASSIVE BUZZER | |
| // ---------------------------------------------------------- | |
| // ESP32 Arduino Core 3.x API | |
| // | |
| // pin, initial frequency, resolution | |
| if (!ledcAttach( | |
| BUZZER_PIN, | |
| BUZZER_DEFAULT_FREQ, | |
| BUZZER_RESOLUTION | |
| )) { | |
| Serial.println( | |
| "ERROR: gagal attach LEDC buzzer!" | |
| ); | |
| } | |
| buzzerOff(); | |
| // ---------------------------------------------------------- | |
| // NETWORK | |
| // ---------------------------------------------------------- | |
| connectWiFi(); | |
| createMqttTopics(); | |
| mqtt.setServer( | |
| MQTT_BROKER, | |
| MQTT_PORT | |
| ); | |
| mqtt.setCallback( | |
| mqttCallback | |
| ); | |
| mqtt.setKeepAlive(30); | |
| connectMQTT(); | |
| } | |
| // ============================================================ | |
| // 16. LOOP | |
| // ============================================================ | |
| void loop() { | |
| uint32_t now = millis(); | |
| // ---------------------------------------------------------- | |
| // WIFI RECONNECT | |
| // ---------------------------------------------------------- | |
| if (WiFi.status() != WL_CONNECTED) { | |
| Serial.println( | |
| "WiFi disconnected, reconnecting..." | |
| ); | |
| WiFi.reconnect(); | |
| delay(1000); | |
| return; | |
| } | |
| // ---------------------------------------------------------- | |
| // MQTT RECONNECT | |
| // ---------------------------------------------------------- | |
| if (!mqtt.connected()) { | |
| if ( | |
| now - lastMqttReconnect | |
| >= MQTT_RECONNECT_INTERVAL | |
| ) { | |
| lastMqttReconnect = now; | |
| connectMQTT(); | |
| } | |
| } else { | |
| // WAJIB dipanggil terus. | |
| // Menjaga koneksi MQTT dan menerima pesan. | |
| mqtt.loop(); | |
| } | |
| // ---------------------------------------------------------- | |
| // BUZZER NON-BLOCKING | |
| // ---------------------------------------------------------- | |
| updateBuzzer(); | |
| // ---------------------------------------------------------- | |
| // PERIODIC TELEMETRY | |
| // ---------------------------------------------------------- | |
| if ( | |
| mqtt.connected() | |
| && now - lastTelemetry >= TELEMETRY_INTERVAL | |
| ) { | |
| lastTelemetry = now; | |
| publishTelemetry(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment