i found this piece of code in a book and its meant to change the brightness of an led depending on how long you hold the button. and i understand what the code does and what it is meant to do. i understand the logic flip to detect if the switch was pressed or not, but where i get confused is when it says starttime = millis(); because millis is how long since the program has started and it writes that millis number to starttime, but then later on in the code it says mills() - starttime>500, and wouldn't that always be zero because starttime was set to equal millis() in the begining? why does the starttime go up as you hold the button?
If someone could SIMPLY explain this to me that would be very helpful!!! i am very much confused by this program.
down below is the code.
const int led = 9;
const int button1 = 3;
int val = 0;
int oldval= 0;
int state = 0;
int brightness= 128;
unsigned long starttime= 0;
void setup()
{
pinMode(led,OUTPUT);
pinMode(button1, INPUT);
Serial.begin(9600);
}
void loop()
{
val= digitalRead(button1);
if ((val == HIGH)&& (oldval== LOW))
{
state = 1 - state;
starttime= millis ();
delay (10);
}
if ((val == HIGH) && (oldval == HIGH))
{
if (state == 1&& (millis()-starttime)>500)
{
brightness++;
delay (10);
if (brightness >255)
{
brightness = 0;
}
}
}
oldval= val;
if (state == 1)
{
analogWrite(led, brightness);
} else{
analogWrite (led, 0);
}
}
Moderator edit:
</mark> <mark>[code]</mark> <mark>
</mark> <mark>[/code]</mark> <mark>
tags added.
hold_buttondown.ino (707 Bytes)