Patrick398
New Member
Greetings.
Apologies for the stupidly simple question but rest assured i have been at this for days and have searched high and low across the internet.
I just want to fade an LED in and out while a button is being pressed. How long it takes the LED to fade in and out is dictated by a potentiometer. When the button is released the LED should reset to OFF irregardless of where it is in the fade in/out cycle.
The code i have so far does most of this but instead of resetting to OFF when the button is released it stays at whatever brightness it was at.
Also when the button is held for longer than a full fade in/out cycle it keeps repeating where as i just want it to happen once irregardless of how long the button is held. It seems so simple but my brain is melting. Any advice would be greatly appreciated!
Apologies for the stupidly simple question but rest assured i have been at this for days and have searched high and low across the internet.
I just want to fade an LED in and out while a button is being pressed. How long it takes the LED to fade in and out is dictated by a potentiometer. When the button is released the LED should reset to OFF irregardless of where it is in the fade in/out cycle.
The code i have so far does most of this but instead of resetting to OFF when the button is released it stays at whatever brightness it was at.
Also when the button is held for longer than a full fade in/out cycle it keeps repeating where as i just want it to happen once irregardless of how long the button is held. It seems so simple but my brain is melting. Any advice would be greatly appreciated!
Code:
int outputPin = 1;
int buttonPin = 0;
int fadeAmount;
int potVal;
bool wasPressed = false;
void setup() {
pinMode(outputPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(outputPin, LOW);
}
void loop() {
potVal = analogRead (2); // read pot on attiny pin 3
fadeAmount = map (potVal, 0, 1023, 20, 500);
if (digitalRead(buttonPin) == LOW) {
delay(15);
if (digitalRead(buttonPin) == LOW) {
wasPressed = true;
if (wasPressed == true) {
fadeLights();
}
if (wasPressed == false) {
digitalWrite(outputPin, LOW);
}
}
}
}
void fadeLights() {
for ( int i = 0; i <= 255; i++) {
analogWrite(outputPin, i);
for ( int y = 0; y < fadeAmount; y++) {
// if button is released
if (digitalRead(buttonPin) == HIGH) {
return;
}
}
}
for ( int i = 255; i >= 0; i--) {
analogWrite(outputPin, i);
for ( int y = 0; y < fadeAmount; y++) {
// if button is released
if (digitalRead(buttonPin) == HIGH) {
digitalWrite (outputPin, LOW);
return;
}
}
}
}