Browse Source

spi_setup(): add bps paramter

Signed-off-by: surenyi <surenyi82@163.com>
master
surenyi 5 years ago
parent
commit
1c6daa003a
  1. BIN
      docs/stm32f4x.pdf
  2. 47
      lib/spi.c
  3. 2
      lib/spi.h

BIN
docs/stm32f4x.pdf

Binary file not shown.

47
lib/spi.c

@ -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;

2
lib/spi.h

@ -16,7 +16,7 @@ typedef struct spi_descr *spi_t;
#define SPI_CS_LOW (0)
#define SPI_CS_HIGH (1)
int spi_setup(spi_t, uint32_t cs, int mode);
int spi_setup(spi_t, uint32_t cs, int mode, int bps);
void spi_close(spi_t spi);
void spi_set_mode(spi_t, int mode);

Loading…
Cancel
Save