Connecting to sources…

How to build K2 (open-source 3D-printed 12-DoF biped): the whole process

147 steps to build K2 (open-source 3D-printed 12-DoF biped), from buying parts, printing and assembly to software, calibration and training, with the bill of materials, …

The creator's README BOM totals $320.52 (the builder's own prices, excluding shipping, tax and printer time; the optional Raspberry Pi 5 is not included). The project site separately gives a $224–225 parts subtotal (before controller, printed parts and shipping) and calls it the builder's estimate, not a complete retail BOM. There is no official kit price

Bill of materials · Bill of materials

PartQtyUS
Feetech STS3215 serial bus servo12USD 180
LSM6DS3 I²C IMU breakout1USD 5
Waveshare serial bus servo driver (TTL UART)1USD 10
12 V → 5 V DC/DC converter1USD 3
12 V power supply1USD 20
WiringsetUSD 6
Seeed XIAO ESP32S3 Sense or Raspberry Pi 51
Printed parts, fasteners, mechanical hardwareset
Subtotal before controller, printing and shippingUSD 224

Bill of materials · Bill of materials

PartQty
Feetech STS3215 serial-bus servo · 19.9012
Seeed XIAO ESP32-S3 Sense · 13.991
LSM6DS3 IMU breakout · 4.991
Serial-bus servo interface · 10.501
DC/DC converter · 7.501
Battery · 12.661
Wiring · 4.20–
Switch and connectors · 7.881
Printed material (approx.) · 20.00–

Buy parts

  • Acquire twelve STS3215 servos

    Prepare 12 Feetech STS3215 serial-bus servos operating at 12 V. Each has 2.94 N·m stall torque, 4.712 rad/s no-load speed, and a mass of 60 g.

  • Acquire a CH343 bus adapter

    Prepare one Waveshare CH343 USB-serial adapter with the device identifier `1a86:55d3`. It is used for the single servo serial bus.

  • Choose a Raspberry Pi 5 controller

    Use a Raspberry Pi 5 rather than a Jetson; policy MLP inference takes 0.012 ms on one Pi 5 CPU thread, about 0.06% of a 50 Hz budget. The GPU is only for training or vision models, and a Jetson is justified only if cameras or a VLA are added later.

  • Review BOM and Servo

    The nine-row BOM is a builder's estimate rather than a complete retail list. A DFRobot listing prices a 12 V ST3215 variant at $19.90, raising the subtotal to about $283; confirm the servo voltage and variant before ordering.

Print and make

  • Print Eighteen Parts

    Print the eighteen parts listed in the document.

Assemble

  • Populate Parts with Servos

    Install the servos into the printed parts.

  • Wire the ESP32-S3

    Connect the ESP32-S3 using the four-row wiring table and refer to the linked ESP32-S3 README for the full procedure.

  • Connect the Shared Ground

    Use a shared ground for the wiring.

  • Build the joint link hierarchy

    Use `base_link` and create `Hip_pitch`, `Hip_roll`, `Hip_yaw`, `Knee`, `Ankle`, and `Feet` on each side. Put the sole and collision geometry on `Feet`, not on `Ankle`.

  • Connect the twelve-servo serial bus

    Connect all 12 STS3215 servos to one 12 V serial bus and connect that bus to the controller through the Waveshare CH343 USB-serial adapter.

  • Install the LSM6DS3 IMU

    Mount the LSM6DS3 IMU on the Raspberry Pi 5 inside the electronics tray.

  • Connect the shared ground

    Connect a common ground between the driver and ESP32.

  • Select TTL on the driver

    Select TTL, not USB, on the Waveshare driver. Set the servo UART to 1 Mbps.

