No Description
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.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # https://how2electronics.com/how-to-control-servo-motor-with-raspberry-pi-pico/
  2. from machine import Pin, PWM
  3. class Servo:
  4. """ A simple class for controlling a 9g servo with the Raspberry Pi Pico.
  5. Attributes:
  6. minVal: An integer denoting the minimum duty value for the servo motor.
  7. maxVal: An integer denoting the maximum duty value for the servo motor.
  8. """
  9. def __init__(self, pin: int or Pin or PWM, minVal=2500, maxVal=7500):
  10. """ Creates a new Servo Object.
  11. args:
  12. pin (int or machine.Pin or machine.PWM): Either an integer denoting the number of the GPIO pin or an already constructed Pin or PWM object that is connected to the servo.
  13. minVal (int): Optional, denotes the minimum duty value to be used for this servo.
  14. maxVal (int): Optional, denotes the maximum duty value to be used for this servo.
  15. """
  16. if isinstance(pin, int):
  17. pin = Pin(pin, Pin.OUT)
  18. if isinstance(pin, Pin):
  19. self.__pwm = PWM(pin)
  20. if isinstance(pin, PWM):
  21. self.__pwm = pin
  22. self.__pwm.freq(50)
  23. self.minVal = minVal
  24. self.maxVal = maxVal
  25. def deinit(self):
  26. """ Deinitializes the underlying PWM object.
  27. """
  28. self.__pwm.deinit()
  29. def goto(self, value: int):
  30. """ Moves the servo to the specified position.
  31. args:
  32. value (int): The position to move to, represented by a value from 0 to 1024 (inclusive).
  33. """
  34. if value < 0:
  35. value = 0
  36. if value > 1024:
  37. value = 1024
  38. delta = self.maxVal-self.minVal
  39. target = int(self.minVal + ((value / 1024) * delta))
  40. self.__pwm.duty_u16(target)
  41. def middle(self):
  42. """ Moves the servo to the middle.
  43. """
  44. self.goto(512)
  45. def free(self):
  46. """ Allows the servo to be moved freely.
  47. """
  48. self.__pwm.duty_u16(0)