From 88209991c674a1975b9a8ac8a4a60f135400451a Mon Sep 17 00:00:00 2001 From: p1 Date: Sun, 26 Jul 2026 23:16:44 +0530 Subject: [PATCH] fix: allow disabling continuous servos --- adafruit_motor/servo.py | 16 ++++++++++------ tests/test_servo.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 tests/test_servo.py diff --git a/adafruit_motor/servo.py b/adafruit_motor/servo.py index ae8ffc0..a32ae0f 100644 --- a/adafruit_motor/servo.py +++ b/adafruit_motor/servo.py @@ -140,18 +140,22 @@ class ContinuousServo(_BaseServo): :param int max_pulse: The maximum pulse width of the servo in microseconds.""" @property - def throttle(self) -> float: + def throttle(self) -> Optional[float]: """How much power is being delivered to the motor. Values range from ``-1.0`` (full throttle reverse) to ``1.0`` (full throttle forwards.) ``0`` will stop the motor from - spinning.""" - return self.fraction * 2 - 1 + spinning. Is ``None`` when the servo is disabled.""" + fraction = self.fraction + if fraction is None: + return None + return fraction * 2 - 1 @throttle.setter - def throttle(self, value: float) -> None: + def throttle(self, value: Optional[float]) -> None: + if value is None: + self.fraction = None + return if value > 1.0 or value < -1.0: raise ValueError("Throttle must be between -1.0 and 1.0") - if value is None: - raise ValueError("Continuous servos cannot spin freely") self.fraction = (value + 1) / 2 def __enter__(self) -> "ContinuousServo": diff --git a/tests/test_servo.py b/tests/test_servo.py new file mode 100644 index 0000000..f1c5735 --- /dev/null +++ b/tests/test_servo.py @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: 2026 Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +"""Tests for servo functionality.""" + +import pytest + +from adafruit_motor.servo import ContinuousServo + + +class PWMOut: + """Minimal PWM output used by servo tests.""" + + def __init__(self) -> None: + self.frequency = 50 + self.duty_cycle = 0 + + +def test_continuous_servo_can_be_disabled_and_reenabled() -> None: + """Setting throttle to None disables PWM and remains readable.""" + pwm = PWMOut() + servo = ContinuousServo(pwm) + + servo.throttle = 0.5 + assert servo.throttle == pytest.approx(0.5, abs=0.001) + + servo.throttle = None + assert pwm.duty_cycle == 0 + assert servo.throttle is None + + servo.throttle = -0.5 + assert servo.throttle == pytest.approx(-0.5, abs=0.001)