Membuat Asisten Virtual dengan ESP8266 dan Speech Recognition

Di era digital saat ini, teknologi Internet of Things (IoT) sudah semakin mudah diakses. Bahkan dengan budget terbatas, kita bisa membuat proyek menarik yang menggabungkan perangkat mikrokontroler dengan teknologi web modern. Pada artikel kali ini, saya akan berbagi pengalaman membuat asisten virtual sederhana menggunakan ESP8266 dan teknologi speech recognition (pengenalan suara) yang berjalan di browser.
Apa yang Bisa Dilakukan Alat Ini?
Proyek ini memungkinkan kita untuk:
- Mengenali suara melalui browser smartphone/laptop
- Menampilkan teks hasil pengenalan suara ke layar LCD 16×2
- Bisa dikembangkan untuk terhubung dengan API AI seperti Groq
Yang menarik, kita tidak perlu modul pengenalan suara khusus karena memanfaatkan kemampuan browser modern yang sudah mendukung Web Speech API.
Komponen yang Dibutuhkan
- NodeMCU ESP8266
- LCD I2C 16×2
- Kabel jumper secukupnya
- Koneksi WiFi
- Smartphone/laptop dengan browser yang mendukung Web Speech API (Chrome, Edge, Safari)
Rangkaian Hardware
Rangkaian hardware-nya sangat sederhana:
- VCC LCD ke 3.3V ESP8266
- GND LCD ke GND ESP8266
- SDA LCD ke pin D2 (GPIO4) ESP8266
- SCL LCD ke pin D1 (GPIO5) ESP8266
Cara Kerja
Sistem ini bekerja dengan prinsip sebagai berikut:
- ESP8266 bertindak sebagai web server yang menampilkan halaman HTML dengan fitur speech recognition
- Browser mengakses halaman tersebut dan mengaktifkan fitur pengenalan suara
- Hasil pengenalan suara dikirim kembali ke ESP8266 melalui HTTP request
- ESP8266 menampilkan teks yang diterima ke layar LCD
Yang membuat sistem ini menarik adalah kita memanfaatkan kemampuan browser untuk mengenali suara tanpa perlu menambahkan hardware khusus. Pengenalan suara terjadi di browser, bukan di ESP8266, sehingga kita bisa mengatasi keterbatasan memori dan daya komputasi mikrokontroler.
Kode Program
Berikut adalah kode lengkap untuk proyek ini:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 |
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <WiFiClientSecure.h> #include <ArduinoJson.h> #include <LiquidCrystal_I2C.h> #include <Wire.h> #define LCD_I2C_ADDR 0x27 #define LCD_COLS 16 #define LCD_ROWS 2 #define SDA_PIN 4 // D2 on NodeMCU #define SCL_PIN 5 // D1 on NodeMCU struct Config { const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; const char* openai_api_key = "YOUR_OPENAI_API_KEY"; const char* openai_host = "api.openai.com"; const int openai_port = 443; }; Config config; ESP8266WebServer server(80); LiquidCrystal_I2C lcd(LCD_I2C_ADDR, LCD_COLS, LCD_ROWS); WiFiClientSecure client; String lastSpeechText = ""; String lastAiResponse = ""; bool processing = false; const char* htmlPage = R"rawliteral( <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ESP8266 AI Speech Assistant</title> <style> :root { --primary: #3498db; --primary-dark: #2980b9; --secondary: #e74c3c; --background: #f9f9f9; --text: #333; --light-text: #666; --border: #ddd; } * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(--background); color: var(--text); line-height: 1.6; padding: 20px; max-width: 800px; margin: 0 auto; } h1 { text-align: center; margin-bottom: 20px; color: var(--primary-dark); } .container { background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); padding: 20px; margin-bottom: 20px; } .btn-group { display: flex; justify-content: center; margin-bottom: 20px; } button { background-color: var(--primary); color: white; border: none; padding: 12px 24px; font-size: 16px; border-radius: 50px; cursor: pointer; margin: 0 10px; transition: background-color 0.3s, transform 0.2s; display: flex; align-items: center; } button:hover { background-color: var(--primary-dark); transform: translateY(-2px); } button:disabled { background-color: var(--border); cursor: not-allowed; transform: none; } #stopBtn { background-color: var(--secondary); } .card { border: 1px solid var(--border); border-radius: 8px; padding: 15px; margin-bottom: 15px; } .card-header { font-weight: bold; margin-bottom: 10px; color: var(--primary-dark); border-bottom: 1px solid var(--border); padding-bottom: 5px; } #speechResult, #aiResponse { min-height: 80px; white-space: pre-wrap; } .listening { color: var(--secondary); font-weight: bold; } .status { text-align: center; font-size: 14px; margin-top: 20px; color: var(--light-text); } .icon { margin-right: 8px; } @media (max-width: 500px) { .btn-group { flex-direction: column; } button { margin: 5px 0; } } </style> </head> <body> <h1>ESP8266 AI Speech Assistant</h1> <div class="container"> <div class="btn-group"> <button id="startBtn"> <span class="icon">🎤</span> Start Listening </button> <button id="stopBtn" disabled> <span class="icon">⏹️</span> Stop </button> <button id="askAiBtn" disabled> <span class="icon">🤖</span> Ask AI </button> </div> <div class="card"> <div class="card-header">Your Speech</div> <div id="speechResult">Speak something to see your words here...</div> </div> <div class="card"> <div class="card-header">AI Response</div> <div id="aiResponse">AI response will appear here...</div> </div> <div class="status" id="status"></div> </div> <script> const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const askAiBtn = document.getElementById('askAiBtn'); const speechResult = document.getElementById('speechResult'); const aiResponse = document.getElementById('aiResponse'); const statusEl = document.getElementById('status'); let recognition; let resultText = ""; function setStatus(message, isError = false) { statusEl.textContent = message; statusEl.style.color = isError ? 'red' : 'var(--light-text)'; } function resetButtons(listening = false) { startBtn.disabled = listening; stopBtn.disabled = !listening; askAiBtn.disabled = !resultText.trim(); } function initSpeechRecognition() { if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) { recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)(); recognition.continuous = true; recognition.interimResults = true; recognition.lang = 'en-US'; // Set language - change as needed recognition.onstart = function() { resetButtons(true); speechResult.classList.add('listening'); speechResult.textContent = "Listening..."; setStatus("Listening for speech"); }; recognition.onresult = function(event) { resultText = ""; for (let i = event.resultIndex; i < event.results.length; i++) { if (event.results[i].isFinal) { resultText += event.results[i][0].transcript; } } speechResult.textContent = resultText; askAiBtn.disabled = !resultText.trim(); if (resultText.trim() !== "") { // Automatically send to ESP if needed // sendToESP(resultText); } }; recognition.onerror = function(event) { console.error('Speech recognition error:', event.error); setStatus(`Error: ${event.error}`, true); speechResult.textContent = "Error: " + event.error; resetButtons(); }; recognition.onend = function() { speechResult.classList.remove('listening'); resetButtons(); setStatus("Speech recognition ended"); }; return true; } else { alert("Your browser doesn't support speech recognition. Please try Chrome or Edge."); return false; } } function sendToESP(text, endpoint = '/process') { setStatus("Sending to ESP..."); return fetch(`${endpoint}?text=${encodeURIComponent(text)}`) .then(response => { if (!response.ok) { throw new Error(`Server returned ${response.status}`); } return response.text(); }) .then(data => { setStatus("ESP processed successfully"); return data; }) .catch(error => { console.error('Error sending to ESP:', error); setStatus(`Error: ${error.message}`, true); throw error; }); } function askAI() { if (!resultText.trim()) return; askAiBtn.disabled = true; aiResponse.textContent = "Processing request..."; setStatus("Sending to AI..."); sendToESP(resultText, '/ask') .then(data => { if (data) { // Poll for result checkAIResponse(); } }) .catch(() => { aiResponse.textContent = "Failed to process your request."; askAiBtn.disabled = false; }); } function checkAIResponse() { fetch('/ai-response') .then(response => response.json()) .then(data => { if (data.processing) { aiResponse.textContent = "AI is thinking..."; setTimeout(checkAIResponse, 2000); } else if (data.response) { aiResponse.textContent = data.response; setStatus("Response received"); askAiBtn.disabled = false; } else { aiResponse.textContent = "No response from AI."; setStatus("No response", true); askAiBtn.disabled = false; } }) .catch(error => { console.error('Error checking AI response:', error); aiResponse.textContent = "Error checking response status."; setStatus("Error checking response", true); askAiBtn.disabled = false; }); } // Initialize if (initSpeechRecognition()) { startBtn.addEventListener('click', function() { recognition.start(); }); stopBtn.addEventListener('click', function() { recognition.stop(); }); askAiBtn.addEventListener('click', askAI); } // Check for ongoing processes on page load fetch('/status') .then(response => response.json()) .then(data => { if (data.lastSpeech) { resultText = data.lastSpeech; speechResult.textContent = resultText; askAiBtn.disabled = false; } if (data.lastResponse) { aiResponse.textContent = data.lastResponse; } if (data.processing) { askAiBtn.disabled = true; setStatus("AI request in progress..."); checkAIResponse(); } }) .catch(error => { console.error('Error fetching status:', error); }); </script> </body> </html> )rawliteral"; void displayLcdMessage(String line1, String line2 = "") { lcd.clear(); lcd.setCursor(0, 0); lcd.print(line1.substring(0, min(LCD_COLS, (int)line1.length()))); if (line2.length() > 0) { lcd.setCursor(0, 1); lcd.print(line2.substring(0, min(LCD_COLS, (int)line2.length()))); } } void setupWifi() { WiFi.mode(WIFI_STA); WiFi.begin(config.ssid, config.password); displayLcdMessage("Connecting WiFi"); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 20) { delay(500); Serial.print("."); attempts++; } if (WiFi.status() == WL_CONNECTED) { Serial.println("\nWiFi Connected"); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); displayLcdMessage("WiFi Connected", WiFi.localIP().toString()); } else { Serial.println("\nWiFi connection failed"); displayLcdMessage("WiFi Failed", "Check settings"); } } void setupServer() { server.on("/", HTTP_GET, []() { server.send(200, "text/html", htmlPage); }); server.on("/process", HTTP_GET, handleSpeechText); server.on("/ask", HTTP_GET, handleAskAI); server.on("/ai-response", HTTP_GET, handleAIResponse); server.on("/status", HTTP_GET, handleStatus); server.onNotFound([]() { server.send(404, "text/plain", "Not Found"); }); server.begin(); Serial.println("Web Server started"); } void setup() { Serial.begin(115200); Serial.println("\nESP8266 AI Speech Assistant"); Wire.begin(SDA_PIN, SCL_PIN); lcd.begin(LCD_COLS, LCD_ROWS); lcd.backlight(); displayLcdMessage("AI Speech", "Assistant v1.0"); delay(2000); setupWifi(); client.setInsecure(); // Note: For production, consider using proper certificate verification setupServer(); Serial.println("Ready! Open browser at http://" + WiFi.localIP().toString()); } void loop() { server.handleClient(); } void handleSpeechText() { if (server.hasArg("text")) { String text = server.arg("text"); text.trim(); lastSpeechText = text; Serial.println("[Speech] " + text); displayLcdMessage("Speech:", text); server.send(200, "text/plain", "Speech received"); } else { server.send(400, "text/plain", "No text parameter"); } } String callOpenAI(String prompt) { if (!client.connect(config.openai_host, config.openai_port)) { Serial.println("Connection to OpenAI failed"); return "Connection failed"; } // Create JSON payload DynamicJsonDocument requestDoc(1024); requestDoc["model"] = "gpt-3.5-turbo"; JsonArray messages = requestDoc.createNestedArray("messages"); JsonObject systemMessage = messages.createNestedObject(); systemMessage["role"] = "system"; systemMessage["content"] = "You are a helpful assistant. Keep responses concise as they will be displayed on a small LCD screen."; JsonObject userMessage = messages.createNestedObject(); userMessage["role"] = "user"; userMessage["content"] = prompt; requestDoc["max_tokens"] = 150; requestDoc["temperature"] = 0.7; String jsonPayload; serializeJson(requestDoc, jsonPayload); // Prepare HTTP request String request = "POST /v1/chat/completions HTTP/1.1\r\n"; request += "Host: " + String(config.openai_host) + "\r\n"; request += "Content-Type: application/json\r\n"; request += "Authorization: Bearer " + String(config.openai_api_key) + "\r\n"; request += "Content-Length: " + String(jsonPayload.length()) + "\r\n"; request += "Connection: close\r\n\r\n"; request += jsonPayload; // Send request client.print(request); // Wait for response long timeout = millis() + 10000; while (client.available() == 0) { if (millis() > timeout) { Serial.println("OpenAI request timeout"); client.stop(); return "Request timeout"; } delay(100); } // Read headers String line; while (client.available()) { line = client.readStringUntil('\n'); if (line == "\r") { break; } } // Read body String response = ""; while (client.available()) { response += client.readString(); } // Parse JSON response DynamicJsonDocument responseDoc(2048); DeserializationError error = deserializeJson(responseDoc, response); if (error) { Serial.print("JSON parsing failed: "); Serial.println(error.c_str()); return "JSON parsing failed"; } // Extract content String content = ""; if (responseDoc.containsKey("choices") && responseDoc["choices"].size() > 0 && responseDoc["choices"][0].containsKey("message") && responseDoc["choices"][0]["message"].containsKey("content")) { content = responseDoc["choices"][0]["message"]["content"].as<String>(); } else if (responseDoc.containsKey("error")) { content = "API Error: " + responseDoc["error"]["message"].as<String>(); } else { content = "Unknown response format"; } return content; } void handleAskAI() { if (!server.hasArg("text")) { server.send(400, "text/plain", "No text parameter"); return; } String text = server.arg("text"); text.trim(); if (text.isEmpty()) { server.send(400, "text/plain", "Empty text"); return; } lastSpeechText = text; processing = true; server.send(200, "text/plain", "Processing"); // Process OpenAI request in a non-blocking way displayLcdMessage("Processing...", "Please wait"); // In a real implementation, you'd use AsyncTCP or similar // Since ESP8266 doesn't multitask well, we'll just do it here lastAiResponse = callOpenAI(text); processing = false; // Display result on LCD displayLcdMessage("AI Response:", lastAiResponse); } void handleAIResponse() { DynamicJsonDocument doc(512); doc["processing"] = processing; doc["response"] = lastAiResponse; String jsonResponse; serializeJson(doc, jsonResponse); server.send(200, "application/json", jsonResponse); } void handleStatus() { DynamicJsonDocument doc(512); doc["processing"] = processing; doc["lastSpeech"] = lastSpeechText; doc["lastResponse"] = lastAiResponse; String jsonResponse; serializeJson(doc, jsonResponse); server.send(200, "application/json", jsonResponse); } |
Jangan lupa ganti
NAMA_WIFI_ANDA
danPASSWORD_WIFI_ANDA
dengan kredensial WiFi Anda.
Penggunaan
- Upload kode program ke ESP8266 melalui Arduino IDE
- Buka Serial Monitor untuk melihat IP address ESP8266
- Dari smartphone atau laptop, buka browser dan akses IP address tersebut
- Tekan tombol “Mulai Mendengarkan” dan ucapkan sesuatu
- Teks hasil pengenalan suara akan muncul di layar browser dan LCD
Pengembangan Lebih Lanjut
Sistem ini masih sangat dasar, tapi bisa dikembangkan lebih jauh. Beberapa ide pengembangan:
- Integrasi dengan API AI: Mengirim teks hasil pengenalan suara ke Groq, OpenAI, atau layanan AI lainnya untuk mendapatkan respons cerdas
- Kontrol Perangkat: Menambahkan kemampuan untuk mengontrol relay atau perangkat lain berdasarkan perintah suara
- Penyimpanan Data: Menyimpan riwayat percakapan ke database atau file
- Dukungan Bahasa: Menambahkan dukungan untuk bahasa lain selain bahasa default
Kesimpulan
Dengan kombinasi ESP8266 dan teknologi web modern, kita bisa membuat sistem pengenalan suara sederhana tanpa perlu komponen mahal. Meskipun ESP8266 memiliki keterbatasan RAM, pendekatan ini mengatasinya dengan memanfaatkan kemampuan browser untuk pemrosesan yang berat.
Semoga artikel ini bermanfaat dan bisa menjadi inspirasi untuk proyek-proyek IoT lainnya. Jangan ragu untuk bereksperimen dan mengembangkan ide ini lebih jauh sesuai kebutuhan Anda.
Selamat mencoba dan berkreasi!