diff --git a/avr/cores/tiny/Arduino.h b/avr/cores/tiny/Arduino.h index c6c0891..8d1a62a 100644 --- a/avr/cores/tiny/Arduino.h +++ b/avr/cores/tiny/Arduino.h @@ -78,7 +78,7 @@ void yield(void); #define interrupts() sei() #define noInterrupts() cli() -#define PRESCALER 4 +#define PRESCALER 1 #define CLK_PER F_CPU / PRESCALER // default prescaler 6, datasheet Page 78, MCLKCCTRLB to Change prescalar diff --git a/avr/cores/tiny/wiring.c b/avr/cores/tiny/wiring.c index 8b4147c..08a3c6d 100644 --- a/avr/cores/tiny/wiring.c +++ b/avr/cores/tiny/wiring.c @@ -3,15 +3,17 @@ #define TIMER0_TOP_VALUE 0xFF -#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * TIMER0_TOP_VALUE)) +#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 256)) #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000) -#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3) -#define FRACT_MAX (1000 >> 3) +#define FRACT_INC 8 // calculated base on 12.8 microseoncds per time0 overflow // 256 / 20 +#define FRACT_MAX 625 + +//#define MICROSECONDS_PER_TIMER0_OVERFLOW 12.8 // 256 / 20 volatile unsigned long timer0_overflow_count = 0; volatile unsigned long timer0_millis = 0; -static unsigned char timer0_fract = 0; +static unsigned int timer0_fract = 0; static void __empty() { // Empty @@ -21,7 +23,7 @@ void yield(void) __attribute__ ((weak, alias("__empty"))); ISR(TCA0_LUNF_vect) { unsigned long m = timer0_millis; - unsigned char f = timer0_fract; + unsigned int f = timer0_fract; m += MILLIS_INC; f += FRACT_INC; @@ -82,13 +84,32 @@ void delay(unsigned long ms) void delayMicroseconds(unsigned int us) { + + + // __asm__ __volatile__ ( + // "nop" "\n\t" + // "nop" "\n\t" + // "nop" "\n\t" + // "nop"); //just waiting 4 cycles + if (us <= 1) return; // = 3 cycles, (4 when true) + + // the following loop takes a 1/5 of a microsecond (4 cycles) + // per iteration, so execute it five times for each microsecond of + // delay requested. + us += (us << 1); // x5 us, = 7 cycles + + // account for the time taken in the preceeding commands. + // we just burned 26 (28) cycles above, remove 7, (7*4=28) + // us is at least 10 so we can substract 7 + us -= 7; // 2 cycles + // F_CPU = 5Mhz - if (us <= 10) return; + // if (us <= 10) return; - us += us >> 3; // us * 1.125 + // us += us >> 3; // us * 1.125 - us >>= 1; // div / 2 + // us >>= 1; // div / 2 __asm__ __volatile__ ( "1: sbiw %0,1" "\n\t" // 2 cycles @@ -100,9 +121,9 @@ void init(void) { CCP = CCP_IOREG_gc; // enable write protect - CLKCTRL_MCLKCTRLB = (1 << CLKCTRL_PDIV0_bp) | (1 << CLKCTRL_PEN_bp); // change prescalar to 4, so it's 20Mhz/4 = 5MHz + //CLKCTRL_MCLKCTRLB = (1 << CLKCTRL_PDIV0_bp) | (1 << CLKCTRL_PEN_bp); // change prescalar to 4, so it's 20Mhz/4 = 5MHz - //CLKCTRL_MCLKCTRLB = 0x00; + CLKCTRL_MCLKCTRLB = 0x00; SREG |= (1 << CPU_I_bp); // global enable interrupt