I'm new and having trouble with this as well.
When I press and hold the button the LED stays on but doesn't dim. If I press again, it turns off.
I also note that the Arduino LED off of pin 13 is constantly on whether the button is pressed or not - is that supposed to happen?
I've reviewed my code and circuit but must be missing something.
Oh, and the LED setup called for a 270ohm resistor which I didn't have - so I used a 330. Maybe that has something to do with it?
Here's my code and the photo of my circuit. (WOW, how the heck did the photo flip? Sorry about that. Not sure what to do about it.)
If you can help enlighten me of my errors I'd greatly appreciate it.
// Example 05: Turn on LED when the button is pressed
// and keep it on after it is released
// including simple de-bouncing
// if the button is held, the brightness changes.
const int LED = 9; // the pin for the LED
const int BUTTON = 7; // the input pin where the pushbutton is connected
int val = 0 ; // val will be used to store the state of the input pin
int old_val = 0; // this variable stores the previous value of "val"
int state = 0; // 0 = LED off while 1 = LED on
int brightness = 128; // Stores the brightness value
unsigned long startTime = 0; // when did we begin pressing?
void setup () {
pinMode (LED, OUTPUT); // tell Arduino LED is an output
pinMode (BUTTON, INPUT); // and BUTTON is an input
}
void loop () {
val = digitalRead (BUTTON); // read input value and store it
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state; // change the state from off to on or vice-versa
startTime = millis(); // millis() is the Arduino clock. It returns how many milliseconds have passed since the board has been reset.
// this line remembers when the button was last pressed.
delay (10);
}
// check whether the button is being held down
if ((val == HIGH) && (old_val == HIGH)) {
if (state == 1 && (millis() - startTime) > 500) { // if the button is held for more than 500 ms.
brightness++; // increment brightness by 1
delay(10); // delay to avoid brightness going up too fast
if (brightness > 255) { // 255 is the max brightness
brightness = 0; // if we go over 255, let's go back to 0
}
}
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); //turn LED ON at the current brightness level
} else {
digitalWrite(LED, LOW); // turn LED off
}
}