embd/motion/servo/servo.go

44 lines
817 B
Go
Raw Normal View History

// Package servo allows control of servos using a PWM controller.
package servo
import (
"log"
2014-01-05 11:19:03 +01:00
"github.com/kid0m4n/go-rpi/util"
)
// A PWM interface implements access to a pwm controller.
type PWM interface {
SetMicroseconds(channel int, us int) error
}
2014-01-05 11:19:03 +01:00
type Servo struct {
PWM PWM
Channel int
Minus, Maxus int
2014-01-05 11:19:03 +01:00
Debug bool
}
2014-01-05 11:19:03 +01:00
// New creates a new Servo interface.
func New(pwm PWM, channel int, minus, maxus int) *Servo {
2014-01-05 11:19:03 +01:00
return &Servo{
PWM: pwm,
Channel: channel,
Minus: minus,
Maxus: maxus,
}
}
// SetAngle sets the servo angle.
2014-01-05 11:19:03 +01:00
func (s *Servo) SetAngle(angle int) error {
us := util.Map(int64(angle), 0, 180, int64(s.Minus), int64(s.Maxus))
2014-01-05 11:19:03 +01:00
if s.Debug {
log.Printf("servo: given angle %v calculated %v us", angle, us)
}
return s.PWM.SetMicroseconds(s.Channel, int(us))
}