servo: add function SetAngle() to simplify API for most common use case

Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
deadprogram
2024-05-21 19:16:22 +02:00
committed by Ron Evans
parent 9063f46313
commit 831982ad33
2 changed files with 42 additions and 14 deletions
+11 -5
View File
@@ -25,19 +25,25 @@ func main() {
return
}
for {
println("setting to 0°")
s.SetMicroseconds(1000)
s.SetAngle(0)
time.Sleep(3 * time.Second)
println("setting to 45°")
s.SetMicroseconds(1500)
s.SetAngle(45)
time.Sleep(3 * time.Second)
println("setting to 90°")
s.SetMicroseconds(2000)
s.SetAngle(90)
time.Sleep(3 * time.Second)
for {
time.Sleep(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)
}
}
+23 -1
View File
@@ -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
}