parent
a190948dbc
commit
21b191cfb2
@ -0,0 +1,45 @@
|
|||||||
|
#include <avr/io.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
|
||||||
|
#include <spi.h>
|
||||||
|
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define SPI_BAUDRATE 1000000
|
||||||
|
#define SPI_MASTER 1
|
||||||
Loading…
Reference in new issue