S
S
Svyatoslav Nemato2019-09-17 22:11:13
Arduino
Svyatoslav Nemato, 2019-09-17 22:11:13

Reset counter ARDUINO?

I often see code like this on the Internet:

void loop() {
  mainTimer++;

  if (!state) {                          
    if ((long)mainTimer - myTimer > PERIOD) {   // таймер периода
      myTimer = mainTimer;                // сброс таймера
    }
  } else {                                
    if ((long)mainTimer - myTimer > WORK) {     // таймер времени работы
      myTimer = mainTimer;                // сброс
    }
  }

}

Why write like that, why is the classic bad?
void loop() {
  mainTimer++;

  if (!state) {                           
    if ((long)mainTimer > PERIOD) {             // таймер периода
      mainTimer = 0;                      // сброс таймера
    }
  } else {                               
    if ((long)mainTimer > WORK) {               // таймер времени работы
      mainTimer = 0;                      // сброс
    }
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
evgeniy_lm, 2019-09-18
@evgeniy_lm

In loop, only a very pot-bellied teapot will count intervals in this way. In this case, there will be no accuracy. Alas, the Arduino entry threshold is almost zero (as it was originally intended), so almost all the Arduino code is the most terrible shit code (including both of your examples).
As already mentioned, advanced dummies use millis() (or micros()). Then the code will look like this.
void loop() {
if (!state) {
if (millis() - myTimer > PERIOD) { // period timer
myTimer = millis(); // reset the timer
}
} else {
if (millis() - myTimer > WORK) { // work timer
myTimer = millis(); // reset
}
}
}
Here you can be sure of +-2ms accuracy for millis() or +-50µs for micros()
Programmers use timers to count intervals. In this case, more accurate and complex measurements can be made. Just keep in mind that all timers are used by the analogWrite() function, timer 0 is also used by millis() and micros(). With other timer settings, these functions will not be available.
For a very accurate reading of large intervals, use the RTC, it is built into the Mega2560, for others you need an external

T
TriKrista, 2019-09-17
@TriKrista

It's possible that mainTimer is involved somewhere else, and therefore it shouldn't be reset.
Perhaps they copy the code without looking.

K
kalapanga, 2019-09-17
@kalapanga

It is unlikely that you actually often saw exactly "this is the code." The arduino uses the millis() (or micros()) function to count time intervals. See the BlinkWithoutDelay example from the standard Arduino IDE for usage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question