1 // V-USB with ATtiny45 / ATtiny85 without a crystal
2 // http://codeandlife.com/2012/02/22/v-usb-with-attiny45-attiny85-without-a-crystal/
7 #define abs(x) ((x) > 0 ? (x) : (-x))
9 // Called by V-USB after device reset
11 int frameLength, targetLength = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
12 int bestDeviation = 9999;
13 uint8_t trialCal, bestCal, step, region;
15 // do a binary search in regions 0-127 and 128-255 to get optimum OSCCAL
16 for(region = 0; region <= 1; region++) {
18 trialCal = (region == 0) ? 0 : 128;
20 for(step = 64; step > 0; step >>= 1) {
21 if(frameLength < targetLength) // true for initial iteration
22 trialCal += step; // frequency too low
24 trialCal -= step; // frequency too high
27 frameLength = usbMeasureFrameLength();
29 if(abs(frameLength-targetLength) < bestDeviation) {
30 bestCal = trialCal; // new optimum found
31 bestDeviation = abs(frameLength -targetLength);