I am building a marble sorter that sorts the colored marbles in the photo attached. Here is how it works: you drop the marbles into a hopper, they are stoped by 2 gates attached to a motor that have a small space in between the gates for one marble to be detected by the color sensor at a time. Once the marble color has been detected, the second motor spins three cups on a plate and spins the correct cup to the corresponding color under the slide. Then, the motor that controls the gates opens and closes very quickly, allowing for another marble to be detected, and the previous marble slides into the correct cup. I’m not sure what is wrong with my code, but if someone could help I would be grateful.
the code:
brain = Brain()
motor_1 = Motor(Ports.PORT1)
motor_2 = Motor(Ports.PORT2)
optical_3 = Optical(Ports.PORT3)
optical_3.set_light(LedStateType.ON)
CUP_POSITIONS = {
'orange': 0,
'white': 120,
'gray': 240
}
marble_detected = False
def open_and_close_gate():
"""Opens and closes the gate very quickly."""
motor_1.spin_to_position(45, DEGREES, wait=True)
wait(0.1, SECONDS)
motor_1.spin_to_position(0, DEGREES, wait=True)
def rotate_to_cup(color):
"""Rotates motor_2 to align the correct cup."""
if color in CUP_POSITIONS:
motor_2.spin_to_position(CUP_POSITIONS[color], DEGREES, wait=True)
wait(0.5, SECONDS)
else:
brain.screen.print("Color not recognized!")
def detect_marble_color():
"""Detects the color of the marble using the optical sensor."""
wait(0.2, SECONDS)
if optical_3.hue() <= 32:
return 'orange'
elif optical_3.color() == Color.WHITE:
return 'white'
elif optical_3.hue() <= 240:
return 'gray'
else:
return None
while True:
marble_color = detect_marble_color()
if marble_color and not marble_detected:
brain.screen.print("Detected: {marble_color}")
open_and_close_gate()
rotate_to_cup(marble_color)
marble_detected = True
elif not optical_3.is_near_object() and marble_detected:
marble_detected = False
else:
wait(0.3, SECONDS)