forked from shanghuiyang/rpi-devices
/
sg90.go
63 lines (57 loc) · 1.12 KB
/
sg90.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
/*
Package dev ...
SG90 is the driver of servo motor
Connect to Pi:
- the red line: any 5v pin
- the brown line: any gnd pin
- the yellow line: any pwn pin(must be one of gpio 12, 13, 18, 19)
*/
package dev
import (
"time"
"github.com/shanghuiyang/rpi-devices/base"
"github.com/stianeikeland/go-rpio"
)
// SG90 ...
type SG90 struct {
pin rpio.Pin
rpi base.RpiModel
}
// NewSG90 ...
func NewSG90(pin uint8) *SG90 {
s := &SG90{
pin: rpio.Pin(pin),
rpi: base.GetRpiModel(),
}
s.pin.Pwm()
s.pin.Freq(50)
s.pin.DutyCycle(0, 100)
return s
}
// Roll ...
// angle: [-90, 90]
// angle < 0: left
// angel = 0: ahead
// angle > 0: right
// e.g.
//
// -30 0 30
// \ | /
// \ | /
// \|/
// *
// eye
//
func (s *SG90) Roll(angle int) {
if angle < -90 || angle > 90 {
return
}
duty := uint32(10.0 - float32(angle)/15.0)
if s.rpi == base.Rpi4 {
// Rpi4 uses a BCM 2711, which is different from the early rpi like rpi3, rpi2, rpiA and rpi0
duty = uint32(26.5 - 39*float32(angle)/180)
}
s.pin.DutyCycle(uint32(duty), 100)
time.Sleep(100 * time.Millisecond)
s.pin.DutyCycle(0, 100)
}