Skip to content

Instantly share code, notes, and snippets.

@Sulter
Last active August 29, 2015 14:02
Show Gist options
  • Save Sulter/f2f0274c0edce228bdc4 to your computer and use it in GitHub Desktop.
Save Sulter/f2f0274c0edce228bdc4 to your computer and use it in GitHub Desktop.
msec counter for avr.
/*
Calculated for 20MHz:
(((1sec/20000000) * 8 )* 250 )* 10 =0.001sec
freq presc ticks multiplayer 1msec
so at freq 20mhz, we need to prescale with 8, count to 249, and then multiple by 10 to get 1msec out of the counter.
This needs some calculations for each different frequency.
Adjust prescalar and ticks until you get the "multiplayer" to be an integer!
*/
//the counter
volatile unsigned long milCounter = 0;
ISR(TIMER0_COMPA_vect){
milCounter++;
}
void initMillis(void){
//start timer
TCCR0A = (1<<WGM01); //set to compare (CTC)
TCCR0B = (1<<CS01); //8prescalar
OCR0A = 249; //ticks
//enable interrupt on compare
TIMSK0 = (1<<OCIE0A);
sei();
}
unsigned long millis(void){
unsigned long millis;
unsigned char sreg_backup = SREG;
cli();
millis = milCounter;
SREG = sreg_backup;
return millis/10;//returns 1msec, by dividing by multip
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment