2014-01-05 13:42:05 +05:30
|
|
|
// Package servo allows control of servos using a PWM controller.
|
|
|
|
package servo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2014-01-05 15:49:03 +05:30
|
|
|
|
2014-02-10 05:05:41 +05:30
|
|
|
"github.com/kidoman/embd/util"
|
2014-01-05 13:42:05 +05:30
|
|
|
)
|
|
|
|
|
2014-01-09 02:41:50 +05:30
|
|
|
const (
|
|
|
|
minus = 544
|
|
|
|
maxus = 2400
|
|
|
|
)
|
|
|
|
|
2014-01-05 13:42:05 +05:30
|
|
|
// A PWM interface implements access to a pwm controller.
|
|
|
|
type PWM interface {
|
2014-01-09 02:35:18 +05:30
|
|
|
SetMicroseconds(channel int, us int) error
|
2014-01-05 13:42:05 +05:30
|
|
|
}
|
|
|
|
|
2014-01-05 15:49:03 +05:30
|
|
|
type Servo struct {
|
|
|
|
PWM PWM
|
|
|
|
Channel int
|
2014-01-05 13:42:05 +05:30
|
|
|
|
2014-01-09 02:35:18 +05:30
|
|
|
Minus, Maxus int
|
2014-01-05 13:42:05 +05:30
|
|
|
|
2014-01-05 15:49:03 +05:30
|
|
|
Debug bool
|
2014-01-05 13:42:05 +05:30
|
|
|
}
|
|
|
|
|
2014-01-05 15:49:03 +05:30
|
|
|
// New creates a new Servo interface.
|
2014-01-09 02:41:50 +05:30
|
|
|
func New(pwm PWM, channel int) *Servo {
|
2014-01-05 15:49:03 +05:30
|
|
|
return &Servo{
|
|
|
|
PWM: pwm,
|
|
|
|
Channel: channel,
|
2014-01-09 02:35:18 +05:30
|
|
|
Minus: minus,
|
|
|
|
Maxus: maxus,
|
2014-01-05 13:42:05 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetAngle sets the servo angle.
|
2014-01-05 15:49:03 +05:30
|
|
|
func (s *Servo) SetAngle(angle int) error {
|
2014-01-09 02:35:18 +05:30
|
|
|
us := util.Map(int64(angle), 0, 180, int64(s.Minus), int64(s.Maxus))
|
2014-01-05 13:42:05 +05:30
|
|
|
|
2014-01-05 15:49:03 +05:30
|
|
|
if s.Debug {
|
2014-01-09 02:35:18 +05:30
|
|
|
log.Printf("servo: given angle %v calculated %v us", angle, us)
|
2014-01-05 13:42:05 +05:30
|
|
|
}
|
|
|
|
|
2014-01-09 02:35:18 +05:30
|
|
|
return s.PWM.SetMicroseconds(s.Channel, int(us))
|
2014-01-05 13:42:05 +05:30
|
|
|
}
|