A PX4 based camera pointer

rpipwm.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2017 Google Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. package pipoint
  16. import (
  17. "fmt"
  18. "os"
  19. "gobot.io/x/gobot/sysfs"
  20. )
  21. // PwmPin represents a single pin on sysfs.
  22. type PwmPin struct {
  23. Chip int
  24. Pin int
  25. }
  26. func writeFile(path string, value int) (wrote int, err error) {
  27. file, err := sysfs.OpenFile(path, os.O_WRONLY, 0644)
  28. defer file.Close()
  29. if err != nil {
  30. return
  31. }
  32. return file.Write([]byte(fmt.Sprintf("%d\n", value)))
  33. }
  34. func (p *PwmPin) chip() string {
  35. return fmt.Sprintf("/sys/class/pwm/pwmchip%d", p.Chip)
  36. }
  37. func (p *PwmPin) attr(attr string) string {
  38. return fmt.Sprintf("/sys/class/pwm/pwmchip%d/pwm%d/%s", p.Chip, p.Pin, attr)
  39. }
  40. // SetEnable enables or disables the PWM output.
  41. func (p *PwmPin) SetEnable(val int) (err error) {
  42. _, err = writeFile(p.attr("enable"), val)
  43. return
  44. }
  45. // SetPeriod sets the PWM period in ns.
  46. func (p *PwmPin) SetPeriod(period int) (err error) {
  47. _, err = writeFile(p.attr("period"), period)
  48. return
  49. }
  50. // SetDuty sets the on time in ns. Should be less than the period.
  51. func (p *PwmPin) SetDuty(duty int) (err error) {
  52. _, err = writeFile(p.attr("duty_cycle"), duty)
  53. return
  54. }
  55. // Export exports this pin.
  56. func (p *PwmPin) Export() (err error) {
  57. path := p.chip() + "/export"
  58. _, err = writeFile(path, p.Pin)
  59. return
  60. }
  61. // UnExport removes the export for this pin.
  62. func (p *PwmPin) UnExport() (err error) {
  63. path := p.chip() + "/unexport"
  64. _, err = writeFile(path, p.Pin)
  65. return
  66. }