I am new to Arduino. Trying to help my son control a Knex roller coaster with multiple DC motors and magnetically actuated reed switches to determine the position of two roller coaster cars on same track.
Objective:
To execute a chunk of code continuously until two digital inputs (ie. Switch 0 and Switch 3) go high. This occurs when one of the roller coasters is in the station and the other is on the brake run portion of the track. I am trying to use a while loop to achieve this, but it is not behaving as I expected.
Here is my code ( I only included the pertinent part):
void loop(){
preStageCoasters(); // call preStageCoasters function
}
void preStageCoasters (){
// read the state of the switches S0 and S3
int Switch0 = digitalRead(S0);
int Switch3 = digitalRead(S3);
//continuously execute following code until both switches S0 and S3 go high
while ((Switch0 == LOW) || (Switch3 == LOW)); {
// read the state of the switches S0 and S3
int Switch0 = digitalRead(S0);
int Switch3 = digitalRead(S3);
//print the state of both switches to the terminal
Serial.print("Station Sw0=");
Serial.print(Switch0);
Serial.print (" ");
Serial.print("Brake Run Sw3=");
Serial.println(Switch3);
delay (1000);
}
}
Observations:
When I reset the Arduino with both switches low, I get no printing to the terminal. However, if I reset the Arduino with both switches high, I get the following print out on my terminal once every second...
Station Sw0=1 Brake Run Sw3=1
Station Sw0=1 Brake Run Sw3=1
Station Sw0=1 Brake Run Sw3=1
As soon as either one of the switches goes low, the "while" loop is exited and printing stops. When I replaced the "||" with a "&&" in the above while loop, I get the same behavior except now, both switches must go low to stop the printing. Neither makes any sense to me. I thought the code within the while loop was to continuously execute provided that the conditions were met? With both switches high, it should completely bypass the serial printing altogether. Very puzzling!
Questions:
- Can anyone explain what is happening here?
- How do I achieve what I want to do - namely continuously execute a chunk of code until both switches are high?
Thanks!
Don