Software

  • Preserve exact MJCF joint names

    Map short names to the MJCF joint names while preserving Fusion’s exact auto-label spelling, including “anke” and the word “pitch” inside the roll joint name.

  • Configure Feetech SDK and port

    Install `feetech-servo-sdk`, use the `scservo_sdk` module, and set STS `PacketHandler protocol_end` to 0. Configure the CH343 adapter port as `/dev/ttyACM0` at 1 Mbps.

  • Configure servo register addresses

    Use the ID 5, Baud 6, HomingOffset 31, TorqueEnable 40, GoalPos 42, Lock 55, PresentPos 56, and PresentSpeed 58 registers. PresentSpeed uses sign-magnitude format, with bit 15 indicating direction.

  • Restore serial-port write access

    Restore write access to `/dev/ttyACM0` each time the adapter is replugged. The documented fix is to change its permissions or add the user to the `dialout` group.

  • Use the K2 MJCF model

    The digital-twin model file is `mjcf/k2_physics.xml`. It is built by a three-phase pipeline in `scripts/`.

  • Rebuild masses, inertia, and joint limits
  • Convert the URDF to MJCF

    Run `phase2_make_mjcf.py` to convert the URDF to MJCF, fixing what URDF cannot express.

  • Create a Z-up floating base

    A URDF root compiles into a fixed base. Inject a `world` link and a `type="floating"` joint, then nest the robot tree under the world-aligned root body `k2_root`, which carries the free joint.

  • Convert the base to Z-up

    Fusion is Y-up. Do not rotate every link; give `base_link` the `0.5 0.5 0.5 0.5` quaternion inside `k2_root`.

  • Preserve MuJoCo visual geometry

    Set `discardvisual="false"` in a `<mujoco>` block inside the URDF. Otherwise MuJoCo discards visual geometry and leaves only collision hulls.

  • Enable foot-only collision

    Use feet-only collision on the `Feet_*` bodies so the legs cannot snag against each other.

  • Measure sole positions from collision meshes

    Measure foot sole and site positions from the collision mesh; do not hardcode them.

  • Set the 2 ms timestep

    Use a 2 ms timestep because 5 ms injects contact energy and makes the robot bounce higher than it was dropped. Decimate by 10 for a 50 Hz control loop.

  • Set armature on every hinge

    Set `armature=0.01` on every hinge to reflect rotor inertia. Without it, foot contact chatters and resting IMU acceleration swings wildly.

  • Add base IMU sensors

    Add an IMU site and sensors on `base_link`: `imu_ang_vel` for the gyro, `imu_lin_vel` for the velocimeter, `imu_lin_acc` for the accelerometer, and `imu_quat` for the frame quaternion.

  • Add the root angular-momentum sensor

    Add `root_angmom` as the subtree angular-momentum sensor.

  • Add foot sites and sensors

    Add the `right_foot` and `left_foot` sites, plus heel and toe sites. Attach framepos and framelinvel sensors to them.

  • Add actuators through training or the bus

    The shipped MJCF contains no actuators. mjlab adds them for training, while SimBus adds them for direct control.

  • Unify simulation and real servo bus

    Place the abstraction at the servo bus in raw encoder counts. Calibration, count-to-radian conversion, observation building, clamping, slew limiting, and control rate remain identical on both paths.

  • Define simulation joint order

    In `k2_conventions.py`, define `SIM_ORDER` as the right leg from hip to toe, followed by the left leg.

  • Create joint and calibration mappings

    Configure `JOINT_TO_ID`, `JOINT_TO_MJCF`, `POS_DESC`, and `NUDGE_DIR`; the latter two support calibration.

  • Implement count conversion and calibration storage

    Implement encoder-count-to-radian conversion and calibration load/save in the conventions module. Read joint limits from the MJCF instead of hardcoding them.

  • Export MJCF joint limits

    Use `write_joint_limits()` to generate `joint_limits.json` from the MJCF so the limits cannot drift from the model.

  • Load joint limits on the Pi

    Load the small `joint_limits.json` on the Pi; no MuJoCo installation is needed for this step.

  • Implement the unified servo bus

    Implement the `Bus` ABC, `SerialBus` for a real STS3215, and `SimBus` for MuJoCo in `k2_bus.py`. The interface includes `tick(dt)`, `read_pos_speed()`, `write_goals()`, and `torque(on)`.

  • Emulate hardware count resolution

    Have `SimBus` quantize positions to 12-bit counts and clamp them to `[40,4055]` so the policy sees hardware-grade resolution.

  • Add force-limited position servos

    Add position servos to `SimBus` with the force limited to 2.94 N·m.

  • Implement the safe control loop

    Implement the control loop in `k2_ctrl.py`. Ease the robot from its current pose into the start pose and apply slew limiting.

  • Release torque on exit

    Always release torque when the control program exits, including on Ctrl-C, so the robot goes limp instead of freezing. Provide the `squat` and `hold` modes.

  • Implement flat-foot squat inverse kinematics

    Use `SquatIK` in `k2_motion.py` to solve the flat-foot double-support squat.

  • Configure the IMU attitude mapping

    In `k2_attitude.py`, map chip to root for gravity and map chip to root to site for the policy gyro.

  • Build the k2_rl RL task

    Build `k2_rl` fresh on mjlab's velocity machinery and do not edit the mjlab site-packages.

  • Set proprioceptive-only observations

    Set actor observations to the gyro, projected gravity, joint positions and velocities, last action, and gait command. Do not include base linear velocity because the hardware IMU velocimeter is not trustworthy.

  • Configure STS3215 position servos

    Model the actuators as STS3215 position servos with `kp=20` and `kd=0.5`, matching the values used by `hardware/k2_bus.py`.

  • Set Up the Simulation Environment

    On Linux with a desktop session, clone the K2 repository, create and activate a virtual environment, and install the Raspberry Pi hardware requirements.

  • Build and Flash the ESP32-S3

    Build and flash the onboard ESP32-S3 with PlatformIO by following the ESP32 guide.

  • Configure Raspberry Pi OS

    Use 64-bit Raspberry Pi OS, enable I²C and the serial port in raspi-config, and disable the serial login console.

  • Install Raspberry Pi Dependencies

    Install python3-venv, python3-dev, python3-tk, build-essential, libgl1, and libglfw3.

  • Join Device and Input Groups

    Add the current user to the dialout, i2c, and input groups, then log out and back in.

  • Install Raspberry Pi Hardware Requirements

    Install the Python dependencies from hardware/requirements-pi.txt.

