2014-01-05 09:12:05 +01:00
|
|
|
// Package servo allows control of servos using a PWM controller.
|
|
|
|
package servo
|
|
|
|
|
|
|
|
import (
|
2014-03-31 15:16:04 +02:00
|
|
|
"github.com/golang/glog"
|
2014-02-10 00:35:41 +01:00
|
|
|
"github.com/kidoman/embd/util"
|
2014-01-05 09:12:05 +01:00
|
|
|
)
|
|
|
|
|
2014-01-08 22:11:50 +01:00
|
|
|
const (
|
|
|
|
minus = 544
|
|
|
|
maxus = 2400
|
|
|
|
)
|
|
|
|
|
2014-04-02 13:55:28 +02:00
|
|
|
const (
|
|
|
|
// DefaultFreq represents the default (preferred) freq of a PWM doing servo duties.
|
|
|
|
DefaultFreq = 50
|
|
|
|
)
|
|
|
|
|
2014-01-05 09:12:05 +01:00
|
|
|
// A PWM interface implements access to a pwm controller.
|
|
|
|
type PWM interface {
|
2014-04-02 13:55:28 +02:00
|
|
|
SetMicroseconds(us int) error
|
2014-01-05 09:12:05 +01:00
|
|
|
}
|
|
|
|
|
2014-01-05 11:19:03 +01:00
|
|
|
type Servo struct {
|
2014-04-02 13:55:28 +02:00
|
|
|
PWM PWM
|
2014-01-05 09:12:05 +01:00
|
|
|
|
2014-01-08 22:05:18 +01:00
|
|
|
Minus, Maxus int
|
2014-01-05 09:12:05 +01:00
|
|
|
}
|
|
|
|
|
2014-01-05 11:19:03 +01:00
|
|
|
// New creates a new Servo interface.
|
2014-04-02 13:55:28 +02:00
|
|
|
func New(pwm PWM) *Servo {
|
2014-01-05 11:19:03 +01:00
|
|
|
return &Servo{
|
2014-04-02 13:55:28 +02:00
|
|
|
PWM: pwm,
|
|
|
|
Minus: minus,
|
|
|
|
Maxus: maxus,
|
2014-01-05 09:12:05 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetAngle sets the servo angle.
|
2014-01-05 11:19:03 +01:00
|
|
|
func (s *Servo) SetAngle(angle int) error {
|
2014-01-08 22:05:18 +01:00
|
|
|
us := util.Map(int64(angle), 0, 180, int64(s.Minus), int64(s.Maxus))
|
2014-01-05 09:12:05 +01:00
|
|
|
|
2014-03-31 15:16:04 +02:00
|
|
|
glog.V(1).Infof("servo: given angle %v calculated %v us", angle, us)
|
2014-01-05 09:12:05 +01:00
|
|
|
|
2014-04-02 13:55:28 +02:00
|
|
|
return s.PWM.SetMicroseconds(int(us))
|
2014-01-05 09:12:05 +01:00
|
|
|
}
|