# SO-101 inverse kinematics and driver in C, for LeRobot arms

Inverse kinematics and a safe servo driver for the **SO-101 / SO-ARM101** robot arm (LeRobot's
follower) in **C**, with a **Python** binding: a drop-in for **LeRobot's `RobotKinematics`** that is
3.6 to 41 times faster, the least-loaded pose for any tip position, a mesh collision check, moves
that stop on a stall or an overload, and **figures drawn in the air as fast as the servos go**. C99
that allocates nothing (the desktop serial port aside), so it is ready for an **ESP32**

Here: the install, the arm's setup, the samples and the safety rules, to read before the first run. Every
call with its arguments: [agents/python-api.md](agents/python-api.md) [agents/c-api.md](agents/c-api.md) The
longer earlier version, with the timings and each run's numbers:
[README.md at 4196c4d](https://github.com/stepankandrushin/lerobot-so101-inverse-kinematics/blob/4196c4d/README.md)

![An SO-101 follower draws a 30 cm heart in the air three times, in real time](media/heart.gif)

*`examples/figures/heart.py --size 30` **in real time**, the tip at up to 93 cm/s, 8.7 s from the command to the
torque off. Grey the planned heart, yellow the tip's trail from the servos.*

```python
from so101ik import Arm
from so101ik.fast import closed_run

with Arm() as arm:                     # finds the port and LeRobot's calibration; torque on
    arm.move_to(0.20, 0.12, 0.18)      # unfolds, then the tip to x, y, z in metres, in the pose gravity loads least
    arm.move_by(0, 0.08, 0)            # a straight line 8 cm to the left
    arm.run(closed_run(arm.model, points, laps=3))   # a closed path of tip points 2 mm apart, at the servos' limits
                                       # leaving the block folds the arm home, also after Ctrl-C
```

## What it does

- **The pose picked.** A tip position leaves the 5-joint arm one free angle, the gripper's pitch: `Model.ik` tries
  them all in closed form and returns the allowed pose with the least gravity torque on the servos, inside the
  calibrated ranges, clear of the table, no part of the arm within 8 mm of another (on the URDF's meshes).
- **LeRobot's `RobotKinematics` compiled**: the same two calls and arguments; where its steps miss the tip by over
  1 mm, the closed-form pose. Timings against LeRobot's: [agents/measurements.md](agents/measurements.md)
- **A driver for the Feetech STS3215 servos**: minimum-jerk moves with goals every 20 ms, and fast runs replayed at
  100 Hz at full torque, each goal leading its joint by the servo's lag.

## What you need

- An **SO-101 follower**, assembled, its servo ids set and **calibrated with LeRobot** `lerobot-setup-motors`
  `lerobot-calibrate` LeRobot is needed for that, not to run this.
- **macOS or Linux.** On Linux your user in `dialout` `sudo usermod -aG dialout $USER` then log in again. It has
  driven arms from macOS; on Linux it builds and passes its tests but has not driven an arm yet: reports welcome.
- **Python 3.12+**, **[uv](https://docs.astral.sh/uv/)** or pip, and a C compiler: `xcode-select --install` on
  macOS, `sudo apt install build-essential` on Debian or Ubuntu.

## Install

```sh
git clone https://github.com/stepankandrushin/lerobot-so101-inverse-kinematics
cd lerobot-so101-inverse-kinematics
uv sync                                 # builds the C extension
uv run examples/kinematics.py           # the kinematics alone: no arm needed
```

From another project, with uv:

```sh
uv add git+https://github.com/stepankandrushin/lerobot-so101-inverse-kinematics
```

or with pip:

```sh
pip install git+https://github.com/stepankandrushin/lerobot-so101-inverse-kinematics
```

## The port and the calibration

`Arm()` finds both by itself:

- **The calibration**: the one file `lerobot-calibrate` wrote for a follower,
  `~/.cache/huggingface/lerobot/calibration/robots/so_follower/<id>.json` (`so101_follower/` before LeRobot 0.4);
  `HF_LEROBOT_CALIBRATION` `HF_LEROBOT_HOME` and `HF_HOME` move the folder as for LeRobot.
- **The port**: the one USB serial port (macOS `/dev/tty.usbmodem*` `/dev/tty.usbserial*` Linux `/dev/ttyACM*`
  `/dev/ttyUSB*`); with several, as with the leader plugged in too, the one whose servos hold that calibration in
  their EEPROM, a check that only reads.

When it cannot tell, it stops and says what to set, or pass `Arm(port=..., calibration_file=...)`

```sh
export SO101_CALIBRATION=~/.cache/huggingface/lerobot/calibration/robots/so_follower/my_follower.json
export SO101_PORT=/dev/tty.usbmodem58760431541    # lerobot-find-port tells which: it asks you to unplug the board
```

**Offsets**, if the tip lands consistently off: degrees per joint, URDF angle = calibrated angle + offset, 0 unless
set. They belong to the arm, so they sit beside its calibration as `my_follower.offsets` (never a second `.json`
there: `Arm()` would find two calibrations); `SO101_OFFSETS` overrides the file for one shell. The format:
[agents/python-api.md](agents/python-api.md) Offsets.

## Run the samples

Read Safety first. Then, with the arm folded in its rest pose and nothing within its reach:

```sh
uv run examples/triangle.py
```

The arm unfolds, moves its gripper to 20 cm in front of the base, 12 cm to the left and 18 cm up, draws a triangle
8 cm along and 7 cm high at 5 cm/s, and folds home. Every tick goes to `outputs/so101ik/triangle.csv` every event
to `triangle.log` beside it; `uv run tools/run_stats.py outputs/so101ik/triangle.csv` says how closely the tip
followed each line. Coordinates are metres in the URDF's base frame: x forward, y to the arm's left, z up.

- **Where the tip is** `uv run examples/where.py` switches the torque off (hold a raised arm) and prints the tip in
  mm and the gripper's pitch 20 times a second while you move the arm by hand. `./build/where PORT [ID.offsets]`
  after `make example` is the same in C, the calibration read from the servos' EEPROM.
- **Without an arm** `SO101_PORT=sim` or `Arm(port="sim")` runs a program on six simulated servos with a clock of
  their own, so a minute of moves takes a moment. They lag their goals as real ones do but have no gravity: they
  try a program's logic, not its accuracy.

### Figures, as fast as the servos go

```sh
uv run examples/figures/heart.py --dry      # plan it and print the timing: nothing moves, no arm needed
uv run examples/figures/heart.py            # a 24 cm heart, three laps, in front of the arm
uv run examples/figures/heart.py --size 30 --facing 0.8 1.2 0.9    # 30 cm, turned towards a camera there
uv run examples/figures/show.py circle star heart                  # three in one run
```

`examples/figures/` circle square triangle star infinity heart waves spiral clover flower, each a script with its
coordinates `POINTS` alone; `dance.py` nine with the jaws and the wrist's roll moving. A new figure is a copy of
`heart.py` with other `POINTS` a closed curve, x right and y up in any unit, or up to 20 corners of a polygon. The
figure lies in a plane 30 cm from the shoulder facing `--facing` (by default a viewer 1.5 m in front, 75 cm up);
a heart plans up to 32 cm across. `--speed 0.5` halves every speed; `--pitch` `--learn` and the rest:
[agents/python-api.md](agents/python-api.md) Figures.

## Safety

- **Start folded.** The arm unfolds from its rest pose (lift and elbow against their stops, gripper on the table in
  front of the base) on its first move and folds back to exactly there; started anywhere else it does not unfold,
  and home is the fold found from the calibration's ranges.
- **Clear the table**: the library knows the table plane and the arm's own parts, nothing else.
- **Ctrl-C** stops the move and the arm folds home. A **second Ctrl-C** switches the torque off and the arm drops:
  hold it. A kill (SIGTERM) or a hang-up counts as Ctrl-C.
- **It stops by itself** on a stall (an arm joint over 7 degrees behind its goal that moves under half a degree
  in 0.3 s) or an overload (45 % of the servo's torque for 0.3 s): every goal freezes where its joint stands, the
  call raises `Fault` and leaving the `with` block folds the arm home.
- **The servos are limited** at torque-on: Torque_Limit at most 500 (50 %) and Acceleration 254, written to RAM so
  a power cut restores the servos' own.
- **A fast run is not**: Torque_Limit 1000 and Acceleration 0, the tip at over 1 m/s; 500 and 254 come back when the
  arm is folded, after a stop and at the next torque-on. It stops (every goal where its joint stands, then home at
  the slow pace) when a joint is 12 degrees off for 0.15 s (6 on the way out of the rest pose and back), at full
  load for 0.4 s, or on Ctrl-C.
- **The limits are a 12 V follower's** (STS3215 12 V, up to 220 degrees/s). A 7.4 V arm's servos are slower: start
  with `--speed 0.6` and go slower if a run stops with a joint behind.
- **The fast way out of the rest pose needs room**: it is taken only where the model clears it with lift, elbow and
  wrist flex 6 degrees off. An arm whose folded gripper lies on the table in the model (offsets of 0, often)
  unfolds and folds at the slow pace instead.
- **It refuses another arm's calibration**: if a servo's Homing_Offset or limits differ from the file, nothing
  moves.
- **One program on the bus at a time**, not while LeRobot (teleoperation, recording) uses the port: the packets
  would collide.
- **From C** the calibration check, the unfold and putting back the slow settings are the caller's:
  [agents/c-api.md](agents/c-api.md)

## Python API

`from so101ik import Arm, Model, RobotKinematics, Pose, Unreachable, Fault, GripLost, SetupError` Every call:
[agents/python-api.md](agents/python-api.md). `RobotKinematics` is LeRobot's class with the same calls; in
LeRobot's end-effector examples and processors, change one import:

```python
# from lerobot.model.kinematics import RobotKinematics
from so101ik import RobotKinematics
```

## C API

Everything is in [`include/so101ik.h`](include/so101ik.h): functions `so101_*` constants `SO101_*` `make` builds
`build/libso101ik.a` link with `-lm` The calls, what a C caller does that `Arm` does for Python, a new board's HAL
and the build flags: [agents/c-api.md](agents/c-api.md)

## ESP32

Not built yet; the library is written for it, single precision giving the poses double gives. The plan, memory and
time to commands over Wi-Fi, Bluetooth or buttons: [agents/esp32.md](agents/esp32.md)

## Development

The commands and the rules for changing it: [AGENTS.md](AGENTS.md); how it works: [agents/design.md](agents/design.md)

## License

Apache-2.0 as SO-ARM100 and LeRobot are. `src/model.c` is derived from SO-ARM100 by TheRobotStudio:
see [NOTICE](NOTICE). Not affiliated with TheRobotStudio or Hugging Face.
