mirror of
https://github.com/tinygo-org/drivers.git
synced 2026-07-26 10:38:41 +00:00
servo: add function SetAngle() to simplify API for most common use case
Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
+19
-13
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+23
-1
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user