]> git.gir.st - tmk_keyboard.git/blob - keyboard/onekey/vusb_osccal.c
onekey: Add settings for Xtal-less V-USB
[tmk_keyboard.git] / keyboard / onekey / vusb_osccal.c
1 // V-USB with ATtiny45 / ATtiny85 without a crystal
2 // http://codeandlife.com/2012/02/22/v-usb-with-attiny45-attiny85-without-a-crystal/
3 #include <avr/io.h>
4 #include <usbdrv.h>
5
6
7 #define abs(x) ((x) > 0 ? (x) : (-x))
8
9 // Called by V-USB after device reset
10 void hadUsbReset() {
11 int frameLength, targetLength = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
12 int bestDeviation = 9999;
13 uint8_t trialCal, bestCal, step, region;
14
15 // do a binary search in regions 0-127 and 128-255 to get optimum OSCCAL
16 for(region = 0; region <= 1; region++) {
17 frameLength = 0;
18 trialCal = (region == 0) ? 0 : 128;
19
20 for(step = 64; step > 0; step >>= 1) {
21 if(frameLength < targetLength) // true for initial iteration
22 trialCal += step; // frequency too low
23 else
24 trialCal -= step; // frequency too high
25
26 OSCCAL = trialCal;
27 frameLength = usbMeasureFrameLength();
28
29 if(abs(frameLength-targetLength) < bestDeviation) {
30 bestCal = trialCal; // new optimum found
31 bestDeviation = abs(frameLength -targetLength);
32 }
33 }
34 }
35
36 OSCCAL = bestCal;
37 }
Imprint / Impressum