Community project

Autonomous 4WD Robot Arm

Photo of Autonomous 4WD Robot Arm
Generated with AI

castlevaniageraliza-lang

Published December 3, 2026

This autonomous 4WD robot arm combines wheeled mobility with articulated manipulation, controlled by an ESP32 microcontroller. The platform integrates four brushed DC gearmotors for drive via an L298N H-bridge, servo-driven arm joints managed by a PCA9685 controller, ultrasonic ranging for obstacle detection, and current monitoring through an INA219 sensor. The guide provides a complete wiring diagram, component parts list, and firmware source code to get the robot moving and sensing its environment.

Builders will learn how to configure the ESP32's PWM outputs for motor speed control, communicate with I2C servo and current-sensing modules, and implement interrupt-driven ultrasonic distance measurement. The assembly outline covers motor and servo connections with notes on future power distribution and remote control interfaces, making this an ideal platform for learning robotics fundamentals from the ground up.

Wiring diagram

Wiring diagram for Autonomous 4WD Robot Arm
Loading diagram…

Gather all the parts

QtyComponent
1

Adafruit INA219 Current Sensor (0x40)

I2C logic powered at 3.3 V.

1

PCA9685 Servo Driver (A0 strapped, 0x41)

I2C logic powered at 3.3 V.

1

Resistor

10 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

MG90S Micro Servo

Tower Pro MG90S 9g metal-gear micro servo motor. Controlled via a standard 50 Hz PWM signal (1–2 ms pulse width). Operating voltage 4.8 V–6 V. Three-wire interface: VCC (red), GND (brown/black), and Signal (orange/yellow). Stall torque 1.8 kg·cm at 4.8 V / 2.2 kg·cm at 6 V. Rotation range 0°–180°.

1

MG90S Micro Servo

Tower Pro MG90S 9g metal-gear micro servo motor. Controlled via a standard 50 Hz PWM signal (1–2 ms pulse width). Operating voltage 4.8 V–6 V. Three-wire interface: VCC (red), GND (brown/black), and Signal (orange/yellow). Stall torque 1.8 kg·cm at 4.8 V / 2.2 kg·cm at 6 V. Rotation range 0°–180°.

1

MG90S Micro Servo

Tower Pro MG90S 9g metal-gear micro servo motor. Controlled via a standard 50 Hz PWM signal (1–2 ms pulse width). Operating voltage 4.8 V–6 V. Three-wire interface: VCC (red), GND (brown/black), and Signal (orange/yellow). Stall torque 1.8 kg·cm at 4.8 V / 2.2 kg·cm at 6 V. Rotation range 0°–180°.

1

MG90S Micro Servo

Tower Pro MG90S 9g metal-gear micro servo motor. Controlled via a standard 50 Hz PWM signal (1–2 ms pulse width). Operating voltage 4.8 V–6 V. Three-wire interface: VCC (red), GND (brown/black), and Signal (orange/yellow). Stall torque 1.8 kg·cm at 4.8 V / 2.2 kg·cm at 6 V. Rotation range 0°–180°.

1

Resistor

2.2 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

2.2 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

L298N Dual H-Bridge Module with IN1–IN4

Stage 1 schematic; external actuator supplies are simulation placeholders.

1

6 V Brushed DC Gearmotor

Stage 1 schematic; external actuator supplies are simulation placeholders.

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

1

6 V Brushed DC Gearmotor

Stage 1 schematic; external actuator supplies are simulation placeholders.

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

1

6 V Brushed DC Gearmotor

Stage 1 schematic; external actuator supplies are simulation placeholders.

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

1

6 V Brushed DC Gearmotor

Stage 1 schematic; external actuator supplies are simulation placeholders.

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

1

Resistor

10 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

10 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

HC-SR04

HC-SR04 ultrasonic distance sensor module with separate 40 kHz transmitter and receiver transducers, measuring 2 to 400 cm. A 10 us pulse on TRIG starts a measurement and ECHO stays high for the echo's round-trip time. This HC-SR04+ board runs from 3.3 V or 5 V.

1

Resistor

1.8 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

3.3 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

47 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

10 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

12 mm Tactile Push Button (Round Cap)

Momentary 12 x 12 mm four-leg through-hole tactile push button with a round cap. Closes a normally open contact while pressed; wire diagonally opposite legs between a digital input configured with INPUT_PULLUP and GND.

1

Resistor

10 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

1

12 mm Tactile Push Button (Round Cap)