Calibrate and test

  • Correct both knee angle limits

    Set both v3/v4 knee ranges to `[−110°, 0]`. Correct the inverted knee-limit sign on every Fusion re-export.

  • Set asymmetric hip-roll limits

    Configure `hip_roll` for approximately 45° abduction and 22° adduction. Adduction is the tighter side.

  • Set ankle-roll inversion limit

    Set the inward `ankle_roll` limit to 12–20°, the binding direction for lateral weight shifts; the document records a mechanical opening to 20°. If it changes, update `ANKLE_ROLL_IN` in `scripts/phase1_mass.py`.

  • Verify positive ankle directions

    Verify that `+q` on `ankle_roll` drops the foot’s inner edge toward the other foot. Verify that `+q` on `ankle_pitch` lifts the toe for dorsiflexion.

  • Clamp servo goal counts

    Hard-clamp goal counts to `[40, 4055]` everywhere. Do not allow a goal to wrap past 0 or 4095, because the single-turn servo would take the long way around.

  • Confirm MJCF joint-to-servo mapping

    In the MJCF, `_R` joints drive physical-left servos 0..5 and `_L` joints drive physical-right servos 6..11. Fusion's `*_right` bodies sit at +root-Y, which is the robot's physical left.

  • Update calibration.json together with the map

    When swapping the map, swap `calibration.json` with it so every physical servo retains its captured zero and sign. Change both together or neither.

  • Scan or renumber servo IDs one at a time

    Use `python -m hardware.set_servo_id` to scan existing IDs, or `--from N --to M` to renumber, handling one servo at a time.

  • Treat JOINT_TO_ID as the single source of truth

    ID 0 is valid and works through the SDK. The map lives in `k2_conventions.JOINT_TO_ID`, the single source of truth that everything reads.

  • Use a weight-shift gait to detect a leg swap

    Held-air sign checks cannot catch a leg swap because every `POS_DESC` string is mirror-symmetric and a symmetric crouch is invariant. It only shows up once the gait must pick a leg to shift weight onto.

  • Convert servo counts to joint radians

    Calibration maps servo counts to joint radians with `q = sign * (raw - home_raw) * 2π/4096` and back with `raw = home_raw + sign * q * 4096/2π`.

  • Record home_raw at the straight pose

    `home_raw` is the encoder count at the straight pose (q = 0). Sign-flips do not change the home pose: at q=0 every servo goes to `home_raw` regardless of sign.

  • Store each joint's sign in calibration.json

    `sign` is ±1, the direction the joint moves for +q, and is stored in `hardware/calibration.json`.

  • Treat a leaning home pose as a home issue

    A "leaning at home" problem is always a home issue, never a sign, so re-capture the home_raw values.

  • Confirm miscalibration comes only from hardware

    The simulation uses an identity calibration by construction, so miscalibration can only ever come from the hardware.

  • Re-verify all 12 joint signs on hardware

    Re-verify all 12 joints on hardware with `check_joint_signs.py`, covering the hips, knees and all four ankles in both directions.

  • Confirm sign entries after the leg swap

    After the leg swap the entries read +1 for every `_R` joint and −1 for every `_L` joint, because each servo kept the sign measured on it.

  • Launch the GUI and straighten the robot

    Run `python -m hardware.k2_calibrate`; the GUI requires DISPLAY. Set the robot to LIMP (torque off), hand-pose it dead straight, and keep both feet flat on the floor.

  • Capture the HOME pose

    Capture HOME and record `home_raw`. If the robot leans while standing at home, a foot was not flat or a joint was not straight when captured; re-capture instead of flipping signs.

  • Check joint directions and save

    Nudge each joint individually. Flip any joint whose motion disagrees with its description, then save.

  • Enter CROUCH to validate calibration

    Move the robot to CROUCH to validate the calibration.

  • Run the single-leg mirror check

    Crouch each leg alone; the two legs must be mirror images. Home offsets are masked when both feet are planted because the floor constrains them, and appear only when a foot is free during a swing or one-foot balance, so a robot may crouch cleanly but fail during a step.

  • Validate contact and holding torque

    Use `phase3_validate.py` with temporary servos to drop the model onto a vertical slide and check foot contact, tunnelling, and holding torque.

  • Run the 12-servo calibration GUI

    Use `k2_calibrate.py` to open the calibration GUI for 12 servos.

  • Read joint order and scales from ONNX metadata

    Joint order, default pose, action scale and gait frequency all come from the ONNX metadata, so a retrain cannot silently break the deploy path.

  • Confirm torque release and safety limits

    Torque is released on every exit path including Ctrl-C; --slew caps per-tick joint motion, --fall-angle cuts torque above a torso tilt, and before the policy takes over the robot is eased into the default crouch over --approach seconds with the tilt cutoff already armed.

  • Verify servo calibration and joint signs

    All 12 servos are calibrated and all 12 joint signs were verified on hardware in both directions with check_joint_signs.py.

  • Calibrate the IMU mounting level

    The IMU mounting tilt was calibrated with calibrate_imu_level.py, and the gyro frame bug in §9 is fixed.

  • Confirm the permanent leg mapping

    The permanent leg mapping is validated (§3) and no deployment flag is required.

  • Validate the march gait on hardware

    March validation passed for four continuous seconds (about six lifts) at 50 Hz with a 10.82 deg logged peak against a 12 deg cutoff; minimum dynamic servo voltage was 11.9 V and post-run temperatures were 35--39 C.

  • Set the IMU mounting transform

    Use the measured mounting transform `root_x=chip_y`, `root_y=-chip_x`, and `root_z=chip_z`. Level calibration then reduces stationary tilt to 0.028 degrees.

  • Validate and calibrate IMU motion

    Use `k2_imu_motion_test.py` to validate the frame-invariant relationship `gravity_dot = -omega x gravity`. Corrected hardware measured a correlation of 0.990 and a gain of 1.004 over 369 moving samples.

  • Configure domain randomization

    Randomize pseudo-inertia by ±15%, foot friction from 0.4–1.1, PD gains by ×0.8–1.2, encoder bias by ±0.02 rad, base CoM offset, control latency, and random pushes to cover the gaps encountered during bring-up.

  • Set the default standing pose

    Set the default pose to a symmetric standing crouch that remains self-stable under the selected kp and kd.

  • Detect and mount the IMU

    Detect the IMU at 0x6A or 0x6B, and keep its mounting orientation unchanged.

  • Support and power the robot

    Support the robot, then power the driver and ESP32. Keep it still during gyro calibration; boot checks the IMU, all 12 servo replies, and policy output.

  • Enable torque and stand

    Boot automatically approaches the default crouch over five seconds, then verifies torque off. At READY, press Enable torque / stand to begin recording and policy control while keeping the robot supported.

  • Enable Torque With Gamepad

    Center the sticks, then press a trigger plus **A** to enable torque independently of the web page and start the logger/policy. The boot crouch is already complete.

  • Use Alternative Enable Methods

    Alternatively, use the web enable button or send `g` through the serial console. These are alternatives to pressing a trigger plus **A** on the gamepad.

  • Detect Loss by Link State

    BLE HID reports can remain quiet while a stick is held steady. Loss is therefore detected from link state, not notification age.

