from machine import Pin, PWM
import utime
# Define pin constants
STEP_PIN = 9
DIR_PIN = 4
TRIG_PIN = 27
ECHO_PIN = 26
LED_PIN = 5
# Initialize pins
step = Pin(STEP_PIN, Pin.OUT)
dir = Pin(DIR_PIN, Pin.OUT)
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
led = Pin(LED_PIN)
# Define constants
FULL_ROTATION_STEPS = 200 # Change this to the number of steps required for a full rotation
DISTANCE_THRESHOLD = 200 # Distance threshold in mm
# Function to trigger the ultrasonic sensor
def trigger_ultrasonic():
trig.high()
utime.sleep_us(10)
trig.low()
# Function to measure distance from ultrasonic sensor
def measure_distance():
trigger_ultrasonic()
pulse_time = pulse_in(echo, 1)
distance = (pulse_time * 34300) / 2 / 1000000 # Convert pulse time to distance in mm
return distance
# Function to perform pulse in measurement
def pulse_in(pin, value, timeout_ms=500):
start = utime.ticks_us()
while pin.value() != value:
if utime.ticks_diff(utime.ticks_us(), start) > timeout_ms * 1000:
return 0
start = utime.ticks_us()
while pin.value() == value:
if utime.ticks_diff(utime.ticks_us(), start) > timeout_ms * 1000:
return 0
return utime.ticks_diff(utime.ticks_us(), start)
# Function to rotate stepper motor
def rotate_stepper(steps, direction):
dir.value(direction)
for _ in range(steps):
step.high()
utime.sleep_us(500) # Adjust this delay as needed for your stepper motor
step.low()
utime.sleep_ms(10) # Adjust this delay as needed for your stepper motor
# Main loop
while True:
distance = measure_distance()
if distance > DISTANCE_THRESHOLD:
led.on() # Turn on the LED
else:
led.off() # Turn off the LED
rotate_stepper(FULL_ROTATION_STEPS, 1) # Rotate clockwise