Skip to content

Commit 831982a

Browse files
committed
servo: add function SetAngle() to simplify API for most common use case
Signed-off-by: deadprogram <[email protected]>
1 parent 9063f46 commit 831982a

File tree

2 files changed

+40
-12
lines changed

2 files changed

+40
-12
lines changed

examples/servo/servo.go

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,25 @@ func main() {
2525
return
2626
}
2727

28-
println("setting to 0°")
29-
s.SetMicroseconds(1000)
30-
time.Sleep(3 * time.Second)
28+
for {
29+
println("setting to 0°")
30+
s.SetAngle(0)
31+
time.Sleep(3 * time.Second)
3132

32-
println("setting to 45°")
33-
s.SetMicroseconds(1500)
34-
time.Sleep(3 * time.Second)
33+
println("setting to 45°")
34+
s.SetAngle(45)
35+
time.Sleep(3 * time.Second)
3536

36-
println("setting to 90°")
37-
s.SetMicroseconds(2000)
38-
time.Sleep(3 * time.Second)
37+
println("setting to 90°")
38+
s.SetAngle(90)
39+
time.Sleep(3 * time.Second)
3940

40-
for {
41-
time.Sleep(time.Second)
41+
println("setting to 135°")
42+
s.SetAngle(135)
43+
time.Sleep(3 * time.Second)
44+
45+
println("setting to 180°")
46+
s.SetAngle(180)
47+
time.Sleep(3 * time.Second)
4248
}
4349
}

servo/servo.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package servo
22

3-
import "machine"
3+
import (
4+
"machine"
5+
6+
"errors"
7+
)
8+
9+
var ErrInvalidAngle = errors.New("servo: invalid angle")
410

511
// PWM is the interface necessary for controlling typical servo motors.
612
type PWM interface {
@@ -80,3 +86,19 @@ func (s Servo) SetMicroseconds(microseconds int16) {
8086
value := uint64(s.pwm.Top()) * uint64(microseconds) / (pwmPeriod / 1000)
8187
s.pwm.Set(s.channel, uint32(value))
8288
}
89+
90+
// SetAngle sets the angle of the servo in degrees. The angle should be between
91+
// 0 and 180, where 0 is the minimum angle and 180 is the maximum angle.
92+
// This function should work for most servos, but if it doesn't work for yours
93+
// you can use SetMicroseconds directly instead.
94+
func (s Servo) SetAngle(angle int) error {
95+
if angle < 0 || angle > 180 {
96+
return ErrInvalidAngle
97+
}
98+
99+
// 0° is 1000µs, 180° is 2000µs. See explanation in SetMicroseconds.
100+
microseconds := angle*1000/180 + 1000
101+
s.SetMicroseconds(int16(microseconds))
102+
103+
return nil
104+
}

0 commit comments

Comments
 (0)