Hello,
I hope I copied in this simple code properly.
I have some LEDs fading but I wish to control them by a button press.
So I press the button and the LEDs fade to black.
But with my code below I have to hold the button down to make the LEDs fade. Not what I want. Driving me mad. Can anyone spot a silly error - or sloppy programming?
Thank you!
[code]
//LED STUFF
int LedStrip[3] = {3, 5, 6};
int brightness = 255;
int fadeAmount = 5;
unsigned long FADE_PERIOD = 2000; // fade time is 2 seconds
unsigned long fadeStartTime;
//BUTTON STUFF
const int ButtonPin = 13;
int ButtonState; // the current reading from the input pin
void setup() {
// LED STUFF
pinMode (LedStrip, OUTPUT);
fadeStartTime = millis();
//BUTTON STUFF
pinMode (ButtonPin, INPUT_PULLUP);
}
void DoTheFade() {
unsigned long progress = millis() - fadeStartTime;
if (progress <= FADE_PERIOD) {
long brightness = 255 - map(progress, 0, FADE_PERIOD, 0, 255);
analogWrite(LedStrip[0], brightness);
analogWrite(LedStrip[1], brightness);
analogWrite(LedStrip[2], brightness);
}
}
void loop() {
//BUTTON STUFF
ButtonState = digitalRead(ButtonPin);
if (ButtonState == LOW) // IF it is LOW run the fade loop
{
DoTheFade();
}
}
[/code]
you have not set your LedStrip pins as output correctly
check when you initialize fadeStartTime
Depending on your Arduino, 13 is not the best pin to use for a button with INPUT_PULLUP
you should have another Boolean variable that you set to true when the button has been pushed and this is the one you test against to see if you call DoTheFade()
may be something like this (typed here, fully untested)
const byte LedStrip[] = {3, 5, 6};
const byte ButtonPin = 13; // suggest you take another one.
const unsigned long FADE_PERIOD = 2000; // fade time is 2 seconds
unsigned long fadeStartTime;
bool fadingIsActive = false;
void setup() {
for (byte i = 0; i < sizeof LedStrip; i++) pinMode(LedStrip[i], OUTPUT);
pinMode (ButtonPin, INPUT_PULLUP);
}
void DoTheFade() {
unsigned long progress = millis() - fadeStartTime;
if (progress <= FADE_PERIOD) {
// set the fading value
int brightness = map(progress, 0, FADE_PERIOD, 255, 0);
for (byte i = 0; i < sizeof LedStrip; i++) analogWrite(LedStrip[i], brightness);
} else {
// we are done
for (byte i = 0; i < sizeof LedStrip; i++) digitalWrite(LedStrip[i], LOW);
fadingIsActive = false;
}
}
void loop() {
if ((digitalRead(ButtonPin) == LOW) && (!fadingIsActive)) {
for (byte i = 0; i < sizeof LedStrip; i++) digitalWrite(LedStrip[i], HIGH);
fadeStartTime = millis();
fadingIsActive = true;
}
if (fadingIsActive) DoTheFade();
}
if all goes well (untested), at a press of a button the 3 LEDs (with current limiting resistors, right???) would turn on and start to fade until they go dark 2 second later. and if you press again, it starts again
Well,
I am not going to even pretend I understand most of this but it works beautifully. Thank you so much. I shall study it and try to figure it out as I continue with my project.