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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. # maximum movements on cardboard box
  13. # pan_min, pan_max, tilt_min, tilt_max
  14. maximum_limits = (20, 160, 0, 90)
  15. def __init__(self, servo1 = 28, servo2 = 27, laser = 2):
  16. self.laserPin = PWM(Pin(laser, Pin.OUT))
  17. self.laserPin.freq(1000)
  18. self.laser(0)
  19. self.pan = Servo(servo1)
  20. self.tilt = Servo(servo2)
  21. pan_min, pan_max, tilt_min, tilt_max = self.maximum_limits
  22. self.angle(self.pan, int((pan_max - pan_min) / 2) + pan_min)
  23. self.angle(self.tilt, int((tilt_max - tilt_min) / 2) + tilt_min)
  24. time.sleep(0.1)
  25. self.pan.free()
  26. self.tilt.free()
  27. def map_value(self, x, in_min, in_max, out_min, out_max):
  28. return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
  29. def angle(self, servo, angle):
  30. if angle < 0:
  31. angle = 0
  32. if angle > 180:
  33. angle = 180
  34. servo.goto(int(self.map_value(angle, 0, 180, 0, 1024)))
  35. def laser(self, value):
  36. v = 1.0 - value
  37. self.laserPin.duty_u16(int(v * 65535))
  38. def test(self, steps = 10):
  39. pan_min, pan_max, tilt_min, tilt_max = self.maximum_limits
  40. self.laser(1)
  41. for y in range(tilt_min, tilt_max, int((tilt_max - tilt_min) / steps)):
  42. self.angle(self.tilt, y)
  43. for x in range(pan_min, pan_max, int((pan_max - pan_min) / steps)):
  44. self.angle(self.pan, x)
  45. time.sleep(0.2)
  46. self.tilt.free()
  47. self.pan.free()
  48. self.laser(0)