連線控制程式:https://chengminlin2.github.io/OTTOBLE2/
接腳:
#define LEFTLEG 2
#define RIGHTLEG 3
#define LEFTFOOT 4
#define RIGHTFOOT 5
#define TRIG 8
#define ECHO 9
#define BLE_TX 11
#define BLE_RX 12
#define BUZZER 13
HTML程式:
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 | <!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Otto Web BLE Controller</title> <style> body { font-family: Arial, sans-serif; text-align:center; background:#f9f9f9; margin:0; padding:24px; } button{ width:160px; height:56px; margin:8px; font-size:16px; border:none; border-radius:10px; background:#4CAF50; color:white; cursor:pointer; } button:disabled{ opacity:.5; cursor:not-allowed; } button.red{ background:#d9534f; } button.blue{ background:#0275d8; } button.gray{ background:#6c757d; } .container{ margin-top:18px; } .panel{ max-width:760px; margin:14px auto; background:#fff; border-radius:14px; padding:14px 12px; box-shadow:0 2px 10px rgba(0,0,0,.06); } .row{ display:flex; flex-wrap:wrap; justify-content:center; gap:8px; margin:8px 0; } .row button{ margin:0; } .status{ font-size:14px; color:#333; } .hint{ font-size:12px; color:#666; margin-top:6px; } .mono{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } .log{ text-align:left; max-width:760px; margin:10px auto 0; background:#111; color:#eee; padding:10px 12px; border-radius:10px; font-size:12px; height:160px; overflow:auto; } input[type="range"]{ width:260px; } .badge{ display:inline-block; padding:2px 8px; border-radius:999px; background:#eee; font-size:12px; } </style> </head> <body> <h2>OTTO BLE 遙控器</h2> <div class="panel"> <div class="row"> <button id="connectBle" class="blue">連線 / Connect</button> <button id="disconnectBle" class="red" disabled>中斷 / Disconnect</button> </div> <p id="status" class="status">尚未連線</p> <div class="row" style="align-items:center;"> <span class="badge">速度</span> <input id="speed" type="range" min="0" max="5" step="1" value="2" /> <span id="speedLabel" class="mono">2</span> </div> <div class="hint"> 指令格式:<span class="mono">command + speedIndex + "\\n"</span>(例如 <span class="mono">forward2</span>) </div> </div> <div class="panel"> <h3>移動 / Move</h3> <div class="container"> <div class="row"> <button onclick="sendMove('forward')">⬆ 前進 / Forward</button> </div> <div class="row"> <button onclick="sendMove('left')">⬅ 左轉 / Left</button> <button onclick="sendMove('stop')" class="red">⏹ 停止 / Stop</button> <button onclick="sendMove('right')">➡ 右轉 / Right</button> </div> <div class="row"> <button onclick="sendMove('backward')">⬇ 後退 / Backward</button> </div> </div> </div> <div class="panel"> <h3>超音波互動 / Ultrasound</h3> <div class="row"> <button id="btnUsOnce" class="blue">量測一次 (ultrasound)</button> <button id="btnAutoOn" class="gray">自動避障 ON</button> <button id="btnAutoOff" class="gray">自動避障 OFF</button> </div> <div class="row"> <button id="btnStreamOn" class="gray">距離串流 ON</button> <button id="btnStreamOff" class="gray">距離串流 OFF</button> </div> <p class="status"> 距離:<span id="usValue" class="mono">--</span> cm <span id="autoBadge" class="badge">AUTOAVOID:OFF</span> <span id="streamBadge" class="badge">US_STREAM:OFF</span> </p> <div class="hint"> 需要 Arduino 端支援指令:<span class="mono">autoavoid_on</span> / <span class="mono">autoavoid_off</span> / <span class="mono">us_stream_on</span> / <span class="mono">us_stream_off</span>(皆會帶 speedIndex 與換行) </div> </div> <div class="panel"> <h3>表情與動作 / Emotions & Gestures</h3> <div class="row"> <button onclick="sendGesture('happy')">開心 / Happy</button> <button onclick="sendGesture('superhappy')">超開心 / Super Happy</button> <button onclick="sendGesture('sad')">難過 / Sad</button> <button onclick="sendGesture('sleeping')">睡覺 / Sleeping</button> </div> <div class="row"> <button onclick="sendGesture('confused')">困惑 / Confused</button> <button onclick="sendGesture('fretful')">煩躁 / Fretful</button> <button onclick="sendGesture('love')">愛心 / Love</button> <button onclick="sendGesture('angry')">生氣 / Angry</button> </div> <div class="row"> <button onclick="sendGesture('magic')">魔法 / Magic</button> <button onclick="sendGesture('wave')">揮手 / Wave</button> <button onclick="sendGesture('victory')">勝利 / Victory</button> <button onclick="sendGesture('fail')">失敗 / Fail</button> </div> <div class="row"> <button onclick="sendGesture('fart')">放屁 / Fart</button> </div> </div> <div class="panel"> <img src="2_01.png" alt="Otto" style="max-width:320px; width:100%; height:auto;" /> </div> <div id="log" class="log" aria-label="log"></div> <script> let device, server, uartService, tx, rx; let speedIndex = 2; const SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb"; const CHAR_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb"; const connectBtn = document.getElementById("connectBle"); const disconnectBtn = document.getElementById("disconnectBle"); const statusEl = document.getElementById("status"); const logEl = document.getElementById("log"); const speedEl = document.getElementById("speed"); const speedLabelEl = document.getElementById("speedLabel"); const usValueEl = document.getElementById("usValue"); const autoBadgeEl = document.getElementById("autoBadge"); const streamBadgeEl = document.getElementById("streamBadge"); const btnUsOnce = document.getElementById("btnUsOnce"); const btnAutoOn = document.getElementById("btnAutoOn"); const btnAutoOff = document.getElementById("btnAutoOff"); const btnStreamOn = document.getElementById("btnStreamOn"); const btnStreamOff = document.getElementById("btnStreamOff"); let rxBuffer = ""; // UI:速度滑桿 speedEl.addEventListener("input", () => { speedIndex = Number(speedEl.value); speedLabelEl.textContent = String(speedIndex); }); // Log helper function logLine(s){ const time = new Date().toLocaleTimeString(); logEl.textContent += `[${time}] ${s}\n`; logEl.scrollTop = logEl.scrollHeight; } function setConnectedUI(connected){ connectBtn.disabled = connected; disconnectBtn.disabled = !connected; // 超音波按鈕也跟著鎖定 btnUsOnce.disabled = !connected; btnAutoOn.disabled = !connected; btnAutoOff.disabled = !connected; btnStreamOn.disabled = !connected; btnStreamOff.disabled= !connected; } // 連線 connectBtn.onclick = async () => { try{ device = await navigator.bluetooth.requestDevice({ // namePrefix 用在不同模組命名(Otto / NFU-...)比較彈性 filters: [ { namePrefix: "Otto" }, { namePrefix: "NFU" } ], optionalServices: [SERVICE_UUID] }); device.addEventListener("gattserverdisconnected", onDisconnected); server = await device.gatt.connect(); uartService = await server.getPrimaryService(SERVICE_UUID); // 多數 BLE 串口模組是同一個 characteristic 負責讀/寫 tx = await uartService.getCharacteristic(CHAR_UUID); rx = tx; // 開啟通知:接收 Arduino 回傳(US:xx / AUTOAVOID:ON / US_STREAM:ON 等) await rx.startNotifications(); rx.addEventListener("characteristicvaluechanged", handleNotify); statusEl.textContent = "已連線: " + (device.name || "(unknown)"); setConnectedUI(true); logLine("已連線,通知已開啟"); }catch(e){ alert("連線失敗: " + e); logLine("連線失敗: " + e); } }; // 斷線 disconnectBtn.onclick = () => disconnect(); function disconnect(){ try{ if (rx){ rx.removeEventListener("characteristicvaluechanged", handleNotify); } }catch(_){} if (device && device.gatt && device.gatt.connected){ device.gatt.disconnect(); } else { onDisconnected(); } } function onDisconnected(){ tx = null; rx = null; uartService = null; server = null; statusEl.textContent = "尚未連線"; setConnectedUI(false); logLine("藍牙已斷線"); } // 寫入(WebBT 常見限制一次 20 bytes 左右,保險起見做切片) async function writeLine(str){ if(!tx){ alert("請先連線 BLE"); return; } const data = new TextEncoder().encode(str); // 20 bytes 分包(含換行) const CHUNK = 20; for(let i=0;i<data.length;i+=CHUNK){ const chunk = data.slice(i, i+CHUNK); await tx.writeValue(chunk); } logLine(">>> " + JSON.stringify(str)); } // 指令:cmd + speedIndex + \n function sendMove(cmd){ const line = cmd + String(speedIndex) + "\n"; writeLine(line); } // 表情:保持你原做法(用 0 當速度字尾) function sendGesture(cmd){ const line = cmd + "0\n"; writeLine(line); } // 超音波:依 Arduino 端邏輯也要附 speedIndex(最後一碼會被拿去當速度) function sendUltra(cmd){ const line = cmd + String(speedIndex) + "\n"; writeLine(line); } // 超音波互動按鈕 btnUsOnce.onclick = () => sendUltra("ultrasound"); btnAutoOn.onclick = () => sendUltra("autoavoid_on"); btnAutoOff.onclick = () => sendUltra("autoavoid_off"); btnStreamOn.onclick = () => sendUltra("us_stream_on"); btnStreamOff.onclick= () => sendUltra("us_stream_off"); // 解析通知(Arduino 端回傳: // "US:12", "AUTOAVOID:ON", "US_STREAM:ON", "AVOID:10" 等) function handleNotify(event){ const value = event.target.value; const chunk = new TextDecoder().decode(value); rxBuffer += chunk; // 盡量以換行切割(Arduino 用 println 會有 \r\n) let idx; while ((idx = rxBuffer.indexOf("\n")) !== -1){ const line = rxBuffer.slice(0, idx).trim(); rxBuffer = rxBuffer.slice(idx + 1); if(!line) continue; logLine("<<< " + line); applyIncoming(line); } // 若對端沒送換行,也嘗試處理單行關鍵字(保底) if (rxBuffer.length > 200){ rxBuffer = rxBuffer.slice(-200); } } function applyIncoming(line){ // 距離 if (line.startsWith("US:")){ const v = parseInt(line.slice(3), 10); if (!Number.isNaN(v)) usValueEl.textContent = String(v); return; } if (line.startsWith("AVOID:")){ const v = parseInt(line.slice(6), 10); if (!Number.isNaN(v)) usValueEl.textContent = String(v); return; } // 狀態徽章 if (line.startsWith("AUTOAVOID:")){ const s = line.slice("AUTOAVOID:".length).trim().toUpperCase(); autoBadgeEl.textContent = "AUTOAVOID:" + s; return; } if (line.startsWith("US_STREAM:")){ const s = line.slice("US_STREAM:".length).trim().toUpperCase(); streamBadgeEl.textContent = "US_STREAM:" + s; return; } } // 初始 UI setConnectedUI(false); </script> </body> </html> |
Arduino程式:
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 | /* * * ______________ ____ _____ _ _ _ * | __ __ | / __ \ _________ _________ ____ | __ \ | | \\ // * | |__| |__| | | | | |___ ___ ___ ___ / __ \ | | | | | | \\ // * |_ _________| | | | | | | | | | | | | | | | | | | | | * | \__/ | | |__| | | | | | | |__| | | |__| | | | | | * | | \____/ |_| |_| \____/ |_____/ |_| |_| * |_ _________| * \__/ * * This Sketch was created to control Otto Starter with the Offical Web Bluetooth Controller for Otto DIY Robots. * For any question about this script you can contact us at education@ottodiy.com * By: Iván R. Artiles */ #include <Otto.h> #include <EEPROM.h> #define LEFTLEG 2 #define RIGHTLEG 3 #define LEFTFOOT 4 #define RIGHTFOOT 5 #define TRIG 8 #define ECHO 9 #define BLE_TX 11 #define BLE_RX 12 #define BUZZER 13 #if defined(ARDUINO_ARCH_ESP32) #include "BluetoothSerial.h" String device_name = "Otto BT Esp32 A24"; BluetoothSerial bluetooth; #else #include <SoftwareSerial.h> String device_name = "NFU-OSSR-A24"; SoftwareSerial bluetooth(BLE_TX, BLE_RX); #endif Otto Ottobot; int move_speed[] = {3000, 2000, 1000, 750, 500, 250}; int n = 2; int ultrasound_threeshold = 15; String command = ""; bool autoAvoid = false; bool usStream = false; unsigned long lastUsStreamTime = 0; const unsigned long usStreamInterval = 500; int v = 0; int i; int positions[] = {90, 90, 90, 90}; int8_t trims[4] = {0, 0, 0, 0}; unsigned long sync_time = 0; bool calibration = false; int isavailable = 1; long ultrasound_distance() { long duration; long distance; digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); duration = pulseIn(ECHO, HIGH, 30000); if (duration == 0) { return 999; } distance = duration / 58; return distance; } void setup() { Serial.begin(9600); Ottobot.init(LEFTLEG, RIGHTLEG, LEFTFOOT, RIGHTFOOT, true, BUZZER); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); #if defined(ARDUINO_ARCH_ESP32) Serial.println("ESP32"); bluetooth.begin(device_name); #else Serial.println("No ESP32"); Serial.println(device_name); bluetooth.begin(9600); bluetooth.print("AT+NAME" + device_name + "\r\n"); #endif Ottobot.home(); } void loop() { checkBluetooth(); if (Serial.available() > 0) { command = Serial.readStringUntil('\n'); command.trim(); Serial.print("Received: "); Serial.println(command); } if (autoAvoid) { AutoAvoidance(); } if (usStream) { sendUltrasoundStream(); } if (command == "forward") { Forward(); } else if (command == "backward") { Backward(); } else if (command == "right") { Right(); } else if (command == "left") { Left(); } else if (command == "stop") { Stop(); } else if (command == "avoidance") { AutoAvoidance(); } else if (command == "force") { UseForce(); } } void checkBluetooth() { char charBuffer[30]; if (bluetooth.available() > 0) { isavailable = 1; int numberOfBytesReceived = bluetooth.readBytesUntil('\n', charBuffer, 29); if (numberOfBytesReceived <= 0) return; charBuffer[numberOfBytesReceived] = '\0'; String received = String(charBuffer); received.trim(); Serial.print("Received by BLE: "); Serial.println(received); char last = received.charAt(received.length() - 1); if (last >= '0' && last <= '9') { n = last - '0'; if (n < 0) n = 0; if (n > 5) n = 5; received.remove(received.length() - 1); } if (received == "forward") { command = "forward"; autoAvoid = false; } else if (received == "backward") { command = "backward"; autoAvoid = false; } else if (received == "right") { command = "right"; autoAvoid = false; } else if (received == "left") { command = "left"; autoAvoid = false; } else if (received == "stop") { command = "stop"; autoAvoid = false; usStream = false; bluetooth.println("AUTOAVOID:OFF"); bluetooth.println("US_STREAM:OFF"); } else if (received == "ultrasound") { command = ""; sendUltrasoundOnce(); } else if (received == "autoavoid_on") { command = ""; autoAvoid = true; bluetooth.println("AUTOAVOID:ON"); } else if (received == "autoavoid_off") { command = ""; autoAvoid = false; Ottobot.home(); bluetooth.println("AUTOAVOID:OFF"); } else if (received == "us_stream_on") { command = ""; usStream = true; bluetooth.println("US_STREAM:ON"); } else if (received == "us_stream_off") { command = ""; usStream = false; bluetooth.println("US_STREAM:OFF"); } else if (received == "happy") { command = ""; Ottobot.playGesture(OttoHappy); } else if (received == "superhappy") { command = ""; Ottobot.playGesture(OttoSuperHappy); } else if (received == "sad") { command = ""; Ottobot.playGesture(OttoSad); } else if (received == "sleeping") { command = ""; Ottobot.playGesture(OttoSleeping); } else if (received == "confused") { command = ""; Ottobot.playGesture(OttoConfused); } else if (received == "fretful") { command = ""; Ottobot.playGesture(OttoFretful); } else if (received == "love") { command = ""; Ottobot.playGesture(OttoLove); } else if (received == "angry") { command = ""; Ottobot.playGesture(OttoAngry); } else if (received == "magic") { command = ""; Ottobot.playGesture(OttoMagic); } else if (received == "wave") { command = ""; Ottobot.playGesture(OttoWave); } else if (received == "victory") { command = ""; Ottobot.playGesture(OttoVictory); } else if (received == "fail") { command = ""; Ottobot.playGesture(OttoFail); } else if (received == "fart") { command = ""; Ottobot.playGesture(OttoFart); } else if (received.startsWith("C")) { if (calibration == false) { Ottobot._moveServos(10, positions); calibration = true; delay(50); } command = "calibration"; Calibration(received); } else if (received == "walk_test") { command = ""; Ottobot.walk(3, 1000, FORWARD); } else if (received == "save_calibration") { command = ""; readChar('s'); } } else { if (isavailable == 1) { Serial.println("No Bluetooth is available."); isavailable = 0; } } } void sendUltrasoundOnce() { long d = ultrasound_distance(); bluetooth.print("US:"); bluetooth.println(d); Serial.print("US:"); Serial.println(d); } void sendUltrasoundStream() { if (millis() - lastUsStreamTime >= usStreamInterval) { lastUsStreamTime = millis(); long d = ultrasound_distance(); bluetooth.print("US:"); bluetooth.println(d); Serial.print("US:"); Serial.println(d); } } void Forward() { Ottobot.walk(1, move_speed[n], FORWARD); } void Backward() { Ottobot.walk(1, move_speed[n], BACKWARD); } void Right() { Ottobot.turn(1, move_speed[n], RIGHT); } void Left() { Ottobot.turn(1, move_speed[n], LEFT); } void Stop() { Ottobot.home(); command = ""; } void AutoAvoidance() { long d = ultrasound_distance(); bluetooth.print("AVOID:"); bluetooth.println(d); Serial.print("AVOID:"); Serial.println(d); if (d <= ultrasound_threeshold) { Ottobot.playGesture(OttoConfused); delay(100); unsigned long startBack = millis(); while (millis() - startBack < 5000) { Ottobot.walk(1, move_speed[n], BACKWARD); } Ottobot.home(); delay(200); unsigned long startTurn = millis(); while (millis() - startTurn < 5000) { Ottobot.turn(1, move_speed[n], LEFT); } Ottobot.home(); delay(200); } else { Ottobot.walk(1, move_speed[n], FORWARD); } } void UseForce() { long d = ultrasound_distance(); if (d <= ultrasound_threeshold) { Ottobot.walk(1, move_speed[n], BACKWARD); } else if (d > 10 && d < 15) { Ottobot.home(); } else if (d >= 15 && d < 30) { Ottobot.walk(1, move_speed[n], FORWARD); } else { Ottobot.home(); } } void Settings(String ts_ultrasound) { ultrasound_threeshold = ts_ultrasound.toInt(); } void Calibration(String c) { if (sync_time < millis()) { sync_time = millis() + 50; for (int k = 1; k < c.length(); k++) { readChar(c[k]); } } } void readChar(char ch) { if (ch >= '0' && ch <= '9') { v = (v * 10 + ch) - 48; return; } switch (ch) { case 'a': trims[0] = v - 90; setTrims(); v = 0; break; case 'b': trims[1] = v - 90; setTrims(); v = 0; break; case 'c': trims[2] = v - 90; setTrims(); v = 0; break; case 'd': trims[3] = v - 90; setTrims(); v = 0; break; case 's': for (i = 0; i <= 3; i++) { EEPROM.write(i, trims[i]); } delay(500); Ottobot.sing(S_superHappy); Ottobot.crusaito(1, 1000, 25, -1); Ottobot.crusaito(1, 1000, 25, 1); Ottobot.sing(S_happy_short); break; } } void setTrims() { Ottobot.setTrims(trims[0], trims[1], trims[2], trims[3]); Ottobot._moveServos(10, positions); } |