diff --git a/examples/servo/servo.go b/examples/servo/servo.go index c986d84..a38d25d 100644 --- a/examples/servo/servo.go +++ b/examples/servo/servo.go @@ -25,19 +25,25 @@ func main() { return } - println("setting to 0°") - s.SetMicroseconds(1000) - time.Sleep(3 * time.Second) - - println("setting to 45°") - s.SetMicroseconds(1500) - time.Sleep(3 * time.Second) - - println("setting to 90°") - s.SetMicroseconds(2000) - time.Sleep(3 * time.Second) - for { - time.Sleep(time.Second) + println("setting to 0°") + s.SetAngle(0) + time.Sleep(3 * time.Second) + + println("setting to 45°") + s.SetAngle(45) + time.Sleep(3 * time.Second) + + println("setting to 90°") + s.SetAngle(90) + time.Sleep(3 * time.Second) + + println("setting to 135°") + s.SetAngle(135) + time.Sleep(3 * time.Second) + + println("setting to 180°") + s.SetAngle(180) + time.Sleep(3 * time.Second) } } diff --git a/servo/servo.go b/servo/servo.go index 5be92ac..73ef8e0 100644 --- a/servo/servo.go +++ b/servo/servo.go @@ -1,6 +1,12 @@ package servo -import "machine" +import ( + "machine" + + "errors" +) + +var ErrInvalidAngle = errors.New("servo: invalid angle") // PWM is the interface necessary for controlling typical servo motors. type PWM interface { @@ -80,3 +86,19 @@ func (s Servo) SetMicroseconds(microseconds int16) { value := uint64(s.pwm.Top()) * uint64(microseconds) / (pwmPeriod / 1000) s.pwm.Set(s.channel, uint32(value)) } + +// SetAngle sets the angle of the servo in degrees. The angle should be between +// 0 and 180, where 0 is the minimum angle and 180 is the maximum angle. +// This function should work for most servos, but if it doesn't work for yours +// you can use SetMicroseconds directly instead. +func (s Servo) SetAngle(angle int) error { + if angle < 0 || angle > 180 { + return ErrInvalidAngle + } + + // 0° is 1000µs, 180° is 2000µs. See explanation in SetMicroseconds. + microseconds := angle*1000/180 + 1000 + s.SetMicroseconds(int16(microseconds)) + + return nil +}