File tree Expand file tree Collapse file tree 2 files changed +40
-12
lines changed Expand file tree Collapse file tree 2 files changed +40
-12
lines changed Original file line number Diff line number Diff line change @@ -25,19 +25,25 @@ func main() {
25
25
return
26
26
}
27
27
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 )
31
32
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 )
35
36
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 )
39
40
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 )
42
48
}
43
49
}
Original file line number Diff line number Diff line change 1
1
package servo
2
2
3
- import "machine"
3
+ import (
4
+ "machine"
5
+
6
+ "errors"
7
+ )
8
+
9
+ var ErrInvalidAngle = errors .New ("servo: invalid angle" )
4
10
5
11
// PWM is the interface necessary for controlling typical servo motors.
6
12
type PWM interface {
@@ -80,3 +86,19 @@ func (s Servo) SetMicroseconds(microseconds int16) {
80
86
value := uint64 (s .pwm .Top ()) * uint64 (microseconds ) / (pwmPeriod / 1000 )
81
87
s .pwm .Set (s .channel , uint32 (value ))
82
88
}
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
+ }
You can’t perform that action at this time.
0 commit comments