#include #include #include #include #include #include #include #include #include "ControlPage.h" #ifndef CONFIG_IDF_TARGET_ESP32C6 #error "Select XIAO_ESP32C6 for this motor test." #endif static const uint8_t MOTOR_PINS[4] = {0, 1, 2, 21}; static const uint32_t DEFAULT_PULSE_MS = 500; static const uint32_t MAX_PULSE_MS = 700; static const uint32_t COOLDOWN_MS = 150; static const char *AP_SSID = "Robot"; static const char *AP_PASS = "12345678"; WebServer server(80); portMUX_TYPE motorMux = portMUX_INITIALIZER_UNLOCKED; int motorA = 0; int motorB = 0; uint32_t pulseStartedMs = 0; uint32_t pulseDurationMs = 0; uint32_t lastStoppedMs = 0; uint32_t motorEpoch = 1; uint32_t controlEpoch = 1; bool watchdogReady = false; Adafruit_PWMServoDriver pwm(0x40); HardwareSerial cameraSerial(1); const uint8_t SERVO_CHANNELS[5] = {0,1,2,3,5}; // Logical ID -> PCA9685 channel const int lowAngle[5] = {10,40,60,60,60}; const int highAngle[5] = {170,110,95,120,120}; const int minPulse[5] = {500,500,500,1000,1000}; const int maxPulse[5] = {2500,2500,2400,2000,2000}; int servoAngle[5] = {90,90,90,90,90}, servoTarget[5] = {90,90,90,90,90}; bool servoEnabled[5] = {false,false,false,false,false}; bool pcaFound = false, screenFound = false, cameraSeen = false, cameraFollow = false; bool invertA = false, invertB = false, invertFront = false, invertRear = true; uint32_t lastCameraMs = 0, lastServoMs = 0, lastProbeMs = 0, lastFaceMs = 0; String cameraLine, cameraColor = "none", face = "neutral", lastCameraApplied = ""; bool cameraOverflow = false; int steeringAngle = 0; String steeringMode = "counter"; bool probe(uint8_t address) { Wire.beginTransmission(address); return Wire.endTransmission() == 0; } bool screenCommand(const String &command) { Wire.beginTransmission(0x32); Wire.write((const uint8_t *)command.c_str(), command.length()); screenFound = Wire.endTransmission() == 0; return screenFound; } void targetServo(int id, int angle) { servoTarget[id] = constrain(angle, lowAngle[id], highAngle[id]); servoEnabled[id] = true; } void updateServos() { if (!pcaFound || millis() - lastServoMs < 40) return; lastServoMs = millis(); for (int i=0; i<5; ++i) { if (!servoEnabled[i]) continue; servoAngle[i] += constrain(servoTarget[i]-servoAngle[i], -1, 1); int us = map(servoAngle[i],0,180,minPulse[i],maxPulse[i]); pwm.setPWM(SERVO_CHANNELS[i],0,(us*4096L)/20000L); } } void readCamera() { // Bounded read prevents noisy UART input from starving the HTTP service. for (int n=0; n<128 && cameraSerial.available(); ++n) { char c = cameraSerial.read(); if (c == '\n') { cameraLine.trim(); int index = cameraOverflow ? -1 : String("rgbpyn").indexOf(cameraLine); if (cameraLine.length()==1 && index>=0) { const char *colors[] = {"red","green","blue","purple","yellow","none"}; cameraColor=colors[index]; cameraSeen=true; lastCameraMs=millis(); digitalWrite(19,cameraColor=="red"); digitalWrite(20,cameraColor=="green"); } cameraLine=""; cameraOverflow=false; } else if (c!='\r') { if (cameraLine.length()<40) cameraLine+=c; else cameraOverflow=true; } } if (cameraSeen && millis()-lastCameraMs>3000) { digitalWrite(19,LOW); digitalWrite(20,LOW); lastCameraApplied=""; } if (!cameraFollow || !cameraSeen || millis()-lastCameraMs>3000) return; if (cameraColor==lastCameraApplied && millis()-lastFaceMs<2000) return; bool changed=cameraColor!=lastCameraApplied; if (cameraColor=="none") {face="neutral"; screenCommand("FACE neutral");} else { face=cameraColor=="red"?"angry":cameraColor=="green"?"happy":cameraColor=="purple"?"surprise":cameraColor=="yellow"?"curious":"neutral"; screenCommand("RGB "+cameraColor); } if(changed && pcaFound) { if(cameraColor=="red") targetServo(0,120); if(cameraColor=="green") {targetServo(1,70); targetServo(2,78);} if(cameraColor=="blue") targetServo(2,95); if(cameraColor=="yellow") {targetServo(0,105); targetServo(2,75);} } lastCameraApplied=cameraColor; lastFaceMs=millis(); } // Called only while motorMux is locked. 0=off, +1=INx high, -1=INy high. void writeOutputsLocked(int a, int b) { gpio_set_level((gpio_num_t)MOTOR_PINS[0], a > 0 ? 1 : 0); gpio_set_level((gpio_num_t)MOTOR_PINS[1], a < 0 ? 1 : 0); gpio_set_level((gpio_num_t)MOTOR_PINS[2], b > 0 ? 1 : 0); gpio_set_level((gpio_num_t)MOTOR_PINS[3], b < 0 ? 1 : 0); motorA = a; motorB = b; } void stopLocked(uint32_t now) { writeOutputsLocked(0, 0); pulseDurationMs = 0; lastStoppedMs = now; ++motorEpoch; // Invalidate any queued motion request made before Stop. } void stopMotors() { portENTER_CRITICAL(&motorMux); stopLocked(millis()); portEXIT_CRITICAL(&motorMux); } void motorWatchdog(void *) { for (;;) { portENTER_CRITICAL(&motorMux); const uint32_t now = millis(); if ((motorA != 0 || motorB != 0) && (uint32_t)(now - pulseStartedMs) >= pulseDurationMs) { stopLocked(now); } portEXIT_CRITICAL(&motorMux); // Independently enforced even when WebServer is waiting on a client. vTaskDelay(pdMS_TO_TICKS(10)); } } String motorStateJson() { portENTER_CRITICAL(&motorMux); const uint32_t now = millis(); const int a = motorA; const int b = motorB; const uint32_t epoch = motorEpoch; const bool ready = watchdogReady; const uint32_t elapsed = now - pulseStartedMs; const uint32_t remaining = (a != 0 || b != 0) && elapsed < pulseDurationMs ? pulseDurationMs - elapsed : 0; const uint32_t stoppedFor = now - lastStoppedMs; const uint32_t cooldown = stoppedFor < COOLDOWN_MS ? COOLDOWN_MS - stoppedFor : 0; portEXIT_CRITICAL(&motorMux); String body; body.reserve(240); body = "{\"firmware\":\"robot-v3.11\",\"pins\":[0,1,2,21],\"motorA\":"; body += a; body += ",\"motorB\":"; body += b; body += ",\"remainingMs\":"; body += remaining; body += ",\"cooldownMs\":"; body += cooldown; body += ",\"epoch\":"; body += epoch; body += ",\"controlEpoch\":"+String(controlEpoch); body += ",\"watchdogReady\":"; body += ready ? "true" : "false"; body += ",\"pcaFound\":"+String(pcaFound?"true":"false"); body += ",\"screenFound\":"+String(screenFound?"true":"false"); body += ",\"cameraOnline\":"+String(cameraSeen && millis()-lastCameraMs<=3000?"true":"false"); body += ",\"cameraFollow\":"+String(cameraFollow?"true":"false"); body += ",\"cameraColor\":\""+cameraColor+"\",\"face\":\""+face+"\""; body += ",\"steeringAngle\":"+String(steeringAngle)+",\"steeringMode\":\""+steeringMode+"\""; body += ",\"invert\":["+String(invertA?1:0)+","+String(invertB?1:0)+","+String(invertFront?1:0)+","+String(invertRear?1:0)+"]"; body += ",\"servos\":["; for(int i=0;i<5;++i) { if(i) body+=","; body+="{\"angle\":"+String(servoAngle[i])+",\"target\":"+String(servoTarget[i])+",\"enabled\":"+String(servoEnabled[i]?"true":"false")+"}"; } body+="]}"; return body; } void responseHeaders() { server.sendHeader("Access-Control-Allow-Origin", "*"); server.sendHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS"); server.sendHeader("Access-Control-Allow-Headers", "Content-Type"); server.sendHeader("Cache-Control", "no-store"); server.sendHeader("Connection", "close"); } void sendState() { responseHeaders(); server.send(200, "application/json; charset=utf-8", motorStateJson()); } void sendResult(int code, const char *error = nullptr) { responseHeaders(); String body = error ? "{\"ok\":false,\"error\":\"" + String(error) + "\",\"state\":" : "{\"ok\":true,\"state\":"; body += motorStateJson(); body += "}"; server.send(code, "application/json; charset=utf-8", body); } bool parseUnsigned(const String &value, uint32_t &result) { if (value.length() == 0 || value.length() > 10) return false; uint64_t parsed = 0; for (size_t i = 0; i < value.length(); ++i) { const char ch = value.charAt(i); if (ch < '0' || ch > '9') return false; parsed = parsed * 10 + (ch - '0'); if (parsed > UINT32_MAX) return false; } result = (uint32_t)parsed; return true; } void handleMotor() { const String target = server.arg("motor"); const String direction = server.arg("direction"); uint32_t duration = DEFAULT_PULSE_MS; uint32_t requestEpoch = 0; if ((target != "a" && target != "b" && target != "both") || (direction != "forward" && direction != "reverse") || !parseUnsigned(server.arg("epoch"), requestEpoch) || (server.hasArg("duration") && !parseUnsigned(server.arg("duration"), duration)) || duration < 100 || duration > MAX_PULSE_MS) { sendResult(400, "Invalid parameters; use the v3 control page"); return; } const int sign = direction == "forward" ? 1 : -1; const int a = target == "b" ? 0 : sign; const int b = target == "a" ? 0 : sign; const char *error = nullptr; int code = 409; portENTER_CRITICAL(&motorMux); const uint32_t now = millis(); if (!watchdogReady) { error = "Watchdog not ready; motors locked"; code = 503; } else if (requestEpoch != motorEpoch) { error = "State updated; refresh and retry"; } else if (motorA != 0 || motorB != 0) { error = "Wait for the current motor pulse to stop"; } else if ((uint32_t)(now - lastStoppedMs) < COOLDOWN_MS) { error = "Cooldown; wait before the next pulse"; } else { pulseStartedMs = now; pulseDurationMs = duration; ++motorEpoch; writeOutputsLocked(a, b); } portEXIT_CRITICAL(&motorMux); if (error) { sendResult(code, error); return; } Serial.printf("Motor test: A=%d B=%d duration=%lu ms\n", a, b, (unsigned long)duration); sendResult(200); } void handleStop() { stopMotors(); sendResult(200); } void handleDrive() { String direction=server.arg("direction"); uint32_t epoch; if ((direction!="forward" && direction!="reverse") || !parseUnsigned(server.arg("epoch"),epoch)) {sendResult(400,"Invalid drive parameters");return;} int sign=direction=="forward"?1:-1; int a=sign*(invertA?-1:1), b=sign*(invertB?-1:1); const char *error=nullptr; portENTER_CRITICAL(&motorMux); uint32_t now=millis(); if(!watchdogReady) error="Watchdog unavailable"; else if(epoch!=motorEpoch) error="Stale drive request; reconnect or release"; else if((motorA || motorB) && (motorA!=a || motorB!=b)) error="Stop before reversing"; else if(!motorA && !motorB && now-lastStoppedMs1000) return false; out=negative?-(int)number:(int)number; return out>=minimum && out<=maximum; } bool freshControl() { uint32_t epoch; if(!parseUnsigned(server.arg("controlEpoch"),epoch) || epoch!=controlEpoch) { sendResult(409,"Control state changed; reconnect or try again");return false; } return true; } void handleServo() { if(!freshControl()) return; int id,angle; if(!parseAngle(server.arg("id"),0,4,id) || !parseAngle(server.arg("angle"),lowAngle[id],highAngle[id],angle)) {sendResult(400,"Invalid servo angle");return;} if(!pcaFound) {sendResult(503,"PCA9685 offline");return;} targetServo(id,angle); sendResult(200); } void handleSteer() { if(!freshControl()) return; int angle; String mode=server.arg("mode"); if(!parseAngle(server.arg("angle"),-120,120,angle) || (mode!="counter" && mode!="parallel" && mode!="front")) {sendResult(400,"Invalid steering parameters");return;} if(!pcaFound) {sendResult(503,"PCA9685 offline");return;} steeringAngle=angle; steeringMode=mode; targetServo(3,90+(angle/4)*(invertFront?-1:1)); int rear=mode=="front"?0:angle/4*(mode=="counter"?-1:1); targetServo(4,90+rear*(invertRear?-1:1)); sendResult(200); } void handleConfig() { if(!freshControl()) return; int values[4]; const char *names[]={"a","b","front","rear"}; for(int i=0;i<4;++i) if(!parseAngle(server.arg(names[i]),0,1,values[i])) {sendResult(400,"Invalid configuration");return;} portENTER_CRITICAL(&motorMux); bool running=motorA || motorB; if(!running) {invertA=values[0];invertB=values[1];invertFront=values[2];invertRear=values[3];++motorEpoch;} portEXIT_CRITICAL(&motorMux); sendResult(running?409:200,running?"Stop motors before calibration":nullptr); } void handleFace() { if(!freshControl()) return; String next=server.arg("face"); if(String("|neutral|happy|sad|angry|surprise|fear|disgust|sleep|curious|look-left|look-right|").indexOf("|"+next+"|")<0 || next.length()==0) {sendResult(400,"Unknown face");return;} cameraFollow=false; if(screenCommand("FACE "+next)) {face=next;sendResult(200);} else sendResult(503,"Screen did not acknowledge"); } void handleFollow() { if(!freshControl()) return; int enabled; if(!parseAngle(server.arg("enabled"),0,1,enabled)) {sendResult(400,"Invalid follow mode");return;} cameraFollow=enabled;lastCameraApplied="";sendResult(200); } void handleEmergencyStop() { stopMotors(); ++controlEpoch; cameraFollow=false; for(int i=0;i<5;++i) servoTarget[i]=servoAngle[i]; sendResult(200); } void setup() { Serial.begin(115200); for (uint8_t pin : MOTOR_PINS) { digitalWrite(pin, LOW); pinMode(pin, OUTPUT); digitalWrite(pin, LOW); } stopMotors(); const BaseType_t created = xTaskCreate(motorWatchdog, "motor-stop", 2048, nullptr, 3, nullptr); portENTER_CRITICAL(&motorMux); watchdogReady = created == pdPASS; portEXIT_CRITICAL(&motorMux); pinMode(19,OUTPUT); pinMode(20,OUTPUT); digitalWrite(19,LOW);digitalWrite(20,LOW); cameraSerial.begin(115200,SERIAL_8N1,17,16); Wire.begin(22,23,100000); Wire.setTimeOut(20); pcaFound=probe(0x40); screenFound=probe(0x32); if(pcaFound) { pcaFound=pwm.begin(); if(pcaFound) { pwm.setOscillatorFrequency(27000000);pwm.setPWMFreq(50); for(int i=0;i<6;++i) pwm.setPWM(i,0,4096); } } WiFi.mode(WIFI_AP); WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0)); if (!WiFi.softAP(AP_SSID, AP_PASS)) { Serial.println("Wi-Fi AP failed; motors remain off."); while (true) delay(1000); } server.on("/", HTTP_GET, []() { responseHeaders(); server.send_P(200, "text/html; charset=utf-8", CONTROL_PAGE); }); server.on("/api/motor-state", HTTP_GET, sendState); server.on("/api/state", HTTP_GET, sendState); server.on("/api/motor", HTTP_POST, handleMotor); server.on("/api/stop", HTTP_POST, handleEmergencyStop); server.on("/api/drive-stop", HTTP_POST, handleStop); server.on("/api/drive", HTTP_POST, handleDrive); server.on("/api/servo", HTTP_POST, handleServo); server.on("/api/steer", HTTP_POST, handleSteer); server.on("/api/config", HTTP_POST, handleConfig); server.on("/api/face", HTTP_POST, handleFace); server.on("/api/camera", HTTP_POST, handleFollow); // Preserve the old stop link; reject all old continuous-motion commands. server.on("/api/drive", HTTP_GET, []() { if (server.arg("command") == "stop") handleStop(); else sendResult(409, "Use the v3 control page at http://192.168.4.1"); }); server.onNotFound([]() { responseHeaders(); if (server.method() == HTTP_OPTIONS) server.send(204); else server.send(404, "text/plain; charset=utf-8", "Open http://192.168.4.1"); }); server.begin(); Serial.println("Robot v3.11 master controller started"); Serial.println("IN1=D0/GPIO0 IN2=D1/GPIO1 IN3=D2/GPIO2 IN4=D3/GPIO21"); Serial.println("Wi-Fi: Robot / 12345678"); Serial.println("Open http://192.168.4.1"); Serial.println(watchdogReady ? "Motor watchdog: ready" : "Motor watchdog failed: motors locked"); } void loop() { server.handleClient(); readCamera(); updateServos(); if(millis()-lastProbeMs>2000) { lastProbeMs=millis();screenFound=probe(0x32); bool present=probe(0x40); if(!present) {pcaFound=false;for(int i=0;i<5;++i) {servoEnabled[i]=false;servoTarget[i]=servoAngle[i];}} else if(!pcaFound) { pcaFound=pwm.begin(); if(pcaFound) {pwm.setOscillatorFrequency(27000000);pwm.setPWMFreq(50);for(int i=0;i<6;++i)pwm.setPWM(i,0,4096);} } Serial.printf("PCA9685=%s Screen=%s Camera=%s\n",pcaFound?"OK":"OFFLINE",screenFound?"ACK":"OFFLINE",cameraSeen&&millis()-lastCameraMs<=3000?"DATA":"NO DATA"); } delay(2); }