hello, i’m not sure why this isn’t working and was hoping someone could clue me in…
i’ve got a momentary pushbutton, 4 LEDs and a small relay hooked up to the UNO at the moment. here’s what i want to do:
-
first (on) button push: relay closes, LEDs fade on to 255. this is working.
-
after LEDs hit 255, they begin to randomly blink, fast. this is working as well.
-
second (off) button push: relay opens, LEDs fade out, loop breaks. this fade-out effect/break is not working, it just drops everything to 0 immediately. i’ve tried pretty much everything i could think of to mod this code to open the relay then fade the LEDs to 0 after the button push, but i’m just fumbling in the dark here. here’s an early iteration, i’d really appreciate any help =)
#define LED 3
#define BUTTON 2
#define LED2 13
#define LED3 5
#define LED4 9
#define relay 12
int i = 0;
int state = 0;
int val = 0;
//A function to see if the button has been pressed, returns an int
int CheckButton()
{
return(digitalRead(BUTTON) == HIGH);
}
void setup()
{
pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(BUTTON, INPUT);
pinMode(relay, OUTPUT);
}
void loop()
{
//Check to see if the button has been pressed.
if(digitalRead(BUTTON) == HIGH)
{
//While the digital read statement is true (high) continue the loop
while(digitalRead(BUTTON) == HIGH)
continue;
//state is true as state is 0 and if we do !state then it is 1
state = !state;
}
//If state is 1 which it will be as we wont make it 0. If we dont use state then we have to keep pressing the button
if(state)
{
for (i = 0; i < 255; i++)
{
//If checkbutton is true it means the button has been pressed
if(CheckButton())
{
//Turn off the LED and break the loop
analogWrite(LED, 0);
analogWrite(LED2, 0);
analogWrite(LED3, 0);
analogWrite(LED4, 0);
digitalWrite(relay, 0);
break;
}
//Continue fading
analogWrite(LED, i);
analogWrite(LED2, i);
analogWrite(LED3, i);
analogWrite(LED4, i);
delay(15);
digitalWrite(relay, 1);
}
for (i != 255; i > 0; i--)
{
//If the checkbutton is true it means the button has been pressed
if(CheckButton())
{
//Turn off the LED and break the loop
analogWrite(LED, 0);
analogWrite(LED2, 0);
analogWrite(LED3, 0);
analogWrite(LED4, 0);
digitalWrite(relay, 0);
break;
}
//Continue fading
analogWrite(LED, random(20, 254));
analogWrite(LED2, random(20, 254));
analogWrite(LED3, random(20, 254));
analogWrite(LED4, random(20, 254));
delay(30);
digitalWrite(relay, 1);
}
}
}