Answer the question
In order to leave comments, you need to log in
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; // сброс
}
}
}
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
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
It's possible that mainTimer is involved somewhere else, and therefore it shouldn't be reset.
Perhaps they copy the code without looking.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question