Skip to content

Instantly share code, notes, and snippets.

@ArminJo
Last active September 2, 2020 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArminJo/bf624af6c9642dc90a30ad3ff5a67350 to your computer and use it in GitHub Desktop.
Save ArminJo/bf624af6c9642dc90a30ad3ff5a67350 to your computer and use it in GitHub Desktop.
Arduino millis() disable, enable and compensation
#include <Arduino.h>
// See: https://github.com/ArminJo/Arduino-Utils/blob/master/src/MillisUtils.cpp
/*
* storage for millis value to enable compensation for interrupt disable at signal acquisition etc.
*/
#if ( defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) )
#define timer0_millis millis_timer_millis // The ATTinyCore libraries use other variable name in wiring.c
#endif
#if defined(TIMSK) && !defined(TIMSK0) // some ATtinys
#define TIMSK0 TIMSK
#endif
extern volatile unsigned long timer0_millis; // ATmega328P
...
/*
* disable Timer0 (millis()) overflow interrupt
* since the loop last exactly a multiple of 1024 micros, add a few statements between disabling and enabling
*/
void disableMillisInterrupt() {
_SFR_BYTE(TIMSK0) &= ~_BV(TOIE0);
}
/*
* enable timer 0 overflow interrupt and compensate for disabled timer, if still disabled.
*/
void enableMillisInterrupt(uint16_t aMillisToAddForCompensation) {
if ((TIMSK0 & _BV(TOIE0)) == 0) {
// still disabled -> compensate
timer0_millis += aMillisToAddForCompensation;
}
_SFR_BYTE(TIMSK0) |= _BV(TOIE0);
}
void delayMilliseconds(unsigned int aMillis) {
for (unsigned int i = 0; i < aMillis; ++i) {
delayMicroseconds(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment