Skip to content

Instantly share code, notes, and snippets.

@dagon666
Created September 30, 2013 20:23
Show Gist options
  • Save dagon666/6769655 to your computer and use it in GitHub Desktop.
Save dagon666/6769655 to your computer and use it in GitHub Desktop.
calculating prescaler and ocr values offline
#include <stdio.h>
#include <stdint.h>
// 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;
}
int main(int argc, char const *argv[])
{
uint32_t freq = 0;
uint8_t prescaler = 0;
uint8_t ocr = 0;
uint16_t prescalers[] = { 0x00, 0x00, 0x03, 0x06, 0x08, 0x0a, 0x00 };
if (argc == 1) {
fprintf(stderr, "pocr <frequency>\n");
return -1;
}
freq = atoi(argv[1]);
timer_freq_prescale(freq, &ocr, &prescaler);
printf("Frequency: [%d Hz], Prescaler: [%4d], OCR: [%3d]\n",
freq, (0x01 << prescalers[prescaler]), ocr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment