forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
servo_driver.go
88 lines (73 loc) · 2.26 KB
/
servo_driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package gpio
import "gobot.io/x/gobot/v2"
// ServoDriver Represents a Servo
type ServoDriver struct {
name string
pin string
connection ServoWriter
gobot.Commander
CurrentAngle byte
}
// NewServoDriver returns a new ServoDriver given a ServoWriter and pin.
//
// Adds the following API Commands:
//
// "Move" - See ServoDriver.Move
// "Min" - See ServoDriver.Min
// "Center" - See ServoDriver.Center
// "Max" - See ServoDriver.Max
func NewServoDriver(a ServoWriter, pin string) *ServoDriver {
s := &ServoDriver{
name: gobot.DefaultName("Servo"),
connection: a,
pin: pin,
Commander: gobot.NewCommander(),
CurrentAngle: 0,
}
s.AddCommand("Move", func(params map[string]interface{}) interface{} {
angle := byte(params["angle"].(float64))
return s.Move(angle)
})
s.AddCommand("Min", func(params map[string]interface{}) interface{} {
return s.Min()
})
s.AddCommand("Center", func(params map[string]interface{}) interface{} {
return s.Center()
})
s.AddCommand("Max", func(params map[string]interface{}) interface{} {
return s.Max()
})
return s
}
// Name returns the ServoDrivers name
func (s *ServoDriver) Name() string { return s.name }
// SetName sets the ServoDrivers name
func (s *ServoDriver) SetName(n string) { s.name = n }
// Pin returns the ServoDrivers pin
func (s *ServoDriver) Pin() string { return s.pin }
// Connection returns the ServoDrivers connection
func (s *ServoDriver) Connection() gobot.Connection { return s.connection.(gobot.Connection) }
// Start implements the Driver interface
func (s *ServoDriver) Start() (err error) { return }
// Halt implements the Driver interface
func (s *ServoDriver) Halt() (err error) { return }
// Move sets the servo to the specified angle. Acceptable angles are 0-180
func (s *ServoDriver) Move(angle uint8) (err error) {
if angle > 180 {
return ErrServoOutOfRange
}
s.CurrentAngle = angle
return s.connection.ServoWrite(s.Pin(), angle)
}
// Min sets the servo to it's minimum position
func (s *ServoDriver) Min() (err error) {
return s.Move(0)
}
// Center sets the servo to it's center position
func (s *ServoDriver) Center() (err error) {
return s.Move(90)
}
// Max sets the servo to its maximum position
func (s *ServoDriver) Max() (err error) {
return s.Move(180)
}