Data and training

  • Run the Learned Policy

    Run the keyboard script with `policies/last_policy.onnx` as the policy for the K2 simulation.

  • Send Movement Commands

    Click the MuJoCo window and use the keys to control the robot; commands remain active until another key is pressed.

  • Adjust Motion Speeds

    Use `--speed`, `--lateral-speed`, and `--yaw-rate` to change speeds; run `python keyboard.py --help` to see all options.

  • Use an Xbox Controller

    Run `joystick.py` with an Xbox controller to perform the same operations as the keyboard script.

  • Run the Keyboard Policy

    Run keyboard.py on /dev/ttyAMA0 with policies/last_policy.onnx.

  • Run the Joystick Policy

    Pair the Xbox controller first with sudo scripts/pair_xbox.sh, then run joystick.py on /dev/ttyAMA0 with policies/last_policy.onnx.

  • Train the First-Stage Actions

    Run the provided training command; stage one trains hold, march, walking, and turning.

  • Prepare the Lateral-Stepping Policy

    Prepare the lateral-stepping policy from the first-stage model checkpoint; the command reads model_<N>.pt from the specified run directory.

  • Run lateral training

    Run the lateral training command; the shipped policy took about 70 minutes on one RTX PRO 5000.

  • Run the march policy on the real robot

    Run the policy on the real robot over the /dev/ttyAMA0 bus in march mode with policies/last_policy.onnx; the policy takes over after --march-after 5 and runs for --duration 20 s, with --slew 1.0 capping per-tick joint motion and --fall-angle 10 cutting torque above a 10 deg torso tilt.

  • Build the legacy 45-D observation

    The observation is rebuilt as in the march env: base_ang_vel(3), projected_gravity(3), joint_pos_rel(12), joint_vel_rel(12), last_action(12) and gait(3) where gait is [march, march*sin(phase), march*cos(phase)].

  • Record run.csv and debug joint mapping

    --log writes a 50 Hz CSV of commanded vs measured position for all 12 joints plus gyro, gravity, tilt and raw actions; a mis-mapped joint tracks its command perfectly while the IMU response is orthogonal to what that command should produce.

  • Evaluate the low-speed forward task in simulation

    A separate low-speed forward task uses a fourth gait command channel plus integrated relative-yaw feedback; the historical forward-only checkpoint measured 10.1--10.6 mm full-sole clearance at 0.01--0.04 m/s in nominal simulation, and real forward walking remains unvalidated.

  • Select and Run a Learned Policy

    Use `--policy` to specify an ONNX file, not a training `.pt` checkpoint; omitting it selects the shipped policy.

  • Test the Trained Motions

    Run the trained policy to test forward or backward speed, lateral speed, and yaw rate.

Use it

  • Connect to the robot Wi-Fi

    Connect the phone to K2-Robot with password k2robot50. Accept staying offline and open http://192.168.4.1.

  • Move with direction buttons

    Hold a direction button to move and release it to request hold. Browser commands expire after 500 ms without a refresh; closing or hiding the page or losing Wi-Fi requests a smooth stop with additional deceleration time.

  • Release torque and latch stop

    Press Release torque to latch a stop. Support the robot before using it.

  • Reboot the robot to recover

    Use Reboot robot to recover from a stop or fall cutoff without opening the enclosure. Reconnect to K2-Robot if necessary; reboot repeats the automatic crouch and torque release before waiting for policy enable, and keep the robot still during gyro calibration.

  • Scale speed with the joystick

    Joystick deflection scales continuously through the deadzone to ±0.05 m/s forward/backward, ±0.03 m/s lateral, and ±0.30 rad/s turning. Full deflection reaches the limit in either direction.

  • Set web button speeds

    Web buttons start at 0.02 m/s forward/backward, 0.015 m/s lateral, and 0.10 rad/s turning. Open Speed settings to raise these three speeds up to the trained limits; the settings apply only to web buttons and reset on reboot.

  • Retain trained speed limits

    Both web buttons and the joystick retain the policy's trained acceleration and jerk limits, so reaching maximum speed is gradual.

  • Request HOLD with centered input

    With centered joystick or no controls, request the policy's learned HOLD state.

  • Hold a Trigger as Dead-Man

    Hold LT or RT while operating as a dead-man control.

  • Control Movement With Gamepad

    Left stick Y walks, left stick X strafes, and right stick X turns. **A** marches only while held, while **B** requests hold.

  • Request Hold on Release

    When the sticks are centered and **A** is released, the robot requests hold.

  • Hold After Release or Disconnect

    Releasing LT or RT, or disconnecting the controller, requests hold.

  • Reboot With Gamepad Chord

    Press a trigger plus **X** for one second to reboot from running, ready, or fault state. Pressing **X** alone does not reboot.

  • Release Chord Before Reuse

    Release the trigger-and-**X** chord before using it again. Holding it across boot does not cause a reboot loop.

  • Switch Input Control Ownership

    Both web and gamepad inputs remain available. The latest deliberate command takes ownership, and commands from the two sources are never added together.

  • Idle Connections Do Not Steer

    Connecting an idle gamepad or refreshing a held web command does not take ownership away from the active input.

  • Switch Inputs Deliberately

    Move a gamepad stick or press another web direction command to switch ownership to that input.

  • Do Not Resume Older Commands

    Releasing the active input or losing its connection requests hold. An older command from the other source is not resumed.

  • Check the Active Input Status

    The status card shows Web, Gamepad, or Hold, along with the BLE connection state.

  • Gamepad Wins Same-Tick Ties

    When new commands arrive during the same control tick, the gamepad command takes priority.

  • Connect to the Robot and Open Controls

    Join the K2-Robot Wi-Fi network and open http://192.168.4.1, or use an Xbox controller over BLE.

  • Support the Robot While Enabling Torque

    Support the robot when enabling torque; torque cuts out above 24° of tilt.

  • Run the simulated squat with viewer

    Run the `squat` motion through the `sim` bus and open the viewer.

  • Run the squat on the real servo chain

    Switch the bus to `/dev/ttyACM0` and run the `squat` motion on the real servo chain.

