Switch off LED after the LED selected by pushbutton

Hi. Please excuse my horrible code. I am brand new to this and I am doing things ineffectively in order to get visibility :slight_smile:

I have re purposed the “debounce” example in order to switch LED’s on and off. Instead of a pushbutton, I am using a proximity sensor. Each time the proximity sensor reads a value, the board’s built-in LED switches on or off, depending on the state it was in.

If the board LED on pin 13 is HIGH, my green LED on pin 3 is HIGH, and my red LED on pin 4 is low. If 13 goes low, the red and green swap. This works well.

(Once I am done, I will no longer use the built-in LED on pin 13 as a marker, but a variable instead)

I am trying to automate a toy train track. The train will trigger the proximity sensor and then switch a toy traffic light, as well as either relay A or B, which I haven’t included yet. The relays in turn will power electro magnets that move the track switch.

Here is where I am stuck. I only want to power the relay for 2 seconds once a switch takes place. For now, if I can get the green or red LED to stay on for only 2 seconds once the proximity sensor has been triggered, I can use the code for testing.

I have tried various times to use the “Blinking without delay” example, but no luck so far. I can get the whichever comes on LED to switch off after two seconds, but it does not come back on after the proximity sensor has read a value again.

Please assist

TrainControl.ino (2.86 KB)

I see no 2 second timing whatsoever. Did you attach the correct sketch? Also for such a small sketch, please just put it in code tags, rather than forcing me to upload it.

Also, all time variables must be unsigned long type to avoid rollover issues.