Make a two-way traffic light code for the Arduino Mega 2560 that will operate both with and without a switch at the same time. Additionally, if there is a switch, one will start off green and the other red.
In this code, the traffic light is controlled using a state machine. The setup() function initializes the pin modes and checks if the switch is connected by reading its state. If the switch is pressed (LOW state), the traffic light starts with Green2, otherwise, it starts with Green1.
The loop() function updates the switch state and controls the traffic light based on the current state. The switch statement is used to determine the behavior of each state. The traffic light timings are controlled using millis() to track the elapsed time.
If the switch is detected during operation, the traffic lights are immediately switched to the opposite state, overriding the current state and starting with Green1 and Red2.
Make sure to connect the LEDs and the switch to the correct pins on the Arduino Mega 2560 as defined in the code.