Momentary 12 x 12 mm four-leg through-hole tactile push button with a round cap. Closes a normally open contact while pressed; wire diagonally opposite legs between a digital input configured with INPUT_PULLUP and GND.

1

12 mm Tactile Push Button (Round Cap)

Momentary 12 x 12 mm four-leg through-hole tactile push button with a round cap. Closes a normally open contact while pressed; wire diagonally opposite legs between a digital input configured with INPUT_PULLUP and GND.

1

Resistor

330 Ω

Through-hole resistor (current-limiting in series with an LED)

1

LED

blue

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

330 Ω

Through-hole resistor (current-limiting in series with an LED)

1

LED

yellow

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

330 Ω

Through-hole resistor (current-limiting in series with an LED)

1

LED

red

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Resistor

680 Ω

Through-hole resistor (current-limiting in series with an LED)

1

LED

green

Standard 3mm/5mm through-hole LED. A current-limiting series resistor is added automatically.

1

Electrolytic Capacitor

470 µF low-ESR, ≥10 V

Radial aluminium electrolytic capacitor bought by value and voltage rating, such as 10 µF, 100 µF or 1000 µF 10 V. It is polarised: the + lead goes to the higher voltage and the - lead, marked by the stripe on the sleeve, to the lower voltage or ground. It is mostly used for bulk filtering across a power rail, with a voltage rating comfortably above the rail.

1

Ceramic Capacitor

100 nF

Through-hole ceramic capacitor bought by value, such as 22 pF, 10 nF or 100 nF (0.1 µF). It is non-polarised, so either lead can go to either net. Its most common job is decoupling: a 100 nF capacitor between an IC's supply pin and ground, placed as close to the chip as possible.

Assemble it in 3 steps

1. Stage 1 simulation only

For each four-leg button, wire diagonally opposite legs to SIGNAL and GND. Pressed closes the contact and reads LOW. Press Rearm with E-Stop and Dead-Man released, then hold Dead-Man. Press E-Stop to latch the stop. At 115200 baud, send DIST 50 for clear range, DIST 15 for an obstacle, DIST -1 for missing echo, or DIST AUTO to return to the sensor.

2. Motor and servo connections

Each L298N output pair feeds two parallel motors on one side. Remove both enable jumpers and the onboard 5 V regulator jumper. Bridge VSS is 5 V logic; VS is a separate modeled 6 V supply. Set PCA9685 A0 closed for 0x41, and use INA219 at 0x40. CH0 through CH3 are pan, shoulder, elbow and gripper. Servo V+ is a separate modeled 5.5 V supply.

  • Do not connect a LiPo or real actuators to this simulation schematic. Motor stall current, switch ratings and braking behavior have not been validated.

3. Future power and remote interfaces

The supply labels stand in for the two physical branches. Branch A stays powered for controller and diagnostics; place the INA219 breakout only on the logic branch unless its shunt and connectors are replaced by a correctly rated design. Branch B needs an independently verified normally closed stop chain, hardware watchdog/latch and rated cutoff upstream of the motor regulator and servo buck. Join logic and power returns at a six-way M3 star point, not through the controller. GPIO6 is the heartbeat; the 100 nF coupling capacitor does not implement a cutoff. The separate ESP32-C3 remote block is planned: SSD1306, two joysticks, NC stop, hold trigger, STOP/RESET and four mode keys; ESP-NOW frames at 50 Hz with receiver freshness checking. Stage 1 uses local controls; no radio receiver or transmitter is loaded.

Review all connections

1. Connections between "ina" and "ESP32"

FunctioninaESP32
powerVCC3V3
groundGNDGND
dataSDAGPIO 4
dataSCLGPIO 5
powerVIN+12.6V
powerVIN-12.6V

2. Connections between "pca" and "ESP32"

FunctionpcaESP32
powerVCC3V3
groundGNDGND
dataSDA → Adafruit INA219 Current Sensor (0x40) SDAEXT
dataSCL → Adafruit INA219 Current Sensor (0x40) SCLEXT
digitalOEGPIO 40
powerV+5.5V

3. Connections between "oe_pull" and "ESP32"

Functionoe_pullESP32
powerP13V3
digitalP2 → PCA9685 Servo Driver (A0 strapped, 0x41) OEEXT

4. Connections between "pan" and "ESP32"

