byte track = 0;bool waiting = false; //set to true if you want to start with waiting in the stationconst byte TrackPins[] = {2, 3}; //connect between pin and GNDconst byte ReedPins[sizeof(TrackPins)] = {4, 5};const byte DirectionPin = 6;const unsigned long WaitInterval = 10 * 1000UL;unsigned long previousMillis = 0;void setup() { //setup ReedPins for(byte i = 0; i < sizeof(ReedPins); i++){ pinMode(ReedPins[i], INPUT_PULLUP); } //setup TrackPins for(byte i = 0; i < sizeof(TrackPins); i++){ pinMode(TrackPins[i], OUTPUT); } //setup direction pin pinMode(DirectionPin, OUTPUT); //if we don start with a wait, depart the first train! if(!waiting){ departTrain(); }}void loop() { //don't overshoot the number of tracks we have if(track >= sizeof(TrackPins)){ track = 0; } //are we waiting in the station? if(waiting){ //done waiting? if(millis() - previousMillis >= WaitInterval){ //set we are done waiting waiting = false; //depart the next train departTrain(); } } //not waiting to depart else{ //has train arived? if(!digitalRead(ReedPins[track])){ //stop all trains stopTrains(); //set waiting and set time waiting == true; previousMillis = millis(); //goto next track track++; } }}void departTrain(byte nr){ //do nothing if we call a non-existing track if(nr < sizeof(TrackPins)){ //set the direction. Alternate direction per track digitalWrite(DirectionPin, nr % 2); //enable corresponding track digitalWrite(TrackPins[nr], HIGH); //wait till the reed is cleared while(!digitalRead(ReedPins[track])); }}void inline departTrain(){ departTrain(track);}void stopTrains(){ for(byte i = 0; i < sizeof(TrackPins); i++){ digitalWrite(TrackPins[i], LOW); }}