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.

toy.py 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # https://how2electronics.com/how-to-control-servo-motor-with-raspberry-pi-pico/
  2. import time
  3. from machine import Pin, PWM
  4. from servo import Servo
  5. class Toy:
  6. """ Tools to control the Cat Toy hardware.
  7. Attributes:
  8. servo1: GPIO pin number of the pan servo.
  9. servo2: GPIO pin number of the tilt servo.
  10. laser: GPIO pin number of the laser diode.
  11. """
  12. # first servo
  13. pan_min = 20
  14. pan_max = 160
  15. # sevond servo
  16. tilt_min = 0
  17. tilt_max = 90
  18. def __init__(self, servo1 = 28, servo2 = 27, laser = 2):
  19. self.laserPin = PWM(Pin(laser, Pin.OUT))
  20. self.laserPin.freq(1000)
  21. self.laser(0)
  22. self.pan = Servo(servo1)
  23. self.tilt = Servo(servo2)
  24. self.angle(self.pan, round((self.pan_max - self.pan_min) / 2) + self.pan_min)
  25. self.angle(self.tilt, round((self.tilt_max - self.tilt_min) / 2) + self.tilt_min)
  26. time.sleep(0.1)
  27. self.pan.free()
  28. self.tilt.free()
  29. def map_value(self, x, in_min, in_max, out_min, out_max):
  30. return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
  31. def angle(self, servo, angle):
  32. if angle < 0:
  33. angle = 0
  34. if angle > 180:
  35. angle = 180
  36. servo.goto(round(self.map_value(angle, 0, 180, 0, 1024)))
  37. def laser(self, value):
  38. v = 1.0 - value
  39. self.laserPin.duty_u16(round(v * 65535))
  40. def test(self, steps = 10):
  41. self.laser(1)
  42. for y in range(self.tilt_min, self.tilt_max, round((self.tilt_max - self.tilt_min) / steps)):
  43. self.angle(self.tilt, y)
  44. time.sleep(0.2)
  45. for x in range(self.pan_min, self.pan_max, round((self.pan_max - self.pan_min) / steps)):
  46. self.angle(self.pan, x)
  47. time.sleep(0.2)
  48. self.tilt.free()
  49. self.pan.free()
  50. self.laser(0)