FunctionpanESP32
powerVCC5.5V
groundGNDGND
pwmSIG → PCA9685 Servo Driver (A0 strapped, 0x41) PWM0-PWM15EXT

5. Connections between "shoulder" and "ESP32"

FunctionshoulderESP32
powerVCC5.5V
groundGNDGND
pwmSIG → PCA9685 Servo Driver (A0 strapped, 0x41) PWM0-PWM15EXT

6. Connections between "elbow" and "ESP32"

FunctionelbowESP32
powerVCC5.5V
groundGNDGND
pwmSIG → PCA9685 Servo Driver (A0 strapped, 0x41) PWM0-PWM15EXT

7. Connections between "gripper" and "ESP32"

FunctiongripperESP32
powerVCC5.5V
groundGNDGND
pwmSIG → PCA9685 Servo Driver (A0 strapped, 0x41) PWM0-PWM15EXT

8. Connections between "sda_pull" and "ESP32"

Functionsda_pullESP32
powerP13V3
digitalP2 → Adafruit INA219 Current Sensor (0x40) SDAEXT

9. Connections between "scl_pull" and "ESP32"

Functionscl_pullESP32
powerP13V3
digitalP2 → Adafruit INA219 Current Sensor (0x40) SCLEXT

10. Connections between "bridge" and "ESP32"

FunctionbridgeESP32
powerVS6V
powerVSS5V
groundGNDGND
pwmENAGPIO 7
pwmENBGPIO 8
digitalIN1GPIO 9
digitalIN2GPIO 10
digitalIN3GPIO 11
digitalIN4GPIO 12
dataOUT1 → 6 V Brushed DC Gearmotor T1EXT
dataOUT2 → 6 V Brushed DC Gearmotor T2EXT
dataOUT3 → 6 V Brushed DC Gearmotor T1EXT
dataOUT4 → 6 V Brushed DC Gearmotor T2EXT

11. Connections between "left_front_cap" and "ESP32"

Functionleft_front_capESP32
digital1 → 6 V Brushed DC Gearmotor T1EXT
digital2 → 6 V Brushed DC Gearmotor T2EXT

12. Connections between "left_rear" and "ESP32"

Functionleft_rearESP32
dataT1 → L298N Dual H-Bridge Module with IN1–IN4 OUT1EXT
dataT2 → L298N Dual H-Bridge Module with IN1–IN4 OUT2EXT

13. Connections between "left_rear_cap" and "ESP32"

Functionleft_rear_capESP32
digital1 → 6 V Brushed DC Gearmotor T1EXT
digital2 → 6 V Brushed DC Gearmotor T2EXT

14. Connections between "right_front_cap" and "ESP32"

Functionright_front_capESP32
digital1 → 6 V Brushed DC Gearmotor T1EXT
digital2 → 6 V Brushed DC Gearmotor T2EXT

15. Connections between "right_rear" and "ESP32"

Functionright_rearESP32
dataT1 → L298N Dual H-Bridge Module with IN1–IN4 OUT3EXT
dataT2 → L298N Dual H-Bridge Module with IN1–IN4 OUT4EXT

16. Connections between "right_rear_cap" and "ESP32"

Functionright_rear_capESP32
digital1 → 6 V Brushed DC Gearmotor T1EXT
digital2 → 6 V Brushed DC Gearmotor T2EXT

17. Connections between "pwm7_pull" and "ESP32"

Functionpwm7_pullESP32
digitalP1 → L298N Dual H-Bridge Module with IN1–IN4 ENAEXT
groundP2GND

18. Connections between "pwm8_pull" and "ESP32"

Functionpwm8_pullESP32
digitalP1 → L298N Dual H-Bridge Module with IN1–IN4 ENBEXT
groundP2GND

19. Connections between "sonar" and "ESP32"

FunctionsonarESP32
powerVCC5V
groundGNDGND
digitalTRIGGPIO 15

20. Connections between "echo_top" and "ESP32"

Functionecho_topESP32
digitalP1 → HC-SR04 ECHOEXT
digitalP2GPIO 16

21. Connections between "echo_bottom" and "ESP32"

Functionecho_bottomESP32
digitalP1 → Resistor P2EXT
groundP2GND

22. Connections between "vbat_top" and "ESP32"

Functionvbat_topESP32
powerP112.6V
digitalP2GPIO 1

23. Connections between "vbat_bottom" and "ESP32"

Functionvbat_bottomESP32
digitalP1 → Resistor P2EXT
groundP2GND

