Go Down

Topic: Which is better millis()or timer? (Read 260 times) previous topic - next topic

wounder1

Jul 19, 2019, 01:25 pm Last Edit: Jul 19, 2019, 01:41 pm by wounder1
I want to create a 30 mint delay in my program(Arduino)
which is better millis() or timer for this purpose?
please give me an example to clarify my doubt ...
Thanks.

evanmars

Do you want the entire program to wait for 30 minutes without doing anything* else?
Do you want to be able to read inputs or do anything else during this time?

If the former, just use delay().
If the latter, use millis()




*other than process interrupts, I believe.

wounder1

1. Do you want the entire program to wait for 30 minutes without doing anything* else?

no..along with i want to receive data from UART..

Do you want to be able to read inputs or do anything else during this time?

Continuously wait  uart  for recive data

sterretje

Just use millis(). It's far simpler (in my opinion).
If you understand an example, use it.
If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.

lesept

For example :

Code: [Select]
unsigned long chrono = 0;
const unsigned long duration = 30*60*1000ul; // 30 minutes in milliseconds

void setup() {
  chrono = millis();
}

void loop () {
  while (millis()-chrono<duration) {
    // do your UART stuff here
  }
  // do the rest
}
A force d'essayer on finit par réussir... Donc, plus ça rate, plus on a de chances que ça marche (proverbe Sharduinok).

Robin2

#5
Jul 19, 2019, 02:55 pm Last Edit: Jul 19, 2019, 02:56 pm by Robin2
For example :
A WHILE loop blocks until it completes - even if it does things during the loop.

For more flexible non-blocking use of millis() have a look at how millis() is used  in Several Things at a Time.

Note how each function runs very briefly and returns to loop() so the next one can be called. None of the functions tries to complete a task in one call. And there may be dozens of calls to a function before it is actually time for it to do anything.



And see Using millis() for timing. A beginners guide if you need more explanation.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

GolamMostafa

#6
Jul 19, 2019, 03:30 pm Last Edit: Jul 19, 2019, 04:00 pm by GolamMostafa
Here is a demonstrative sketch based on Post#4.
Code: [Select]
unsigned long chrono = 0;
const unsigned long duration = 5000;//30 * 60 * 1000ul; // 30 minutes in milliseconds

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop ()
{
  unsigned long chrono = millis();
  while (millis() - chrono < duration)
  {
    // do your UART stuff here
    while (Serial.available() > 0)  //enter characters from InputBox of Serial Monitor and then click Send button
    {
      char x = Serial.read();
      Serial.print(x);
    }
  }
  // do the rest
  digitalWrite(13, !digitalRead(13));
}

Go Up