Trying to get a modified traffic signal challenge worked out The challenge is for a robot to go around the perimeter of a rectangular field and execute 90 degree turns when it gets within 4.5 inches of a wall.  Simultaneously, if the bot encounters a red flag, it needs to stop until the flag color turns green.  At that point, the arm holding the color sensor needs to dip to avoid the traffic signal, and once it is passed, continue on it's way.


I have tried running two threads, one where the bot encounters a flag (which I have constructed a switch for cases red and green), while the other is where it encounters a wall.  I think these two threads need to be encased within an infinite loop, but I can't seem to make it so.
You can use finite state machine. In this case you will have these 5 states:


RUN


Action: turn on the motors for moving straight

Transition to state TURN in case of event: ultrasonic sensor detects obstacle closer than 4.5 inch).

Transition to state WAIT in case of event: color sensor detects red color


WAIT


Action: stop motors

Transition to state CONTINUE in case of event: color sensor detects green


CONTINUE


Action: move forward a bit while avoiding the flag

Transition to state RUN immediately.


TURN


Action: Turn the robot 90 degrees right, increment the rotations

Transition to state STOP in case of event: rotations = 4

Transition to state RUN in case of event: rotations &lt; 4


STOP


Action: Interrupt the program.

Here is the code I've just scratched without a testing, let me know if it works:


You can enhance the state machine to check for the flag during rotations, too. :)

You can learn this robotics topic from the great book by Daniele Benedetelli - LEGO MINDSTORMS EV3 Laboratory.