Tell me more ×
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It's 100% free, no registration required.

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?

share|improve this question
Does your push button automatically switch back after releasing it? – Camil Staps 2 days ago
Yes it does. Instead of switching to the next brightness, it goes back to the same brightness. – user22934 2 days ago
#define led 11 //assign pin 11 to LED this is wrong as long as you use analog , this can be from 0-5 . – yahya tawil 2 days ago
1  
I thought pins 1 to 5 serve only as analog INPUTS. Are you sure about it? – user22934 2 days ago
yes I'm sure it is for input and output . – yahya tawil 2 days ago
show 1 more comment

1 Answer

Although your code has some weaknesses it shouldn't generate the behavior you describe. You haven't provided any shematic of the setup so my answer is really just a guess but a missing pull-down resistor would probably cause exactly what you're telling : the digital reading of the button pin sporadically switches between HIGH and LOW, and the led appears to flicker randomly instead of just changing brightness as expected.

share|improve this answer
Thanks for pointing it out. I just realized there's no pull down resistor in my circuit. Will revert back when I'm able to add one. – user22934 2 days ago
1  
The AVR that the arduino is based on has internal pull up resistors. It is much easier to use the switch to connect to ground and have the internal pullup resistors enabled. – Kurt E. Clothier 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.