Hi All ,
I am using an Arduino UNO with two buttons/switches connected using internal pull up resistors and two LEDs . The power source is USB port of laptop .
This is part of a bigger project but I thought I should solve the problems individually as they occur .
What I want to happen in this code :
- Push button 1 , white LED fades in
- Push button 1 again , white LED fades out
- Push button 2 , red LED fades in
- Push button 2 again , red LED fades out
What actually happens :
- When I push button 1 , white LED fades in , push button 1 again , white LED turns off ( I would like it to fade out but I am not sure how to put that in my code )
- When I push button 2 the red LED does not fade in
So , two questions : how do I get the 2nd button to work and how do I get the LEDs to fade out instead of snap off ? I hope this is all the info you need to help troubleshoot my problem , if not , let me know what else I need to post and I will do so .
This is my first time attaching code , hope this works .
const int button1Pin = 2;
const int button2Pin = 4;
const int whitePin = 3; // LED pin is a PWM pin
const int redPin = 5; // LED pin is a PWM pin
int button1State = HIGH, lastButton1State = LOW, led1State = LOW;
int button2State = HIGH, lastButton2State = LOW, led2State = LOW;
unsigned long lastDebounce1Time = 0,
debounce1Delay = 50,
lastPress1Time = 0,
fade1Duration = 3000; // fade over 3 seconds (3000ms)
unsigned long lastDebounce2Time = 0,
debounce2Delay = 50,
lastPress2Time = 0,
fade2Duration = 3000; // fade over 3 seconds (3000ms)
void setup() {
pinMode(button1Pin, INPUT_PULLUP);
pinMode(whitePin, OUTPUT);
analogWrite(whitePin, 0);
pinMode(button2Pin, INPUT_PULLUP);
pinMode(redPin, OUTPUT);
analogWrite(redPin, 0);
}
void loop() {
int reading1 = digitalRead(button1Pin);
int reading2 = digitalRead(button2Pin);
unsigned long now1 = millis();
unsigned long now2 = millis();
if (reading1 != lastButton1State) {
lastDebounce1Time = now1;
}
if ((now1 - lastDebounce1Time) > debounce1Delay) {
if (reading1 != button1State) {
button1State = reading1;
if (button1State == LOW) {
led1State = !led1State;
lastPress1Time = now1;
}
}
}
if (led1State == HIGH) {
analogWrite(whitePin, min(255, (now1 - lastPress1Time) * 255 / fade1Duration));
} else {
analogWrite(whitePin, 0);
}
lastButton1State = reading1;
if (reading2 != lastButton2State) {
lastDebounce2Time = now2;
if ((now2 - lastDebounce2Time) > debounce2Delay) {
if (reading2 != button2State) {
button2State = reading2;
if (button2State == LOW) {
led2State = !led2State;
lastPress2Time = now2;
}
}
}
if (led2State == HIGH) {
analogWrite(redPin, min(255, (now2 - lastPress2Time) * 255 / fade2Duration));
} else {
analogWrite(redPin, 0);
}
lastButton2State = reading2;
}
}
Thanks for taking the time to read through this post and any help would be appreciated .
Tom