diff --git a/src/devices/MotorHat/README.md b/src/devices/MotorHat/README.md index 6392d0de86..34aae2fca8 100644 --- a/src/devices/MotorHat/README.md +++ b/src/devices/MotorHat/README.md @@ -41,6 +41,60 @@ using (var motorHat = new MotorHat()) Check the [ServoMotor documentation](../ServoMotor/README.md) for examples on how to use the ServoMotor class +## Resource management (disposing) + +The `MotorHat` owns all the resources it creates. When you call `CreateDCMotor`, `CreateServoMotor` or `CreatePwmChannel`, the returned object uses PWM channels that belong to the `MotorHat`'s underlying PCA9685 controller. + +Because of this ownership model: + +- **Disposing the `MotorHat` is enough.** `MotorHat.Dispose()` stops every channel it handed out and then disposes the underlying PCA9685 (and its I2C device). You do not need to dispose the motors, servos or PWM channels separately. +- **If you dispose motors explicitly, do it before disposing the `MotorHat`.** A `DCMotor` created by `CreateDCMotor` stops its PWM channels in `Dispose()`, and stopping a channel after the PCA9685 has been disposed can throw. +- **Dispose order matters when disposing both.** Prefer nested `using` (motor inside the `MotorHat` scope) so the motor is disposed first. + +The recommended pattern is to keep the objects you need alive for as long as the `MotorHat` and let a single `using` (or `Dispose`) on the `MotorHat` clean everything up: + +```csharp +using (var motorHat = new MotorHat()) +{ + var motor = motorHat.CreateDCMotor(1); + + motor.Speed = 1; + + // ... use the motor ... + + // No need to dispose 'motor' explicitly; disposing 'motorHat' releases it. +} +``` + +If you wrap the `MotorHat` in your own class, forward disposal to the `MotorHat`. Disposing the individual motors as well is harmless but not required: + +```csharp +public class PumpController : IDisposable +{ + private MotorHat _motorHat = new MotorHat(); + private List _motors = new List(); + + public void Initialize() + { + _motors.Add(_motorHat.CreateDCMotor(1)); + } + + // ... use the motors ... + + public void Dispose() + { + // Dispose motors first (their Dispose stops the PWM channels), + // then dispose the MotorHat which releases the underlying PCA9685 + I2C device. + foreach (var motor in _motors) + { + motor.Dispose(); + } + + _motorHat.Dispose(); + } +} +``` + ## Support - Up to 4 DC Motors