I just made a code:
simple one…that it…when u press the button and as long as u hold the button ,the led will be constantly increasing the brightness
when u release the button the led will turn off suddenly
the above was my plan of making a code.I made the code ,no errors,but stilll its not working…!!!
can any one please say the solution for this …
I Commented a few problems, but there are more.. For example "val" never changes.
You also need to learn to style your code.. It will make is easier to read.. See here. Side note please read the whole page for that link..
const int led = 9;
const int button = 7;
int val = 0;
int brightness = 128;
int state = 0;
unsigned long startTime = 0;
int old_val = 0;
void setup()
{
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop()
{
//this will not do anything..
digitalRead(button);
// Unnecessary brackets.. should be "if(val==HIGH && old_val == LOW)"
if((val==HIGH)&&(old_val == LOW))
{
state = 1 - state; //
startTime = millis();
delay(10);
}
// Unnecessary brackets.. should be "if(val == HIGH && old_val = HIGH)"
if((val ==HIGH) && (old_val = HIGH))
{
// Unnecessary brackets.. should be "if(state == 1 && millis() - startTime > 500)"
if(state ==1 && (millis() - startTime) >500)
{
brightness++;
delay(10);
if (brightness > 250)
{
brightness = 0;
}
}
}
old_val = val;
if(state = 1) // This sets state to 1 and then returns true, thus will always run
{
analogWrite(led,brightness);
}
else
{
analogWrite(led,0);
}}
GoForSmoke:
I completely disagree with your unnecessary brackets comments.
Have to agree with this.
Just when you think you know the order of operator precedence, there'll be one that catches you out. An extra set of brackets, to be sure costs nothing.