| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import pigpio
- import time
- # Pin numbers (BCM)
- DIR_PIN = 11
- STEP_PIN = 9
- EN_PIN = 10
- # Connect to pigpio daemon
- pi = pigpio.pi()
- if not pi.connected:
- exit()
- # Set up pins
- pi.set_mode(DIR_PIN, pigpio.OUTPUT)
- pi.set_mode(STEP_PIN, pigpio.OUTPUT)
- pi.set_mode(EN_PIN, pigpio.OUTPUT)
- def move_motor(steps, direction=True, step_delay_us=10):
- """
- Moves the motor a specific number of steps.
- :param steps: Number of step pulses.
- :param direction: True for one way, False for the other.
- :param step_delay_us: Microseconds between rising edges (controls speed).
- """
- # Enable motor driver (LOW = enabled)
- pi.write(EN_PIN, 0)
- # Set direction
- pi.write(DIR_PIN, 0 if direction else 1)
- # Create pulse waveform
- pulses = []
- for _ in range(steps):
- pulses.append(pigpio.pulse(1 << STEP_PIN, 0, step_delay_us)) # STEP high
- pulses.append(pigpio.pulse(0, 1 << STEP_PIN, step_delay_us)) # STEP low
- pi.wave_clear()
- pi.wave_add_generic(pulses)
- wave_id = pi.wave_create()
- if wave_id >= 0:
- pi.wave_send_once(wave_id)
- while pi.wave_tx_busy():
- time.sleep(0.01)
- pi.wave_delete(wave_id)
- # Optional: disable motor
- pi.write(EN_PIN, 1)
- # Example: Move 200 steps forward with 1ms step pulse (i.e., ~500 steps/sec)
- move_motor(1600, direction=True, step_delay_us=200)
- # Clean up
- pi.stop()
|