I’m using an Arduino to control my train set. The plan is to have a programmed routine that the train follows. Being relatively new to programming, it appears to me that such a routine is best performed by sequential software. I’m somewhat freaked out by the Arduino software because the void loop keeps repeating so more conditions need to be set up to control events.
Anyway, what I’m trying to do at this point is simply run the train and have it reverse direction when it goes over a reed switch located under the track. Once it reverses, it goes over a second reed switch to send it forward again and the process repeats.
The code below is only partially working in that it detects the first reed switch and stops the train for 3 seconds as planned. However, when the train restarts, it does not reverse but continues in the forward direction. I can’t seem to get the correct logic figured out and was hoping someone could offer some suggestions on how best to accomplish this.
void loop() {
if (dir == 0) { // train in forward direction
if (bitRead(poll0,4)) { // reed switch 4 activated
throttle = 0; // train coasts to a stop
}
if (spd > 0) { // start timer when train stops
directionTimer = millis() ;
}
if (millis() - directionTimer >= directionInterval){ // after 3 seconds
dir = 1; // set direction to reverse
throttle = 50; // at speed 50
}
}
if (dir == 1) { // train in reverse direction
if (bitRead(poll0,5)) { // reed switch 5 activated
throttle = 0; // train coasts to a stop
}
if (spd > 0) { // start timer when train stops
directionTimer = millis() ;
}
if (millis() - directionTimer >= directionInterval){ // after 3 seconds
dir = 0; // set direction to forward
throttle = 100; // at speed 100
}
}
}