I had to do some research about how to write an 'else' statement. As I already had an 'if' statement me and Xavi looked at the fact that if I have an if I should also have an else. As after all this is a machine I am telling this machine what to do when the button is pressed, I should tell it what to do when the button isn't pressed.
So, what is an 'else' statement.
The if... else allows greater control over the flow of code than the basic 'if' statement, by allowing multiple tests to be grouped together. An 'else' clause (if at all exists) will be executed if the condition in the if statement results in false. The else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same time.
After learning this I re - wrote the code;
const int buttonPin = 2;
const int motorOne = 13;
const int motorTwo = 11;
const int motorThree = 9;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an outfput.
pinMode(motorOne, OUTPUT);
pinMode(motorTwo, OUTPUT);
pinMode(motorThree, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
if ( digitalRead(buttonPin) == HIGH) {
motor(motorOne);
motor(motorTwo);
motor(motorThree);
}
else if ( digitalRead(buttonPin) == LOW) {
}
}
void motor(int motorNumber) {
digitalWrite(motorNumber, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(motorNumber, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
Comments