|
|
@ -16,14 +16,29 @@ struct spi_descr { |
|
|
|
void (*setup)(struct spi_descr *); |
|
|
|
}; |
|
|
|
|
|
|
|
int spi_setup(spi_t spi, uint32_t cs, int mode) |
|
|
|
/* query APB1 clocks */ |
|
|
|
static uint32_t __PCLK1() |
|
|
|
{ |
|
|
|
RCC_ClocksTypeDef clks; |
|
|
|
|
|
|
|
RCC_GetClocksFreq(&clks); |
|
|
|
|
|
|
|
return clks.PCLK1_Frequency; |
|
|
|
} |
|
|
|
|
|
|
|
int spi_setup(spi_t spi, uint32_t cs, int mode, int bps) |
|
|
|
{ |
|
|
|
uint32_t clk; |
|
|
|
uint16_t prescale = SPI_BaudRatePrescaler_4; |
|
|
|
|
|
|
|
if (spi->setup) |
|
|
|
spi->setup(spi); |
|
|
|
|
|
|
|
spi->cs = cs; |
|
|
|
gpio_init(spi->cs, GPIO_OUTPUT | GPIO_FLAG_PD | GPIO_FLAG_PU | GPIO_SPEED_FAST); |
|
|
|
gpio_set(spi->cs); |
|
|
|
if (cs > 0) { |
|
|
|
gpio_init(spi->cs, GPIO_OUTPUT | GPIO_FLAG_PD | GPIO_FLAG_PU | GPIO_SPEED_FAST); |
|
|
|
gpio_set(spi->cs); |
|
|
|
} |
|
|
|
|
|
|
|
switch (spi->apb) { |
|
|
|
case 1: |
|
|
@ -36,9 +51,33 @@ int spi_setup(spi_t spi, uint32_t cs, int mode) |
|
|
|
|
|
|
|
SPI_DeInit(spi->base); |
|
|
|
|
|
|
|
|
|
|
|
SPI_StructInit(&spi->conf); |
|
|
|
spi->conf.SPI_Mode = SPI_Mode_Master; |
|
|
|
spi->conf.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4; |
|
|
|
|
|
|
|
if (bps > 0) { |
|
|
|
clk = __PCLK1(); |
|
|
|
|
|
|
|
if (bps >= (clk / 2)) { |
|
|
|
prescale = SPI_BaudRatePrescaler_2; |
|
|
|
} else if ((bps >= (clk / 4)) && (bps < (clk / 2))) { |
|
|
|
prescale = SPI_BaudRatePrescaler_4; |
|
|
|
} else if ((bps >= (clk / 8)) && (bps < (clk / 4))) { |
|
|
|
prescale = SPI_BaudRatePrescaler_8; |
|
|
|
} else if ((bps >= (clk / 16)) && (bps < (clk / 8))) { |
|
|
|
prescale = SPI_BaudRatePrescaler_16; |
|
|
|
} else if ((bps >= (clk / 32)) && (bps < (clk / 16))) { |
|
|
|
prescale = SPI_BaudRatePrescaler_32; |
|
|
|
} else if ((bps >= (clk / 64)) && (bps < (clk / 32))) { |
|
|
|
prescale = SPI_BaudRatePrescaler_64; |
|
|
|
} else if ((bps >= (clk / 128)) && (bps < (clk / 64))) { |
|
|
|
prescale = SPI_BaudRatePrescaler_128; |
|
|
|
} else if (bps < (clk / 128)) { |
|
|
|
prescale = SPI_BaudRatePrescaler_256; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
spi->conf.SPI_BaudRatePrescaler = prescale; |
|
|
|
|
|
|
|
if (mode & 0x1) { |
|
|
|
spi->conf.SPI_CPHA = SPI_CPHA_2Edge; |
|
|
|