Last active
September 2, 2020 08:14
-
-
Save ArminJo/bf624af6c9642dc90a30ad3ff5a67350 to your computer and use it in GitHub Desktop.
Arduino millis() disable, enable and compensation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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