24. Connections between "stop" and "ESP32"

FunctionstopESP32
digitalSIGNALGPIO 14
groundGNDGND

25. Connections between "stop_pull" and "ESP32"

Functionstop_pullESP32
digitalP1 → 12 mm Tactile Push Button (Round Cap) SIGNALEXT
powerP23V3

26. Connections between "stop_cap" and "ESP32"

Functionstop_capESP32
digital1 → 12 mm Tactile Push Button (Round Cap) SIGNALEXT
ground2GND

27. Connections between "deadman" and "ESP32"

FunctiondeadmanESP32
digitalSIGNALGPIO 13
groundGNDGND

28. Connections between "rearm" and "ESP32"

FunctionrearmESP32
digitalSIGNALGPIO 2
groundGNDGND

29. Connections between "blue_r" and "ESP32"

Functionblue_rESP32
digitalP1GPIO 17
digitalP2 → LED ANODEEXT

30. Connections between "blue" and "ESP32"

FunctionblueESP32
groundGNDGND

31. Connections between "yellow_r" and "ESP32"

Functionyellow_rESP32
digitalP1GPIO 18
digitalP2 → LED ANODEEXT

32. Connections between "yellow" and "ESP32"

FunctionyellowESP32
groundGNDGND

33. Connections between "red_r" and "ESP32"

Functionred_rESP32
digitalP1GPIO 21
digitalP2 → LED ANODEEXT

34. Connections between "red" and "ESP32"

FunctionredESP32
groundGNDGND

35. Connections between "green_r" and "ESP32"

Functiongreen_rESP32
powerP15V
digitalP2 → LED ANODEEXT

36. Connections between "green" and "ESP32"

FunctiongreenESP32
groundGNDGND

37. Connections between "logic_cap" and "ESP32"

Functionlogic_capESP32
power+5V
ground-GND

38. Connections between "heartbeat_cap" and "ESP32"

Functionheartbeat_capESP32
digital1GPIO 6
digital2 → Future watchdog input conditioningEXT

Deploy the firmware

