hybridgroup.gobot/platforms/beaglebone/pwm_pin.go

82 lines
1.6 KiB
Go
Raw Normal View History

2014-04-28 19:39:51 +08:00
package beaglebone
import (
"fmt"
2014-11-10 06:35:36 +08:00
"github.com/hybridgroup/gobot/sysfs"
"os"
"strings"
)
type pwmPin struct {
pinNum string
pwmDevice string
}
2014-10-16 23:59:23 +08:00
// newPwmPin creates a new pwm pin with specified pin number
2014-11-10 06:35:36 +08:00
func newPwmPin(pinNum string, ocp string) *pwmPin {
var fi sysfs.File
2014-07-01 10:50:28 +08:00
d := &pwmPin{
pinNum: strings.ToUpper(pinNum),
}
2014-11-10 06:35:36 +08:00
pwmDevice, err := glob(fmt.Sprintf("%v/pwm_test_%v.*", ocp, d.pinNum))
if err != nil {
panic(err)
}
2014-07-01 10:50:28 +08:00
d.pwmDevice = pwmDevice[0]
for i := 0; i < 10; i++ {
2014-11-10 06:35:36 +08:00
fi, err = sysfs.OpenFile(fmt.Sprintf("%v/run", d.pwmDevice), os.O_RDWR|os.O_APPEND, 0666)
defer fi.Close()
if err != nil && i == 9 {
panic(err)
2014-07-01 10:50:28 +08:00
} else {
break
}
}
2014-07-01 10:50:28 +08:00
fi.WriteString("1")
2014-07-01 10:50:28 +08:00
fi.Sync()
2014-07-01 10:50:28 +08:00
for {
2014-11-10 06:35:36 +08:00
if _, err := sysfs.OpenFile(fmt.Sprintf("%v/period", d.pwmDevice), os.O_RDONLY, 0644); err == nil {
2014-07-01 10:50:28 +08:00
break
}
}
for {
2014-11-10 06:35:36 +08:00
if _, err := sysfs.OpenFile(fmt.Sprintf("%v/duty", d.pwmDevice), os.O_RDONLY, 0644); err == nil {
2014-07-01 10:50:28 +08:00
break
}
}
return d
}
2014-10-16 23:59:23 +08:00
// pwmWrite writes to a pwm pin with specified period and duty
2014-06-11 06:16:11 +08:00
func (p *pwmPin) pwmWrite(period string, duty string) {
2014-11-10 06:35:36 +08:00
f1, err := sysfs.OpenFile(fmt.Sprintf("%v/period", p.pwmDevice), os.O_WRONLY|os.O_APPEND, 0666)
defer f1.Close()
if err != nil {
panic(err)
}
2014-11-10 06:35:36 +08:00
f1.WriteString(period)
2014-11-10 06:35:36 +08:00
f2, err := sysfs.OpenFile(fmt.Sprintf("%v/duty", p.pwmDevice), os.O_WRONLY|os.O_APPEND, 0666)
defer f2.Close()
if err != nil {
panic(err)
}
2014-11-10 06:35:36 +08:00
f2.WriteString(duty)
}
2014-10-16 23:59:23 +08:00
// releae writes string to close a pwm pin
2014-06-11 06:16:11 +08:00
func (p *pwmPin) release() {
2014-11-10 06:35:36 +08:00
fi, err := sysfs.OpenFile(fmt.Sprintf("%v/run", p.pwmDevice), os.O_WRONLY|os.O_APPEND, 0666)
defer fi.Close()
if err != nil {
panic(err)
}
fi.WriteString("0")
}