motor_playground.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import pigpio
  2. import time
  3. # Pin numbers (BCM)
  4. DIR_PIN = 11
  5. STEP_PIN = 9
  6. EN_PIN = 10
  7. # Connect to pigpio daemon
  8. pi = pigpio.pi()
  9. if not pi.connected:
  10. exit()
  11. # Set up pins
  12. pi.set_mode(DIR_PIN, pigpio.OUTPUT)
  13. pi.set_mode(STEP_PIN, pigpio.OUTPUT)
  14. pi.set_mode(EN_PIN, pigpio.OUTPUT)
  15. def move_motor(steps, direction=True, step_delay_us=10):
  16. """
  17. Moves the motor a specific number of steps.
  18. :param steps: Number of step pulses.
  19. :param direction: True for one way, False for the other.
  20. :param step_delay_us: Microseconds between rising edges (controls speed).
  21. """
  22. # Enable motor driver (LOW = enabled)
  23. pi.write(EN_PIN, 0)
  24. # Set direction
  25. pi.write(DIR_PIN, 0 if direction else 1)
  26. # Create pulse waveform
  27. pulses = []
  28. for _ in range(steps):
  29. pulses.append(pigpio.pulse(1 << STEP_PIN, 0, step_delay_us)) # STEP high
  30. pulses.append(pigpio.pulse(0, 1 << STEP_PIN, step_delay_us)) # STEP low
  31. pi.wave_clear()
  32. pi.wave_add_generic(pulses)
  33. wave_id = pi.wave_create()
  34. if wave_id >= 0:
  35. pi.wave_send_once(wave_id)
  36. while pi.wave_tx_busy():
  37. time.sleep(0.01)
  38. pi.wave_delete(wave_id)
  39. # Optional: disable motor
  40. pi.write(EN_PIN, 1)
  41. # Example: Move 200 steps forward with 1ms step pulse (i.e., ~500 steps/sec)
  42. move_motor(1600, direction=True, step_delay_us=200)
  43. # Clean up
  44. pi.stop()