I'm trying to switch between 4 different brightness of an LED using an Arduino Uno. I've used analogWrite and not digitalWrite with PWM. The problem i'm facing is that the brightness does not switch at all when the pushbutton is pressed. Here's my code:
#define led 11 //assign pin 11 to LED
#define BUTTON 7 //assign pin 7 to pushbutton
int val=0; //val used to check current status of pushbutton later in the program
int old_val=0; //old_val to check previous status
int state=0; //state to check button presses
void setup()
{
pinMode(led,OUTPUT);
pinMode(BUTTON,INPUT);
}
void loop()
{
val=digitalRead(BUTTON); //check status of pushbutton
if((val==HIGH)&&(old_val==LOW)) //button pressed
{
state++; //increment state
delay(10); //debounce consideration
if(state>4) //want only 4 brightness options
{
state=1;
delay(10);
}
}
old_val=val;
if(state==1)
{
analogWrite(led,0); //0 brightness
}
else if(state==2)
{
analogWrite(led,75);
}
else if(state==3)
{
analogWrite(led,150);
}
else if(state==4)
{
analogWrite(led,255);
}
}
How can I resolve this problem?