Hello Folks!
I am new here and a beginner to Arduino programming.
I am stuck at a project and after trying different methods to execute my program which I failed, i sought to take help at this forum.
My program is to use a single pushbutton to Turn off and on LED but also dimming or brightening the LED with the same Pushbutton.
If the Pushbutton is pressed only once if acts as on/off switch and turns LED on if it is off in current state and vice versa. While the LED is turned on , if the button is pressed long it dims the LED light and next time the button is pressed long it brightens the led and vice-versa.
Here is my code, all help is greatly appreciated. Thanks in advance ![]()
//Creating a dimmable Led Lamp using one Pushbutton.
//When button is pressed once if works as on/off switch
// and when it is pressed for long, it will either dims or brightens LED.
//Pressing pushbutton once, turns LED either ON or OFF; whereas keeping pushbutton pressed long with either dim or brighten the LED as per the last action.
int ledState=0; //indicates LED is turned off when program starts
int buttonOld=1; // button State at the start of program
int buttonNew; //button State when pushbutton is pressed everytime.
int ledPin=3; // Assigning Led to Arduino Pin no.3
int buttonPin=10; //Assigning button to pin no. 10
int dt=100;
void setup() {
Serial.begin(9600);
pinMode(ledPin,OUTPUT); //Declaring LED pin is OUTPUT
pinMode(buttonPin, INPUT); //Declaring button Pin is INPUT
}
void loop() {
buttonNew=digitalRead(buttonPin);
if(buttonOld==0 && buttonNew==1)//when buttonState changes from 0 to 1,make the switch
{if(ledState==0){
digitalWrite(ledPin,HIGH);
ledState=1;
}
else{
digitalWrite(ledPin,LOW);
ledState=0;
}
}
buttonOld=buttonNew;
delay(dt);
int ledBright; //making a dimmable LED
int buttonVal=digitalRead(buttonPin);
if(buttonVal==0 && ledState==1) //Means if pushbutton is pressed long and while LED is ON, brighten the LED by value of 15
{ledBright=ledBright+15;}
if(ledBright>255){ledBright=255;
analogWrite(ledPin,ledBright);
}
if(buttonVal==0 && ledState==1) //Means next time when pushbutton is pressed long and while LED is On, it will dim the LED brightness by value of 15.
{ledBright=ledBright-15;}
if(ledBright<0){ledBright=0;
analogWrite(ledPin,ledBright);
}
Serial.print(buttonNew);
Serial.print(",");
Serial.print(ledBright);
Serial.print(",");
Serial.println(buttonVal);
delay(dt);
}