Parts

  • 12 Feetech STS3215 serial bus servos (12V, $19.90 each, $238.80 in all) on one 1 Mbaud half-duplex bus
  • Seeed XIAO ESP32-S3 Sense ($13.99); optional Raspberry Pi 5 (not included)
  • LSM6DS3 IMU breakout ($4.99), serial bus servo interface ($10.50; the site says the Waveshare driver must be set to TTL), DC/DC converter ($7.50)
  • Battery ($12.66, spec not stated), switch and connectors ($7.88), wiring ($4.20)
  • 18 printed structural parts (base, lid, controller holder, handle, and per leg three hip links, knee, ankle, foot and sole), about $20 of material; the README mentions the current TPU soles

Tools

  • A 3D printer (model and settings not stated)
  • A computer with PlatformIO to build and flash the ESP32-S3 firmware
  • Optional: an Xbox Bluetooth controller; retraining needs a CUDA GPU

Skills

  • Servo IDs and calibration: set_servo_id to scan, k2_calibrate for the 12 joints, calibrate_imu_level for the IMU's mounting tilt (needed on every new build)
  • Building and flashing the firmware with PlatformIO, and turning a new policy into the ESP32 weight header with export_policy.py
  • Two-stage PPO training with mjlab and RSL-RL (hold, march, walk and turn first, then lateral stepping) and ONNX export

Software

  • esp32-s3/: PlatformIO firmware with web control, Xbox BLE gamepad, flight logging and native tests
  • hardware/: the Raspberry Pi runtime (Python with feetech-servo-sdk, onnxruntime and MuJoCo 3.6.0); one program switches between sim and robot with --bus
  • k2_rl/: mjlab tasks, PPO training, evaluation and ONNX export; policies/last_policy.onnx is the shipped policy
  • The project site's in-browser joint viewer: one slider per joint, labelled with servo ID and limits

Documents