Skip to content

Instantly share code, notes, and snippets.

@dagon666
Created September 30, 2013 20:19
Show Gist options
  • Save dagon666/6769590 to your computer and use it in GitHub Desktop.
Save dagon666/6769590 to your computer and use it in GitHub Desktop.
prescaler calculation atmega328p
// system clock frequency
#define F_CPU 16000000UL
void timer_freq_prescale(uint32_t a_freq, uint8_t *a_ocr, uint8_t *a_prescaler) {
// prescaler table for timer 0
uint8_t prescalers[] = { 0x00, 0x03, 0x06, 0x08, 0x0a, 0x00 };
uint16_t ocr = 0x00;
uint8_t prescaler = 0x00;
do {
ocr = (uint16_t) (F_CPU / ((a_freq << 1) * (0x01 << prescalers[prescaler])));
++prescaler;
} while ((ocr > 255) && (prescalers[prescaler]));
--ocr;
if (ocr > 255) ocr = 255;
*a_ocr = ocr & 0xff;
*a_prescaler = prescaler;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment