2026年1月8日 星期四

[OTTO Ninja]OTTO忍者機器人Web控制介面

 




  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
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
#include <Servo.h>

/* ========== WiFi AP ========== */
const char* ssid = "OTTO NINJA";
const char* password = "12345678";

/* ========== Web ========== */
ESP8266WebServer server(80);
WebSocketsServer webSocket(81);

/* ========== Servo pulse range(SG90 建議較保守,避免頂住抖動/重啟) ========== */
const int SERVO_MIN_US = 580;
const int SERVO_MAX_US = 2350;

/* ========== Calibration SETTINGS(沿用你原本) ========== */
// Feet forward/back speed(保留:ROLL 模式仍使用)
int LFFWRS= 20;
int RFFWRS= 20;
int LFBWRS= 20;
int RFBWRS= 20;

// Walk stand (legs)
int LA0= 60;
int RA0= 120;

// Walk tilt positions
int LATL= 100;
int RATL= 175;
int LATR= 5;
int RATR= 80;

// Roll (legs)
int LA1= 168;
int RA1= 8;

/* ========== Timing ========== */
unsigned long currentmillis1 = 0;

// Mode: 0=WALK, 1=ROLL
int ModeCounter = 0;

/* ========== Pinout ========== */
const uint8_t ServoLeftFootPin   = 13; // D7
const uint8_t ServoLeftLegPin    = 15; // D8
const uint8_t ServoRightFootPin  = 0;  // D3
const uint8_t ServoRightLegPin   = 2;  // D4

// 手/頭腳位保留宣告,但程式不再 attach 它們(避免 RX/TX 干擾)
const uint8_t ServoLeftArmPin    = 16; // D0
const uint8_t ServoRightArmPin   = 3;  // RX (GPIO3)
const uint8_t ServoHeadPin       = 1;  // TX (GPIO1)

Servo myservoLeftFoot;
Servo myservoLeftLeg;
Servo myservoRightFoot;
Servo myservoRightLeg;

Servo myservoLeftArm;
Servo myservoRightArm;
Servo myservoHead;

/* ========== Web 控制輸入 ========== */
int CTRL_JX = 0;   // -100..100
int CTRL_JY = 0;   // -100..100

/* ========== HTML Page(精簡介面:只留連線+模式+搖桿) ========== */
const char MAIN_page[] PROGMEM = R"=====(<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>OTTO NINJA Web</title>
<style>
  body{font-family:Arial;text-align:center;background:#f4f6f8;margin:0;padding:16px;}
  .card{max-width:560px;margin:0 auto;background:#fff;border-radius:14px;padding:16px;box-shadow:0 8px 24px rgba(0,0,0,.08);}
  button{width:150px;height:54px;font-size:16px;margin:6px;border:none;border-radius:12px;background:#2d7ef7;color:#fff}
  button.gray{background:#6c757d}
  button.green{background:#00a86b}
  .row{display:flex;justify-content:center;flex-wrap:wrap}
  .box{margin:10px;padding:8px;border-radius:8px;font-weight:bold;background:#eee;}
  .small{font-size:12px;color:#666;line-height:1.6}

  .joystick-wrap{
    margin:20px auto;
    width:220px;
    height:220px;
    position:relative;
    user-select:none;
    -webkit-user-select:none;
  }
  .joystick-base{
    width:220px;
    height:220px;
    border-radius:50%;
    background:#ddd;
    position:absolute;
    left:0;
    top:0;
  }
  .joystick-stick{
    width:86px;
    height:86px;
    border-radius:50%;
    background:#2d7ef7;
    position:absolute;
    left:67px;
    top:67px;
    touch-action:none;
  }
</style>
</head>
<body>
<div class="card">
  <h2>OTTO NINJA(Web 控制)</h2>

  <div id="statusBox" class="box">狀態:未連線</div>
  <div id="modeBox" class="box">模式:未知</div>
  <div id="actBox"  class="box">動作:未知</div>

  <div class="row">
    <button class="gray" onclick="connectWS()">連線</button>
  </div>

  <div class="row">
    <button class="green" onclick="sendCmd('mode_walk')">Walk(人形)</button>
    <button class="green" onclick="sendCmd('mode_roll')">Roll(車形)</button>
  </div>

  <div class="joystick-wrap">
    <div class="joystick-base"></div>
    <div id="joy" class="joystick-stick"></div>
  </div>

  <p class="small">
    連 Wi-Fi:OTTO NINJA / 12345678<br>
    瀏覽器:192.168.4.1
  </p>
</div>

<script>
let ws=null;
let currentMode="WALK";

const statusBox=document.getElementById("statusBox");
const modeBox=document.getElementById("modeBox");
const actBox=document.getElementById("actBox");

function setStatus(t,c){statusBox.innerText="狀態:"+t; statusBox.style.background=c;}
function connectWS(){
  ws=new WebSocket("ws://"+location.hostname+":81/");
  setStatus("連線中…","#ffeaa7");
  ws.onopen=()=>setStatus("已連線","#55efc4");
  ws.onclose=()=>setStatus("中斷","#fab1a0");
  ws.onerror=()=>setStatus("錯誤","#ff7675");
  ws.onmessage=(e)=>handleMsg(e.data);
}
function sendCmd(cmd){
  if(ws && ws.readyState===1) ws.send(cmd);
  else alert("請先按「連線」");
}
function move(x,y){
  sendCmd("move "+x+" "+y);
}

function handleMsg(m){
  if(m.startsWith("MODE:")){
    currentMode = m.substring(5).trim();
    modeBox.innerText="模式:"+currentMode;
  }
  if(m.startsWith("ACT:"))  actBox.innerText ="動作:"+m.substring(4);
}

/* ===== 虛擬搖桿(含節流 25Hz) ===== */
const joy = document.getElementById("joy");
const joyWrap = joy.parentElement;

let dragging = false;
// 220x220 的中心點
let center = { x: 110, y: 110 };
let maxDist = 80;

let lastSend = 0;
function sendJoy(x, y){
  const now = Date.now();
  if(now - lastSend < 40) return;
  lastSend = now;

  x = Math.round(x);
  y = Math.round(y);
  move(x, y);
}
function resetJoy(){
  joy.style.left = "67px";
  joy.style.top  = "67px";
  move(0,0); // 放手一定送一次
}

joy.addEventListener("pointerdown", e=>{
  dragging = true;
  joy.setPointerCapture(e.pointerId);
});

window.addEventListener("pointermove", e=>{
  if(!dragging) return;

  const rect = joyWrap.getBoundingClientRect();
  let x = e.clientX - rect.left - center.x;
  let y = e.clientY - rect.top  - center.y;

  const dist = Math.sqrt(x*x + y*y);
  if(dist > maxDist){
    x = x / dist * maxDist;
    y = y / dist * maxDist;
  }

  // stick 半徑 86/2 = 43
  joy.style.left = (center.x + x - 43) + "px";
  joy.style.top  = (center.y + y - 43) + "px";

  let jx = (x / maxDist) * 100;
  let jy = (-y / maxDist) * 100;

  sendJoy(jx, jy);
});

window.addEventListener("pointerup", e=>{
  if(!dragging) return;
  dragging = false;
  resetJoy();
});
</script>
</body>
</html>)=====";

/* ========== 工具:WebSocket 廣播 ========== */
void wsBroadcast(String s){
  webSocket.broadcastTXT(s);
}

/* ========== 小工具:統一 attach/detach(方便校正) ========== */
inline void attachLF(){ myservoLeftFoot.attach(ServoLeftFootPin, SERVO_MIN_US, SERVO_MAX_US); }
inline void attachLL(){ myservoLeftLeg.attach(ServoLeftLegPin, SERVO_MIN_US, SERVO_MAX_US); }
inline void attachRF(){ myservoRightFoot.attach(ServoRightFootPin, SERVO_MIN_US, SERVO_MAX_US); }
inline void attachRL(){ myservoRightLeg.attach(ServoRightLegPin, SERVO_MIN_US, SERVO_MAX_US); }

inline void detachLF(){ myservoLeftFoot.detach(); }
inline void detachLL(){ myservoLeftLeg.detach(); }
inline void detachRF(){ myservoRightFoot.detach(); }
inline void detachRL(){ myservoRightLeg.detach(); }

inline void detachAllLegs(){
  detachLF(); detachLL(); detachRF(); detachRL();
}

/* ========== 動作函式(穩定優化:不再動 RX/TX 的伺服) ========== */
void NinjaStop(){
  detachAllLegs();
}

void NinjaSetWalk(){
  attachLL();
  attachRL();
  myservoLeftLeg.write(LA0);
  myservoRightLeg.write(RA0);
  delay(300);
  detachLL();
  detachRL();
}

void NinjaSetRoll(){
  attachLL();
  attachRL();
  myservoLeftLeg.write(LA1);
  myservoRightLeg.write(RA1);
  delay(300);
  detachLL();
  detachRL();
}

void NinjaWalkStop(){
  attachLF(); attachRF(); attachLL(); attachRL();
  myservoLeftFoot.write(90);
  myservoRightFoot.write(90);
  myservoLeftLeg.write(LA0);
  myservoRightLeg.write(RA0);
}

void NinjaRollStop(){
  attachLF(); attachRF();
  myservoLeftFoot.write(90);
  myservoRightFoot.write(90);
  detachLF(); detachRF();
}

/* ========== WebSocket event:接收控制命令 ========== */
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length){
  if(type == WStype_CONNECTED){
    wsBroadcast("MODE:" + String(ModeCounter==0 ? "WALK" : "ROLL"));
    wsBroadcast("ACT:STOP");
    return;
  }
  if(type != WStype_TEXT) return;

  // 安全解析:payload 不保證 \0 結尾
  String cmd;
  cmd.reserve(length);
  for(size_t i=0;i<length;i++) cmd += (char)payload[i];
  cmd.trim();

  if(cmd == "mode_walk"){
    NinjaSetWalk();
    ModeCounter = 0;
    wsBroadcast("MODE:WALK");
    return;
  }

  if(cmd == "mode_roll"){
    NinjaSetRoll();
    ModeCounter = 1;
    wsBroadcast("MODE:ROLL");
    return;
  }

  if(cmd.startsWith("move")){
    int sp1 = cmd.indexOf(' ');
    int sp2 = cmd.lastIndexOf(' ');
    if(sp1 > 0 && sp2 > sp1){
      CTRL_JX = cmd.substring(sp1+1, sp2).toInt();
      CTRL_JY = cmd.substring(sp2+1).toInt();
      CTRL_JX = constrain(CTRL_JX, -100, 100);
      CTRL_JY = constrain(CTRL_JY, -100, 100);
    }
    return;
  }
}

/* ========== Setup ========== */
void setup(){
  Serial.begin(115200);

  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);

  server.on("/", [](){ server.send_P(200, "text/html", MAIN_page); });
  server.begin();

  webSocket.begin();
  webSocket.onEvent(webSocketEvent);

  NinjaWalkStop();
  delay(300);
  NinjaStop();

  Serial.println("OTTO NINJA Web Ready");
  Serial.println(WiFi.softAPIP());
}

/* ========== Loop ========== */
void loop(){
  server.handleClient();
  webSocket.loop();

  /* ===== 狀態顯示(供網頁) ===== */
  static String lastAct = "";
  String act;

  const int DZ = 15;
  bool idle = (abs(CTRL_JX) <= DZ && abs(CTRL_JY) <= DZ);

  if(idle) act="STOP";
  else if(abs(CTRL_JY) >= abs(CTRL_JX)) act = (CTRL_JY > 0) ? "FORWARD" : "BACK";
  else act = (CTRL_JX > 0) ? "RIGHT" : "LEFT";

  if(act != lastAct){
    lastAct = act;
    wsBroadcast("ACT:" + act);
  }

  /* ===== WALK:可前後走 + 可原地轉向 + 轉向更明顯(加腿部 bias) ===== */
  if(ModeCounter == 0){

    int x = CTRL_JX;
    int y = CTRL_JY;

    bool wIdle = (abs(x) <= DZ && abs(y) <= DZ);
    bool inPlaceTurn = (abs(y) <= DZ && abs(x) > DZ);

    if(wIdle){
      NinjaWalkStop();
      return;
    }

    // 步幅(腳掌擺動角度)
    int step = map(constrain(abs(y), 0, 100), 0, 100, 18, 58);

    // 轉向量(-1~+1)
    float steer = (float)constrain(x, -100, 100) / 100.0f;

    // 左右步幅差(加大)
    const float STEER_GAIN = 0.75f;
    int stepL = (int)round(step * (1.0f + STEER_GAIN * steer));
    int stepR = (int)round(step * (1.0f - STEER_GAIN * steer));

    stepL = constrain(stepL, 12, 65);
    stepR = constrain(stepR, 12, 65);

    // 原地轉向:固定小步幅(更穩)
    if(inPlaceTurn){
      stepL = stepR = 28;
    }

    // 轉彎時「腿部重心偏置」:讓轉向更明顯
    int bias = map(abs(x), 0, 100, 0, 14);
    if(x < 0) bias = -bias; // 左轉負、右轉正

    // 節奏:越小越快,但越吃電
    const unsigned long PHASE_MS = 300;
    static unsigned long t0 = 0;
    static int phase = 0;

    if(millis() - t0 >= PHASE_MS){
      t0 = millis();
      phase = (phase + 1) % 4;
    }

    // 確保伺服有輸出(推地才會走)
    attachLL(); attachRL(); attachLF(); attachRF();

    // dir: +1 前進, -1 後退(若方向顛倒,把 +1/-1 對調)
    int dir = (y >= 0) ? +1 : -1;

    if(phase == 0){
      // 重心偏右 + 轉向偏置
      myservoLeftLeg.write(LATR + bias);
      myservoRightLeg.write(RATR + bias);
    }
    else if(phase == 1){
      // 左腳擺動(另一腳回中避免累積偏差)
      myservoRightFoot.write(90);

      if(inPlaceTurn){
        if(x < 0){
          // 原地左轉:左腳往後
          myservoLeftFoot.write(90 - stepL);
        }else{
          // 原地右轉:左腳往前
          myservoLeftFoot.write(90 + stepL);
        }
      }else{
        myservoLeftFoot.write(90 + dir * stepL);
      }
    }
    else if(phase == 2){
      // 重心偏左 + 轉向偏置
      myservoLeftLeg.write(LATL + bias);
      myservoRightLeg.write(RATL + bias);
    }
    else if(phase == 3){
      // 右腳擺動(另一腳回中避免累積偏差)
      myservoLeftFoot.write(90);

      if(inPlaceTurn){
        if(x < 0){
          // 原地左轉:右腳往前
          myservoRightFoot.write(90 + stepR);
        }else{
          // 原地右轉:右腳往後
          myservoRightFoot.write(90 - stepR);
        }
      }else{
        myservoRightFoot.write(90 - dir * stepR);
      }
    }

    return; // WALK 已處理完,避免往下跑到 ROLL
  }

  /* ===== ROLL:差速左右轉(加輸出 constrain 避免頂死) ===== */
  if(ModeCounter == 1){
    if(idle){
      NinjaRollStop();
      return;
    }

    attachLF();
    attachRF();

    int LWS= map(CTRL_JY, 100, -100, 135, 45);
    int RWS= map(CTRL_JY, 100, -100, 45, 135);
    int LWD= map(CTRL_JX, 100, -100, 45, 0);
    int RWD= map(CTRL_JX, 100, -100, 0, -45);

    int outL = constrain(LWS + LWD, 0, 180);
    int outR = constrain(RWS + RWD, 0, 180);

    myservoLeftFoot.write(outL);
    myservoRightFoot.write(outR);
  }
}

沒有留言:

張貼留言