I wrote some code that accend and descend 7 LEDs according to wether or not i press a button.
I feel like the code is long, messy and unnecessary complex for my task. Is there a way to optimise it?
const int switchPin = 2;
int switchState = 0;
int led = 3;
void setup() {
Serial.begin(9600);
for(int x = 3; x < 10; x++) {
pinMode(x, OUTPUT);
}
pinMode(switchPin, INPUT);
}
void loop() {
switchState = digitalRead(switchPin);
Serial.println(switchState);
if(switchState == 0 && led < 9) {
for(int x = 3; x < 10; x++){
digitalWrite(led, HIGH);
led++;
delay(50);
Serial.println(led);
}
}
if(switchState == 1 && led > 3) {
for(int x = 3; x < 10; x++){
led--;
digitalWrite(led, LOW);
delay(50);
Serial.println(led);
}
}
}
I feel like the code is long, messy and unnecessary complex for my task.
The first thing that comes to mind is the fact that you two variables, the for loop index and led, that are doing exactly the same thing. Get rid of one of them.
I feel like the code is long, messy and unnecessary complex for my task.
The first thing that comes to mind is the fact that you two variables, the for loop index and led, that are doing exactly the same thing. Get rid of one of them.
for(int x = 3; x < 10; x++){
digitalWrite(led, HIGH);
led++;
delay(50);
Serial.println(led);
}
What value will led have on each iteration?
What value will x have on each iteration?
Will they ever be different?
If not, why do you need two variables containing the same value?
What value will led have on each iteration?
What value will x have on each iteration?
Will they ever be different?
If not, why do you need two variables containing the same value?
I guess that's one way to do it. Not the one I had in mind.
Im sorry, i didn't really understand what you were referring to.
But removing the for loop actually made it better.
It lights up on led before checking the button again, making it possible to jump out before all are lit.