Hi as you will tell I am new to this but have undertaken a minor Halloween project that I though would be simple....and am stuck
The code below is to light 3 LED's one constantly and the other 2 in differing flash sequences. There is a function called BlinkLed in a while loop triggered by a button press.
This all worked perfectly. Press the button, lights sequence as expected ..push it again and they stop. The problem was the I pushed it again they stopped flashing but stayed in whatever state they were on. I thought I would tidy the code with three digitalwrite (led,LOW) lines to turn them all off.
Weirdly this didn't do the trick. Now when the button is pressed, the green LED lights as required but the 2 flashing ones, that called the function, came on at the right time but then straight off...they didn't stay on for the correct length of time.
When the button is pressed again they all go off.
The whole flashing stuff thing is in a while loop but I can't understand why the digitalwrite LOW lines which are outside the loop seems to affect a function inside the loop?
Can anyone help please...would be very grateful
#define redLed 13 //
#define yellowLed 12
#define greenLed 11//pin for each led
unsigned long previousMillis[2]; //[x] = number of leds
int buttonState = 0;
const byte buttonPin = 2;
void setup() {
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
buttonState = digitalRead(buttonPin);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
while (buttonState == HIGH) {
digitalWrite(greenLed,HIGH);
BlinkLed(redLed, 2000, 0);
BlinkLed(yellowLed, 1000, 1);
buttonState =digitalRead(buttonPin);
}
{
digitalWrite(greenLed,LOW);
digitalWrite(redLed,LOW);
digitalWrite(yellowLed,LOW);
}
}
void BlinkLed (int led, int interval, int array){
//(long) can be omitted if you dont plan to blink led for very long time I think
if (((long)millis() - previousMillis[array]) >= interval)
{
previousMillis[array]= millis(); //stores the millis value in the selected array
digitalWrite(led, !digitalRead(led)); //changes led state
}
}