|
| 1 | +import time |
| 2 | + |
| 3 | +# Constants |
| 4 | +STEPS_PER_REV = 200 # Number of steps per motor revolution |
| 5 | +MIN_DELAY = 0.001 # Minimum delay between steps (controls maximum speed) |
| 6 | + |
| 7 | +# Function to enable or disable the motor driver (active low) |
| 8 | +def enable_motor(EN_PIN, enabled=True): |
| 9 | +"""Enable or disable the motor driver.""" |
| 10 | +EN_PIN.value(0 if enabled else 1) |
| 11 | + |
| 12 | +# Function to move the motor a specific number of steps |
| 13 | +def step_motor(STEP_PIN, DIR_PIN, steps=STEPS_PER_REV, direction=1, delay=0.005): |
| 14 | +"""Move the motor a specified number of steps in the given direction.""" |
| 15 | +DIR_PIN.value(direction) # Set direction (1 = forward, 0 = backward) |
| 16 | +for _ in range(steps): |
| 17 | +STEP_PIN.value(1) |
| 18 | +time.sleep(delay) |
| 19 | +STEP_PIN.value(0) |
| 20 | +time.sleep(delay) |
| 21 | + |
| 22 | +# Function to calculate current speed in steps per second and RPM |
| 23 | +def calculate_speed(current_delay): |
| 24 | +"""Calculate the current speed in steps per second and RPM.""" |
| 25 | +if current_delay <= 0: |
| 26 | +return 0, 0 |
| 27 | +steps_per_second = 1 / (2 * current_delay) # Delay is for each half-step |
| 28 | +rpm = (steps_per_second / STEPS_PER_REV) * 60 # Convert to RPM |
| 29 | +return steps_per_second, rpm |
| 30 | + |
| 31 | +# Function to increase motor speed by reducing delay |
| 32 | +def inc_speed(current_delay): |
| 33 | +"""Decrease delay to increase speed, respecting minimum delay limit.""" |
| 34 | +new_delay = max(current_delay - 0.001, MIN_DELAY) |
| 35 | +return new_delay |
| 36 | + |
| 37 | +# Function to decrease motor speed by increasing delay |
| 38 | +def dec_speed(current_delay): |
| 39 | +"""Increase delay to decrease speed.""" |
| 40 | +new_delay = current_delay + 0.001 |
| 41 | +return new_delay |
| 42 | + |
| 43 | +# Function to move motor forward |
| 44 | +def forward_motion(STEP_PIN, DIR_PIN, steps=STEPS_PER_REV, delay=0.005): |
| 45 | +"""Move motor forward for a given number of steps and delay.""" |
| 46 | +step_motor(STEP_PIN, DIR_PIN, steps, direction=1, delay=delay) |
| 47 | + |
| 48 | +# Function to move motor backward |
| 49 | +def backward_motion(STEP_PIN, DIR_PIN, steps=STEPS_PER_REV, delay=0.005): |
| 50 | +"""Move motor backward for a given number of steps and delay.""" |
| 51 | +step_motor(STEP_PIN, DIR_PIN, steps, direction=0, delay=delay) |
0 commit comments