#include #include #include #include void spi_init(){ uint8_t spcr, spsr, d; /* calculate clock divisor, * gcc with optimize will do that calculation compile-time. */ uint8_t spi_clock_divisor(){ double d; d = F_CPU / SPI_BAUDRATE; d = ceil((log(d)/log(2))*0.95); // clock needs dividing by 2^d // the 0.95 to avoid ceil issues return d-1; // the -1 because minimum divisor is /2 } d = spi_clock_divisor(); if(d>7){ #warning "spi baudrate too slow, cannot be set" d=7; } spsr = 0; spsr |= (d & 1) ? 0 : _BV(SPI2X); spcr = 0 | _BV(SPIE) | _BV(SPE); spcr |= (d & 2) ? _BV(SPR0) : 0; spcr |= (d & 4) ? _BV(SPR1) : 0; #ifdef SPI_MASTER spcr |= _BV(MSTR); #endif SPCR = spcr; SPSR = spsr; }