Timer: set up a 62.5kHz timer

main
radex 2024-02-14 21:17:41 +01:00
parent 1233d07a1c
commit a4e0a69165
Signed by: radex
SSH Key Fingerprint: SHA256:hvqRXAGG1h89yqnS+cyFTLKQbzjWD4uXIqw7Y+0ws30
1 changed files with 27 additions and 12 deletions

View File

@ -1,16 +1,26 @@
#include <Arduino.h>
#define DEMO_TRIGGER_MS 1500
#define DEMO_TRIGGER_MS 1000
#if F_CPU != 16000000
#error "Unsupported F_CPU"
#endif
void setupTimer() {
// Set up Timer 0 to trigger interrupt every 1ms
// Timer 0 is already used and configured by Arduino for millis()
// however it uses TOIE0 (overflow interrupt), so we'll use OCIE0A:
// When this bit is written to one, and the I-flag in the Status Register is set
// (interrupts globally enabled), the Timer/Counter0 Output Compare A Match interrupt is enabled
// The corresponding Interrupt Vector is executed when the OCF0A Flag, located in TIFR0, is set.
OCR0A = 0xAF; // any number is OK, it will trigger at some point during the counter
TIMSK0 |= _BV(OCIE0A);
noInterrupts();
// reset timer settings
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
// 256 prescaler (16MHz / 256 = 62.5kHz)
TCCR1B |= (1 << CS12);
// CTC mode (Clear Timer on Compare Match)
TCCR1B |= (1 << WGM12);
// interrupt at 62.5kHz / (OCR1A + 1)
OCR1A = 0;
// enable timer
TIMSK1 |= (1 << OCIE1A);
interrupts();
}
// incremented every DEMO_TRIGGER_MS by interrupt,
@ -32,11 +42,16 @@ void demoTimer() {
}
}
volatile uint16_t timerTicks = 0;
volatile uint16_t timerMillis = 0;
// triggers every 1ms
ISR(TIMER0_COMPA_vect) {
timerMillis++;
// triggers at 62.5kHz
ISR(TIMER1_COMPA_vect) {
timerTicks++;
if (timerTicks == 625) {
timerTicks = 0;
timerMillis += 10;
}
if (timerMillis >= DEMO_TRIGGER_MS) {
timerMillis -= DEMO_TRIGGER_MS;
timerEvents++;