Looping incremented variable

Hi All, I'm a newbie to Arduino. and I'm Trying some simple codes. I try to blink a led by increasing variable 'previousMillis' :

const int ledPin = 13; int ledState = LOW; long previousMillis = 0;

void setup() { pinMode(ledPin, OUTPUT); } void loop() { previousMillis++; //incrementing variable

if (previousMillis>500) ledState=LOW; // when the value more than 500, led goes OFF

if (previousMillis==1000) { // when the value reach 1000, led goes ON ledState=HIGH; previousMillis=0; // set variable back to zero }

digitalWrite(ledPin, ledState); // write to pin 13 }

but after I upload it to the board, it's not working. then I add Serial.begin() and Serial.println() to test the variable.

const int ledPin = 13; int ledState = LOW; long previousMillis = 0;

void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() { previousMillis++; //incrementing variable

if (previousMillis>500) ledState=LOW; // when the value more than 500, led goes OFF

if (previousMillis==1000) { // when the value reach 1000, led goes ON ledState=HIGH; previousMillis=0; // set variable back to zero } Serial.println(previousMillis); digitalWrite(ledPin, ledState); // write to pin 13 }

and it's WORK..

can anybody explain why the first codes is not working?

oockown: but after I upload it to the board, it's not working.

It's working fine. It's flashing the LED every 6.62 milliseconds. It's just too fast for you to see.

The processor is pretty fast, you know.

Adding the Serial.println() just slows things down enough for you to see them, because serial comms is pretty slow.

If you change the tests to 50000 and 100000 then it is visible, although pretty fast (every 66 mS).

Try changing the limits to 500000 and 100000 - then it blinks pretty obviously. And that shows how much you can get done in a second!

[quote author=Nick Gammon link=topic=90694.msg681246#msg681246 date=1328598656] If you change the tests to 50000 and 100000 then it is visible, although pretty fast (every 66 mS).

Try changing the limits to 500000 and 100000 - then it blinks pretty obviously. And that shows how much you can get done in a second! [/quote]

ahh! yes.. it works. Thank you very much.. :)

Of course, if you used previousMillis as it was intended, in whatever code you "borrowed", to contain a previous value returned by millis(), you would not be having the difficulties you are.