|
| 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 | + |
| 13 | +# Function to move the motor a specific number of steps |
| 14 | +def step_motor(STEP_PIN, DIR_PIN, steps=STEPS_PER_REV, direction=1, delay=0.005): |
| 15 | + """Move the motor a specified number of steps in the given direction.""" |
| 16 | + DIR_PIN.value(direction) # Set direction (1 = forward, 0 = backward) |
| 17 | + for _ in range(steps): |
| 18 | + STEP_PIN.value(1) |
| 19 | + time.sleep(delay) |
| 20 | + STEP_PIN.value(0) |
| 21 | + time.sleep(delay) |
| 22 | + |
| 23 | + |
| 24 | +# Function to calculate current speed in steps per second and RPM |
| 25 | +def calculate_speed(current_delay): |
| 26 | + """Calculate the current speed in steps per second and RPM.""" |
| 27 | + if current_delay <= 0: |
| 28 | + return 0, 0 |
| 29 | + steps_per_second = 1 / (2 * current_delay) # Delay is for each half-step |
| 30 | + rpm = (steps_per_second / STEPS_PER_REV) * 60 # Convert to RPM |
| 31 | + return steps_per_second, rpm |
| 32 | + |
| 33 | + |
| 34 | +# Function to increase motor speed by reducing delay |
| 35 | +def inc_speed(current_delay): |
| 36 | + """Decrease delay to increase speed, respecting minimum delay limit.""" |
| 37 | + new_delay = max(current_delay - 0.001, MIN_DELAY) |
| 38 | + return new_delay |
| 39 | + |
| 40 | + |
| 41 | +# Function to decrease motor speed by increasing delay |
| 42 | +def dec_speed(current_delay): |
| 43 | + """Increase delay to decrease speed.""" |
| 44 | + new_delay = current_delay + 0.001 |
| 45 | + return new_delay |
| 46 | + |
| 47 | + |
| 48 | +# Function to move motor forward |
| 49 | +def forward_motion(STEP_PIN, DIR_PIN, steps=STEPS_PER_REV, delay=0.005): |
| 50 | + """Move motor forward for a given number of steps and delay.""" |
| 51 | + step_motor(STEP_PIN, DIR_PIN, steps, direction=1, delay=delay) |
| 52 | + |
| 53 | + |
| 54 | +# Function to move motor backward |
| 55 | +def backward_motion(STEP_PIN, DIR_PIN, steps=STEPS_PER_REV, delay=0.005): |
| 56 | + """Move motor backward for a given number of steps and delay.""" |
| 57 | + step_motor(STEP_PIN, DIR_PIN, steps, direction=0, delay=delay) |
0 commit comments