Hi everyone.
I got an arduino a couple of days ago and allready having trouble with my fist project. I want control the brightnes of three leds with 2 pushbuttons. One for increasing the brightnes and the other for decreasing.
The circuit is simple. Two pushbuttons with pulldown resistors to pins 2 and 4.
The leds are conected through resistors to pins 11, 5 and 6.
I 've set 5 levels of brightness using a counter variable. The counter determines the PWM value that is sent to the leds. The problem is that eventhough the counter works fine, the PWM value is incorrect when brightness goes all the way up or down, or when i switch from brightness up to brightness down.
Here is the code:
//Variables won't change
const int lamp1 = 11; //led #1
const int lamp2 = 5; //led #2
const int lamp3 = 6; //led #3
const int upPin = 2; //button for brightnes up
const int downPin = 4; //button for brightnes down
//Variables will change
int lastCounter = 3;
int counter; //the basic counter
int up; //brightnes up button reading
int down; //brightnes down button reading
int volt; //PWM value sent to the leds
void setup(){
pinMode(up, INPUT);
pinMode(down, INPUT);
Serial.begin(9600);
}
void loop(){
counter = lastCounter; //counter recyrculation
up = digitalRead(upPin); //button pins reading
down = digitalRead(downPin);
if (up == HIGH) { //if the up button is pressed
counter = counter++; //counter increases by one
Serial.println("Counter");
Serial.println(counter);
Serial.println("PWM");
Serial.println(volt);
}
if (down == HIGH) { //if down button is pressed
counter = counter--; //counter decreases by one
Serial.println("Counter");
Serial.println(counter);
Serial.println("PWM");
Serial.println(volt);
}
if (counter > 5){ //check that counter won't get further than 5
counter = 5;
}
if (counter < 2){ //check that counter won't fall bellow 1
counter = 1;
}
switch (counter){ //depending on counter value the propper PWM value is sent to the leds
case 1:
volt = 50;
break;
case 2:
volt = 100;
break;
case 3:
volt = 150;
break;
case 4:
volt = 200;
break;
case 5:
volt = 250;
break;
}
analogWrite(lamp1, volt); //leds turn on with the desirable PWM
analogWrite(lamp2, volt);
analogWrite(lamp3, volt);
lastCounter = counter; //counter recylculation
delay(500);
}
I thing the problem lyies in the switch command.
Any thoughts?
BTW my english sucks, working on improving it!!
Thanks.