avr-fw-modules/timer/m8timer2/src/m8timer2.c

37 lines
808 B
C

#include <hwo/utils.h>
#include <avr/io.h>
#include <avr/wdt.h>
#include <sys/systick.h>
uint16_t t0_steps[] = { 0,1,8,32,64,128,256,1024 };
void systick_timer_init(uint32_t systick_us)
{
uint64_t clocks = ((uint64_t)systick_us) * ((uint64_t)__freq_cpu) / 1000000LL;
uint8_t n_prescaler;
for (n_prescaler = 1; n_prescaler < 8 ; n_prescaler++)
{
if ((clocks / t0_steps[ n_prescaler ]) < 256) {
break;
};
};
if (n_prescaler > 7)
return;
TCCR2 = _BV(WGM21);
TCNT2 = 0;
OCR2 = (uint8_t)(clocks / t0_steps[ n_prescaler-1 ]);
TCCR2 |= (n_prescaler & 0x07);
TIMSK |= _BV(OCIE2);
_systick_us = 1000000LL * (t0_steps[ n_prescaler ]<<1) * (OCR2 + 1) / __freq_cpu;
if ((&_st_cycles_per_intervall)!=NULL){
_st_cycles_per_intervall = ((uint32_t)OCR2) * t0_steps[ n_prescaler-1 ];
}
}