From 0b8d0f11f6ee89dabfefaa3768e9d4ecbab1be25 Mon Sep 17 00:00:00 2001 From: bartool Date: Thu, 29 May 2025 18:53:41 +0200 Subject: [PATCH] add timer_counter module --- src/timer_counter.c | 43 +++++++++++++++++++++++++++++++++++++++++++ src/timer_counter.h | 4 ++++ 2 files changed, 47 insertions(+) create mode 100644 src/timer_counter.c create mode 100644 src/timer_counter.h diff --git a/src/timer_counter.c b/src/timer_counter.c new file mode 100644 index 0000000..ef302cc --- /dev/null +++ b/src/timer_counter.c @@ -0,0 +1,43 @@ +#include +#include +#include "timer_counter.h" + +volatile uint16_t counter = 0; + +void timer0_init(void) +{ + // Mode CTC: WGM01 = 1, WGM00 = 0 + TCCR0A = (1 << WGM01); + + // Prescaler 64: CS01 = 1, CS00 = 1 (CS02 = 0) + // TCCR0B = (1 << CS01) | (1 << CS00); + // Prescaler 8: CS01 = 1, (CS00 = 0, CS02 = 0) + TCCR0B = (1 << CS01); + + // Setting OCR0A to 124 gives 1 ms with 8 MHz and prescaler of 64 + // OCR0A = 124; + // Setting OCR0A to 99 gives 100 us with 8 MHz and prescaler of 8 + OCR0A = 99; + + // Enable Timer/Counter0 Output Compare Match A interrupt + TIMSK0 = (1 << OCIE0A); +} + +ISR(TIM0_COMPA_vect) +{ + counter++; +} + +uint16_t ticks100us(void) +{ + uint16_t value1, value2; + + // Double-checked locking to ensure atomic read of counter + do + { + value1 = counter; + value2 = counter; + } while (value1 != value2); + + return value1; +} \ No newline at end of file diff --git a/src/timer_counter.h b/src/timer_counter.h new file mode 100644 index 0000000..c5e5c9e --- /dev/null +++ b/src/timer_counter.h @@ -0,0 +1,4 @@ +#pragma once + +void timer0_init(void); +uint16_t ticks100us(void); \ No newline at end of file