Take a look at this code for a line following robot that I'm coding that is supposed to…
- User
Take a look at this code for a line following robot that I'm coding that is supposed to follow a predermined track. from time import sleep # Import the time library for the sleep function from basehat import Button, LineFinder, IMUSensor from buildhat import Motor, ColorSensor
Initialize motors and sensors
motorA = Motor('A') motorB = Motor('B') lineFinderL = LineFinder(24) lineFinderR = LineFinder(26) IMU = IMUSensor() colorPort = "C" color = ColorSensor(colorPort)
def control_motors(speedA, speedB): """Starts both motors with given speeds.""" motorA.start(speedA) motorB.start(speedB)
def stop_motors(): """Stops both motors.""" motorA.stop() motorB.stop()
def rightTurn(valL, valR): """Performs a right turn based on line finder values.""" if valL == 0 and valR == 0: control_motors(100, -100) # Forward elif valL == 0 and valR == 1: control_motors(100, 100) # Right elif valL == 1 and valR == 0: control_motors(-100, -100) # Left else: control_motors(100, 0) # Slow right
def leftTurn(valL, valR): """Performs a left turn based on line finder values.""" if valL == 0 and valR == 0: control_motors(100, -100) # Forward elif valL == 0 and valR == 1: control_motors(100, 100) # Right elif valL == 1 and valR == 0: control_motors(-100, -100) # Left else: control_motors(0, -100) # Slow left
def straight(): """Keeps the robot moving straight by balancing motor encoders.""" control_motors(100, -100) if abs(encoderA) + 100 < abs(encoderB): control_motors(100, 100) elif abs(encoderA) > abs(encoderB) + 100: control_motors(-100, -100)
def place_cargo(): """Function for placing cargo.""" print("Cargo placed.")
Initialize encoder positions
initialPositionA = motorA.get_position() initialPositionB = motorB.get_position()
Initialize state machine variables
phase = 1 magnet_count = 0 state = 'LEFT_TURN' magnet_detected_last = False # To prevent multiple counts for a single magnet
try: while True: # Read encoder values encoderA = motorA.get_position() - initialPositionA encoderB = motorB.get_position() - initialPositionB
# Read line finder values valL, valR = lineFinderL.value, lineFinderR.value # Debugging information print(f"Sensor Left: {valL}, Sensor Right: {valR}") # Read IMU sensor data magx, magy, magz = IMU.getMag() gyrx, gyry, gyrz = IMU.getGyro() print(f"MX = {magx:.2f} uT MY = {magy:.2f} uT MZ = {magz:.2f} uT") print(f"GX = {gyrx:.2f} dps GY = {gyry:.2f} dps GZ = {gyrz:.2f} dps") # Display encoder values for each motor print(f"Encoder A: {encoderA}, Encoder B: {encoderB}") # State machine logic if state == 'LEFT_TURN': leftTurn(valL, valR) # Hill detection: Ascending if gyry > 5: print("Hill detected: Ascending") state = 'STRAIGHT' # Reset encoder positions when starting to move straight initialPositionA = motorA.get_position() initialPositionB = motorB.get_position() # Magnet detection with debounce if magx > 2000 and magy > 2000 and magz > 2000: if not magnet_detected_last: magnet_count += 1 print(f"Magnet detected. Count: {magnet_count} in Phase {phase}") if phase == 1: if magnet_count == 1: print("Phase 1: Switching to RIGHT_TURN") state = 'RIGHT_TURN' elif phase == 2: if magnet_count == 2: print("Phase 2: Switching to RIGHT_TURN") state = 'RIGHT_TURN' elif phase == 3: if magnet_count == 3: print("Phase 3: Placing cargo") state = 'PLACE_CARGO' magnet_detected_last = True else: magnet_detected_last = False elif state == 'STRAIGHT': straight() # Hill handling: Descending if gyry < -5: print("Descending hill") state = 'DESCENT' elif abs(gyry) < 1: print("Hill ended: Back to normal") state = 'LEFT_TURN' elif state == 'DESCENT': straight() # Completed descent if abs(gyry) < 1: print("Finished hill descent") state = 'LEFT_TURN' elif state == 'RIGHT_TURN': rightTurn(valL, valR) print("Completed RIGHT_TURN, switching to LEFT_TURN") state = 'LEFT_TURN' elif state == 'PLACE_CARGO': place_cargo() if phase < 3: phase += 1 print(f"Advancing to Phase {phase}") else: print("All phases complete.") magnet_count = 0 state = 'LEFT_TURN' # Small delay to reduce CPU load sleep(0.05) - Assistant