8 years, 4 months ago.

Interrupt in a traffic light with pedestrian crossing

My program simulates a traffic light with a pedestrian crossing. when a switch is pressed the normal traffic light sequence is interrupted to execute a pedestrian crossing. If say the switch is pressed when the amber light is on, the interrupt waits for the traffic light to go back to red before allowing pedestrians to cross. The problem is after allowing pedestrians to cross, the program starts from where it was interrupted, i.e. instead of traffic light starting from red again ,it starts from green (because it was interrupted on amber). My question is: is there any way for the program to detect when an interrupt has happened, so that I can force the program to start the traffic light from red rather than from where it was interrupted? Thanks.

Question relating to:

1 Answer

8 years, 4 months ago.

The interrupt shouldn't directly change the pattern at all, it should set a flag indicating that the button has been pressed.

In the main loop you look for that flag and change the state of the lights as needed. Once the lights have been red for the crossing time you clear the flag and let the normal state machine behavior take over.

In pseudo code:

If green and (have been green for n seconds or (button pressed and have been green for m seconds)) go to yellow
If yellow and have been yellow for n seconds go to red.
If red (
   if button flag set light pedestrian sign
   if pedestrian sign has been lit for n seconds turn pedestrian sign off and clear button flag
   if have been red for n seconds and pedestrian sign has been off for m seconds go to green
)