Robotics Merit Badge Sumobot Starter Code

#!/usr/bin/env pybricks-micropython

"""
Simple Sumobot Program
----------------------
This robot drives forward until it detects a black line (the edge of the ring),
then backs up, turns around, and continues searching for opponents.
"""

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, ColorSensor
from pybricks.parameters import Port
from pybricks.robotics import DriveBase

# Initialize the EV3 brick
ev3 = EV3Brick()

# Set up the motors
# Change these ports to match your robot's configuration
left_motor = Motor(Port.B)
right_motor = Motor(Port.C)

# Set up the color sensor to detect the black line
# Change this port to match where your sensor is connected
color_sensor = ColorSensor(Port.S1)

# Create a DriveBase for easier driving
# The two numbers are wheel diameter (mm) and axle track (mm)
# TODO: Measure and adjust these values for your specific robot
robot = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=114)

# TWEAKABLE SETTINGS - Experiment with these values!
DRIVE_SPEED = 200        # Speed when driving forward (mm/s) - try 100-400
TURN_SPEED = 100         # Speed when turning (mm/s) - try 50-200
BACKUP_DISTANCE = -80    # How far to back up (mm) - negative means backward
TURN_ANGLE = 120         # How much to turn (degrees) - try 90-180
BLACK_THRESHOLD = 20     # Light sensor value to detect black line - try 15-30

# Main loop - runs forever until the program is stopped
while True:
    print("Forward!")
    # Drive forward looking for opponents
    robot.drive(DRIVE_SPEED, 0)
    print(color_sensor.ambient())
    
    # Check if the light sensor sees the black line (edge of ring)
    if color_sensor.reflection() < BLACK_THRESHOLD:
        print("Backward!")
        # Edge detected! Stop immediately
        robot.stop()
        
        # Back up from the edge
        robot.straight(BACKUP_DISTANCE)
        
        # Turn around to face back into the ring
        robot.turn(TURN_ANGLE)
        
        # Brief pause before continuing (optional)
        # wait(100)  # Uncomment this to add a 100ms pause