C++ Arduino Coding

Hey guys. I'm very new to C++ coding and am stuck on a problem with my arduino code.

I'm wondering how to write a code that involves 3 LEDs on my breadboard. I would like to make it so that when voltage is not passing through my switch, one LED on my board turns on and stays on. However, when the switch is closed, I want my one lit LED to immediately turn off and for the other two LEDs to immediately turn on and do a sequence of blinking involving "delay()" functions. However, I only want these two blinking LEDs to continue their sequence while the switch is closed. When the switch is open once more, I want the blinking to immediately stop and revert to the other single LED that stays on. My code currently makes it so that the two LEDs that blink will finish their code sequence even while the circuit is open and then will switch over to the other single LED thereafter.

I guess what I'm hoping for is a type of loop that constantly checks a condition, i.e. the voltage across my switch, and will stop immediately if that condition is broken.

Here is my current code if it helps at all.

int boardState = 0;

void setup() {
pinMode(2,INPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
}

void loop() {
boardState = digitalRead(2);
if(boardState == HIGH){
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
delay(100);
digitalWrite(4,LOW);
delay(100);
digitalWrite(4,HIGH);
delay(100);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
delay(100);
digitalWrite(4,HIGH);
delay(100);
digitalWrite(4,LOW);
delay(100);
}
else{
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
}
}
Last edited on
it looks like you need more checks. something like

if(high)
pattern section 1
if high
pattern 2
if high
pattern 3
etc
by doing this, you will also skip the delays if the switch state changed in the middle, so it will jump out and re-loop on a low condition (doing the second section) much more quickly, which should be what you want (?).

if that isn't fast enough swapping or gives ugly results, you may have to wrap the low switch condition into a function and do this instead..

if high
pattern 1
else
low function
if high
pattern 2
else low function

etc.

you may also want boardstate to be volatile, on this I am not sure. Normal C++ (which this is NOT) would potentially need to consider this, as its a variable that changes OUTSIDE the code via a device, so to keep it current you may need to add that keyword.
Topic archived. No new replies allowed.