-
Notifications
You must be signed in to change notification settings - Fork 0
Servo API
The Servo class controls a standard servo motor (0–180°) attached to a PWM-capable Arduino pin.
servo = Servo()Creates an un-attached servo. You must call attach(pin) before any movement commands.
Servo.attach(pin: int) -> NoneBind the servo to a PWM-capable digital pin.
| Parameter | Type | Description |
|---|---|---|
pin |
int |
Digital pin number (e.g. 9). |
Requires: A Board must have been created beforehand (it uses Board.get_active_board()).
Raises: RuntimeError if no Board exists.
Board("/dev/ttyUSB0")
servo = Servo()
servo.attach(9)Servo.detach() -> NoneRelease the pin. Clears pin, current_angle, and the internal servo reference. Call attach() again before further movement.
servo.detach()Servo.write(angle: int | float) -> NoneImmediately move the servo to the given angle.
| Parameter | Type | Description |
|---|---|---|
angle |
int/float |
Target angle. Clamped to 0–180 internally. |
Raises:
-
RuntimeErrorif not attached. -
ValueErrorif angle is not a number.
servo.write(90) # centre
servo.write(0) # minimum
servo.write(180) # maximum
servo.write(200) # silently clamped to 180Servo.read() -> intReturn the last angle written via write(), move_smooth(), or sweep().
Raises:
-
RuntimeErrorif not attached. -
RuntimeErrorifwrite()has never been called (angle is unknown).
servo.write(90)
print(servo.read()) # 90Servo.move_smooth(
target_angle: int | float,
delay_ms: int = 15,
) -> NoneMove to target_angle one degree at a time with a pause between steps. Produces a smooth, visible rotation.
| Parameter | Type | Default | Description |
|---|---|---|---|
target_angle |
int/float |
— | Destination angle (clamped 0–180). |
delay_ms |
int |
15 |
Milliseconds between each 1° step. |
Behaviour when current_angle is None: jumps directly to target (same as write()).
Behaviour when target_angle == current_angle: does nothing.
servo.attach(9)
servo.write(0)
servo.move_smooth(180, delay_ms=10) # smooth 0→180Servo.sweep(
start: int | float = 0,
end: int | float = 180,
step: int = 1,
delay_ms: int = 15,
) -> NoneSweep the servo from start to end, stepping by step degrees each delay_ms milliseconds.
| Parameter | Type | Default | Description |
|---|---|---|---|
start |
int/float |
0 |
Starting angle (clamped 0–180). |
end |
int/float |
180 |
Ending angle (clamped 0–180). |
step |
int |
1 |
Degrees per step (must be > 0). |
delay_ms |
int |
15 |
Milliseconds between each step. |
Raises: ValueError if step <= 0.
Works in both directions: start < end sweeps up, start > end sweeps down.
servo.sweep(0, 180, 1, 15) # slow sweep up
servo.sweep(180, 0, 5, 5) # fast sweep downServo.pin -> int | NoneThe pin the servo is attached to, or None if detached.
Servo.current_angle -> int | NoneThe last commanded angle, or None if write() has never been called. Updated by write(), move_smooth(), and sweep().