2014-01-08 22:05:18 +01:00
|
|
|
// Package servoblaster allows interfacing with the software servoblaster driver.
|
|
|
|
//
|
|
|
|
// More details on ServoBlaster at: https://github.com/richardghirst/PiBits/tree/master/ServoBlaster
|
|
|
|
package servoblaster
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2014-03-31 15:16:04 +02:00
|
|
|
|
|
|
|
"github.com/golang/glog"
|
2014-01-08 22:05:18 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// ServoBlaster represents a software RPi PWM/PCM based servo control module.
|
|
|
|
type ServoBlaster struct {
|
|
|
|
initialized bool
|
|
|
|
fd *os.File
|
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a new ServoBlaster instance.
|
|
|
|
func New() *ServoBlaster {
|
|
|
|
return &ServoBlaster{}
|
|
|
|
}
|
|
|
|
|
2014-03-31 15:16:04 +02:00
|
|
|
func (d *ServoBlaster) setup() error {
|
2014-01-08 22:05:18 +01:00
|
|
|
if d.initialized {
|
2014-03-31 15:16:04 +02:00
|
|
|
return nil
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|
2014-03-31 15:16:04 +02:00
|
|
|
var err error
|
2014-01-08 22:05:18 +01:00
|
|
|
if d.fd, err = os.OpenFile("/dev/servoblaster", os.O_WRONLY, os.ModeExclusive); err != nil {
|
2014-03-31 15:16:04 +02:00
|
|
|
return err
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|
|
|
|
d.initialized = true
|
2014-03-31 15:16:04 +02:00
|
|
|
return nil
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|
|
|
|
|
2014-04-02 13:55:28 +02:00
|
|
|
type pwmChannel struct {
|
|
|
|
d *ServoBlaster
|
|
|
|
|
|
|
|
channel int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *pwmChannel) SetMicroseconds(us int) error {
|
|
|
|
return p.d.setMicroseconds(p.channel, us)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *ServoBlaster) Channel(channel int) *pwmChannel {
|
|
|
|
return &pwmChannel{d: d, channel: channel}
|
|
|
|
}
|
|
|
|
|
2014-01-08 22:05:18 +01:00
|
|
|
// SetMicroseconds sends a command to the PWM driver to generate a us wide pulse.
|
2014-04-02 13:55:28 +02:00
|
|
|
func (d *ServoBlaster) setMicroseconds(channel, us int) error {
|
2014-03-31 15:16:04 +02:00
|
|
|
if err := d.setup(); err != nil {
|
|
|
|
return err
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|
|
|
|
cmd := fmt.Sprintf("%v=%vus\n", channel, us)
|
2014-03-31 15:16:04 +02:00
|
|
|
glog.V(1).Infof("servoblaster: sending command %q", cmd)
|
|
|
|
_, err := d.fd.WriteString(cmd)
|
|
|
|
return err
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the open driver handle.
|
2014-03-31 15:16:04 +02:00
|
|
|
func (d *ServoBlaster) Close() error {
|
2014-01-08 22:05:18 +01:00
|
|
|
if d.fd != nil {
|
2014-03-31 15:16:04 +02:00
|
|
|
return d.fd.Close()
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|
2014-03-31 15:16:04 +02:00
|
|
|
return nil
|
2014-01-08 22:05:18 +01:00
|
|
|
}
|