Home \ Help \ Search \ Login RSS

Welcome, Guest. Please Login

This forum is now READ-ONLY! Please visit http://forum.wiring.co/ for the new forum.

Wiring ForumProgramming Questions & HelpSyntax › delay vs millis

Page Index Toggle Pages: 1
delay vs millis (Read 9454 times)
11/01/10 at 08:53:04

mga   Offline
YaBB Newbies

Posts: 41
*
 
Hi

Can any:

Code (C++):
int n = 100;
void loop() {
  doSomething();
  delay(n);
}
 


be modeled using:

Code (C++):
int n = 100;
unsigned long mycounter = 0;
void loop() {
  if (millis()-mycounter>n) {
    mycounter = millis();
    doSomething();
  }
} 



and expect the same results?
 
IP Logged
 
Reply #1 - 11/01/10 at 17:53:49

barragan   Offline
YaBB Administrator

Posts: 939
*****
 
not really, the second program doesn't block the cpu. The delay() command blocks the cpu for the number or milliseconds specified, on the other hand the second program just checks if "n" milliseconds have passed, if true it executes the commands inside the if, it not it continues executing other statements within the program.

Code (C++):
int n = 100;
unsigned long mycounter = 0;

void loop() {
  if (millis()-mycounter>n) {
    mycounter = millis();
    doSomething();
  }
  // … other things continue executing beyond this point

}
 



 
IP Logged
 
Reply #2 - 11/01/10 at 20:10:55

mga   Offline
YaBB Newbies

Posts: 41
*
 
OK. So this is what I want (not blocking the CPU). I assume it is advisable NOT to use delay() unless there is a very special reason to do so.
 
IP Logged
 
Reply #3 - 11/01/10 at 22:24:50

barragan   Offline
YaBB Administrator

Posts: 939
*****
 
that's right delay() will stop the cpu.
 
IP Logged
 
Page Index Toggle Pages: 1