Problems with delay

Hi,

it seems that delay() function on my Duemilanove does not work as it should. The delay is random and much shorted that expected. For example, the following piece of code:

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  int secs = millis()/1000;
  Serial.println(secs);
  delay(1000);      
}

produces output like;

0
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
3
3
....

Have I fried the chip or what could explain this behavior?

millis() is a function that returns a long datatype. So try changing 'int secs' to 'long secs' or 'unsigned long secs'.

Should work better.

/me

I just tried the same code but in processing [so I didn't have to setup the hardware] and I got a steady stream of 0, 1.0, 2.0, 3.0, 4.0...

Not sure how Arduino and Processing go as far as similarity apart from being very similar .... if you know what I mean.

But try it as a 'long' or 'unsigned long' and I'm 99.9% sure it'll do what you hoped.

But watch as delay() will wait for a time of at least the value you entered, it's not perfect.

/me

I calculated the seconds only after I otherwise realized that delay does not work as it should. It clearly prints lines much faster as expected. I even tried Blink-example and the led seemed to blink randomly. At first it blinked much faster than supposed, then for some time it blinked at seemingly correct rate and then after a while it went wild again.

You could use millis() to calculate an interval to leave out delay()

But the the code up there would be stupefied.

/me

I tried using millis() instead of delay(). Counting went ok at first, but at about 60 secs it went wild too, printing perhaps a few hundred times each second.

void myDelay(unsigned long ms)
{
  unsigned t1 = millis()+ms;
  while (millis() < t1) { } 
}

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  unsigned long secs = millis()/1000;
  Serial.println(secs);
  myDelay(1000);
}

Where you have said 'unsigned t1' you haven't given it a data type. Try 'unsigned long'.

/me

Thanks! That fixed the problem. Without "long" it was int and it overflowed. There is still something wrong with the actual delay() function, but at least now I can get over it. Release notes says there have been some changes in delay() in version 0.13 (I am using 0.15 on Linux). Perhaps something broke there.

But now I have to go to bed. It's almost 3am here and alarm clock wakes me up at 6.50.

Thanks again for helping me up.

It's only 1pm here. But alarm goes off at 7am in about a week when I go back to college!

Good luck, /me