You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

servo.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package adafruitPCA9685 // import "go.rls.moe/misc/adafruitPCA9685"
  2. import (
  3. "errors"
  4. "sync"
  5. )
  6. var (
  7. errLowAngle = errors.New("Exceeded Lower Operating Range of Angle")
  8. errHiAngle = errors.New("Exceeded Higher Operating Range of Angle")
  9. )
  10. type Servo struct {
  11. lock sync.Mutex
  12. controller *PCA9685
  13. settings ServoSettings
  14. currentAngle int16
  15. channel byte
  16. }
  17. type ServoSettings struct {
  18. OffsetAngle int16
  19. StartAngle, MinAngle, MaxAngle, MiddleAngle int16
  20. }
  21. func NewServo(controller *PCA9685, channel byte, sc ServoSettings) (*Servo, error) {
  22. if controller == nil {
  23. return nil, errors.New("Controller was nil")
  24. }
  25. ns := &Servo{
  26. controller: controller,
  27. settings: sc,
  28. channel: channel,
  29. currentAngle: sc.StartAngle,
  30. }
  31. if err := ns.controller.SetPWM(ns.channel, 0, ns.currentAngle); err != nil {
  32. return nil, err
  33. }
  34. return ns, nil
  35. }
  36. func (s *Servo) TurnTo(angle int16) error {
  37. s.lock.Lock()
  38. defer s.lock.Unlock()
  39. angle -= s.settings.OffsetAngle
  40. if angle < s.settings.MinAngle {
  41. return errLowAngle
  42. }
  43. if angle > s.settings.MaxAngle {
  44. return errHiAngle
  45. }
  46. err := s.controller.SetPWM(s.channel, 0, angle)
  47. if err != nil {
  48. return err
  49. }
  50. s.currentAngle = angle
  51. return nil
  52. }
  53. func (s *Servo) DisableSignal() error {
  54. s.lock.Lock()
  55. defer s.lock.Unlock()
  56. return s.controller.SetPWM(s.channel, 0, 0)
  57. }
  58. func (s *Servo) CurrentAngle() int16 {
  59. s.lock.Lock()
  60. defer s.lock.Unlock()
  61. return s.currentAngle
  62. }
  63. func (s *Servo) GetSettings() ServoSettings { return s.settings }
  64. func (s *Servo) SetSettings(sc ServoSettings) { s.settings = sc }
  65. func (s *Servo) Offset() int16 { return s.settings.OffsetAngle }
  66. func (s *Servo) Controller() *PCA9685 { return s.controller }
  67. func (s *Servo) Channel() byte { return s.channel }
  68. func (s *Servo) Center() error { return s.TurnTo(s.settings.MiddleAngle) }