add timer_counter module
This commit is contained in:
43
src/timer_counter.c
Normal file
43
src/timer_counter.c
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
#include <avr/io.h>
|
||||||
|
#include <avr/interrupt.h>
|
||||||
|
#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;
|
||||||
|
}
|
||||||
4
src/timer_counter.h
Normal file
4
src/timer_counter.h
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
void timer0_init(void);
|
||||||
|
uint16_t ticks100us(void);
|
||||||
Reference in New Issue
Block a user