#include <Arduino.h>
#include <Wire.h>
#include <ctype.h>
#include <math.h>
#include <Adafruit_NeoPixel.h>
#include <esp_arduino_version.h>
constexpr int STOP=14, DEAD=13, RESET=2, OE=40;
Adafruit_NeoPixel rgb(1,48,NEO_GRB+NEO_KHZ800);
portMUX_TYPE mux=portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t rise=0,width=0,stamp=0;
volatile bool rising=false, ready=false;
void IRAM_ATTR echoEdge(){
 uint32_t t=micros(); bool high=digitalRead(16);
 portENTER_CRITICAL_ISR(&mux);
 if(high){rise=t;rising=true;} else if(rising){width=t-rise;stamp=t;ready=true;rising=false;}
 portEXIT_CRITICAL_ISR(&mux);
}
void duty(int pin,int value){
#if ESP_ARDUINO_VERSION_MAJOR >= 3
 ledcWrite(pin,value);
#else
 ledcWrite(pin-7,value);
#endif
}
void speeds(int d){duty(7,d);duty(8,d);}
void direction(bool brake){for(int i=9;i<=12;i++)digitalWrite(i,brake || (i%2));}
bool reg(uint8_t address,uint8_t value){Wire.beginTransmission(0x41);Wire.write(address);Wire.write(value);return Wire.endTransmission()==0;}
bool pose(int ch,int angle){
 int count=205+angle*205/180;
 Wire.beginTransmission(0x41); Wire.write(6+4*ch);Wire.write(0);Wire.write(0);Wire.write(count&255);Wire.write(count>>8);return Wire.endTransmission()==0;
}
bool armed=false,latched=false,hb=false,trig=false,valid=false,driving=false,braking=false,pcaOK=false,resetReady=false;
uint32_t lastHb,lastPing,lastTick,lastLog,brakeAt,lastEcho;
int32_t dist=0,cov=4<<16,raw=0;
int angles[]={90,90,90,20}, targets[]={90,105,75,15};
enum State {IDLE, ACTIVE, HOLD, ESTOP};
State state=IDLE, shown=ESTOP;
const char* names[]={"IDLE_SAFE","ACTIVE_DRIVE","OBSTACLE_HOLD","ESTOP_CUTOFF"};
enum Mode { DRIVE, RADAR, ARM, PARK };
Mode mode=DRIVE;
bool virtualStop=false, virtualDead=false, rearm=false;
int injected=-2; // -2: hardware, -1: simulated missing echo
bool inaOK=false;
float fallbackVbat=11.80f;
bool overrideVbat=false;
void execute(char* line, Stream& reply){
 while(isspace((unsigned char)*line))++line;
 char* end=line+strlen(line);
 while(end>line && isspace((unsigned char)end[-1]))*--end=0;
 if(!*line)return;
 bool ok=true;
  if(!strcmp(line,"ESTOP 1")){virtualStop=true;latched=true;armed=false;}
  else if(!strcmp(line,"ESTOP 0"))virtualStop=false;
  else if(!strcmp(line,"DEAD 1"))virtualDead=true;
  else if(!strcmp(line,"DEAD 0"))virtualDead=false;
  else if(!strcmp(line,"REARM"))rearm=!virtualStop && !virtualDead && digitalRead(STOP) && digitalRead(DEAD);
  else if(!strcmp(line,"MODE 4WD"))mode=DRIVE;
  else if(!strcmp(line,"MODE RADAR"))mode=RADAR;
  else if(!strcmp(line,"MODE ARM"))mode=ARM;
  else if(!strcmp(line,"MODE IDLE")){mode=PARK;armed=false;}
  else if(!strcmp(line,"DIST AUTO")){injected=-2;valid=false;}
  else if(!strncmp(line,"DIST ",5)){
   char* tail;long n=strtol(line+5,&tail,10);
   ok=tail!=line+5 && !*tail && (n==-1 || (n>=2 && n<=400));
   if(ok){injected=n;if(n==-1)valid=false;}
  }else if(!strncmp(line,"VBAT ",5)){
   char* tail;float v=strtof(line+5,&tail);
   ok=tail!=line+5 && !*tail && isfinite(v) && v>=0 && v<=20;
   if(ok){fallbackVbat=v;overrideVbat=true;}
  }else ok=false;
 reply.print(ok?"CMD OK: ":"CMD ERR: ");reply.println(line);
}
struct CommandInput {
 char line[48]; unsigned len=0; bool overflow=false; uint32_t lastByte=0;
 void finish(Stream& port){
  if(overflow)port.println("CMD ERR: line too long");
  else if(len){line[len]=0;execute(line,port);}
  len=0;overflow=false;
 }
 void poll(Stream& port){
  for(int budget=64;budget && port.available();--budget){
   int c=port.read();if(c<0)break;
   lastByte=millis();
   if(c=='\r'||c=='\n')finish(port);
   else if(len<sizeof(line)-1)line[len++]=char(c);
   else overflow=true;
  }
  if((len||overflow) && !port.available() && millis()-lastByte>=100)finish(port);
 }
};
void commands(){
 static CommandInput primary;
 primary.poll(Serial);
#if ARDUINO_USB_CDC_ON_BOOT
 static CommandInput uart;
 uart.poll(Serial0);
#endif
}
bool probe(uint8_t addr){Wire.beginTransmission(addr);return Wire.endTransmission()==0;}
float battery(){
 if(overrideVbat)return fallbackVbat;
 uint32_t mv=analogReadMilliVolts(1);
 if(mv>=1000)return mv*0.0057f;
 if(!inaOK)return fallbackVbat;
 Wire.beginTransmission(0x40);Wire.write(0x02);
 // Use a STOP between register selection and read for simulator compatibility.
 if(Wire.endTransmission()!=0 || Wire.requestFrom(uint8_t(0x40),uint8_t(2))!=2){
  inaOK=false;return fallbackVbat;
 }
 uint16_t bus=uint16_t(Wire.read())<<8;bus|=Wire.read();
 return (bus>>3)*0.004f;
}
void setup(){
 Serial.begin(115200);
#if ARDUINO_USB_CDC_ON_BOOT
 Serial0.begin(115200);
#endif
 for(int pin:{6,7,8,9,10,11,12,15,17,18,21,OE})pinMode(pin,OUTPUT);
 digitalWrite(OE,HIGH);
 for(int pin:{STOP,DEAD,RESET})pinMode(pin,INPUT_PULLUP);
#if ESP_ARDUINO_VERSION_MAJOR >= 3
 ledcAttach(7,20000,8);ledcAttach(8,20000,8);
#else
 for(int pin:{7,8}){ledcSetup(pin-7,20000,8);ledcAttachPin(pin,pin-7);}
#endif
 speeds(0); pinMode(16,INPUT);attachInterrupt(digitalPinToInterrupt(16),echoEdge,CHANGE);
 Wire.begin(4,5,400000);Wire.setTimeOut(2);
 latched=!digitalRead(STOP);
 inaOK=probe(0x40);
 pcaOK=probe(0x41);
 pcaOK=pcaOK&&reg(0,0x10)&&reg(0xfe,121)&&reg(0,0x20);
 rgb.begin();rgb.setBrightness(24);
}
void loop(){
 commands();
 bool stop=!digitalRead(STOP)||virtualStop, dead=!digitalRead(DEAD)||virtualDead, reset=!digitalRead(RESET);
 bool resetEdge=reset && resetReady;
 resetReady=!reset;
 if(stop){latched=true;armed=false;}
 else if(!dead && (resetEdge || rearm)){latched=false;armed=true;}
 rearm=false;
 uint32_t now=micros(),w=0,t=0;
 portENTER_CRITICAL(&mux);
 if(ready){w=width;t=stamp;ready=false;}
 portEXIT_CRITICAL(&mux);
 if(injected==-1 || (valid && uint32_t(now-lastEcho)>150000)) valid=false;
 static uint32_t lastSample=0;
 bool synthetic=injected>=0 && uint32_t(now-lastSample)>=20000;
 if(synthetic || (injected==-2 && w>=116 && w<=23200)){
  lastSample=now;
  raw=synthetic?(injected<<16):w*1124L;
  if(!valid){dist=raw;cov=4<<16;}
  else {cov+=1<<16;int32_t k=(int64_t(cov)<<16)/(cov+(9<<16));dist+=(int64_t(k)*(raw-dist))>>16;cov=(int64_t(65536-k)*cov)>>16;}
  valid=true;lastEcho=synthetic?now:t;
 }
 state=latched?ESTOP:!armed||!dead||mode==PARK?IDLE:!valid||raw<(20<<16)||dist<(20<<16)?HOLD:ACTIVE;
 if((state!=ACTIVE || mode!=DRIVE) && driving){
  speeds(0);driving=false;direction(true);speeds(255);braking=true;brakeAt=now;
 }
 if(braking && uint32_t(now-brakeAt)>=15000){speeds(0);braking=false;}
 if(state!=ACTIVE)digitalWrite(OE,HIGH);
 if(latched){hb=false;digitalWrite(6,LOW);lastHb=now;}
 else if(uint32_t(now-lastHb)>=10000){lastHb=now;hb=!hb;digitalWrite(6,hb);}
 if(trig && uint32_t(now-lastPing)>=10){digitalWrite(15,LOW);trig=false;}
 if(!trig && uint32_t(now-lastPing)>=60000){lastPing=now;trig=true;digitalWrite(15,HIGH);}
 if(uint32_t(now-lastTick)>=20000){
  lastTick=now;
  if(state==ACTIVE && !braking){
   if(mode==DRIVE && !driving){direction(false);speeds(170);driving=true;}
   if(pcaOK){
    static int panTarget=145;
    int first=mode==ARM?1:0, end=mode==RADAR?1:4;
    if(mode==RADAR){
     if(angles[0]==panTarget)panTarget=panTarget==145?35:145;
     targets[0]=panTarget;
    }else targets[0]=90;
    for(int ch=first;ch<end && pcaOK;++ch){
     angles[ch]+=constrain(targets[ch]-angles[ch],-2,2);
     pcaOK=pose(ch,angles[ch]);
    }
    digitalWrite(OE,!pcaOK);
   }
  }
 }
 if(shown!=state){shown=state;digitalWrite(17,state==ACTIVE);digitalWrite(18,state==HOLD);digitalWrite(21,state==ESTOP);
  rgb.setPixelColor(0,state==ESTOP?rgb.Color(255,0,0):state==HOLD?rgb.Color(255,90,0):state==ACTIVE?rgb.Color(0,0,255):0);rgb.show();}
 if(uint32_t(now-lastLog)>=200000 && Serial.availableForWrite()>=100){
  lastLog=now;float vb=battery();
  Serial.printf("%s cm=%.1f Vbat=%.2f dead=%d stop=%d servo=%d,%d,%d,%d\n",names[state],valid?dist/65536.0f:-1.0f,vb,dead,latched,angles[0],angles[1],angles[2],angles[3]);
 }
}
// GPIO4/5 route Wire through the ESP32-S3 GPIO matrix.

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik