| #include "spi.h" |
| |
| static void spi_gpio_init(void) |
| { |
| GPIO_InitTypeDef GPIO_InitStructure; |
| |
| RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE); |
| GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15|GPIO_Pin_13; |
| GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; |
| GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; |
| GPIO_Init(GPIOB, &GPIO_InitStructure); |
| |
| GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; |
| GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; |
| GPIO_Init(GPIOB, &GPIO_InitStructure); |
| } |
| |
| static void spi_cs_init(void) |
| { |
| GPIO_InitTypeDef GPIO_InitStructure; |
| |
| RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC|RCC_APB2Periph_GPIOA, ENABLE); |
| GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; |
| GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; |
| GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; |
| GPIO_Init(GPIOB, &GPIO_InitStructure); |
| |
| GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; |
| GPIO_Init(GPIOC, &GPIO_InitStructure); |
| |
| GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; |
| GPIO_Init(GPIOA, &GPIO_InitStructure); |
| |
| GPIO_SetBits(GPIOB, GPIO_Pin_12); |
| GPIO_SetBits(GPIOC, GPIO_Pin_7); |
| GPIO_SetBits(GPIOA, GPIO_Pin_8); |
| } |
| |
| void spi_init(void) |
| { |
| SPI_InitTypeDef SPI_InitStructure; |
| |
| spi_cs_init(); |
| spi_gpio_init(); |
| |
| RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); |
| SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; |
| SPI_InitStructure.SPI_Mode = SPI_Mode_Master; |
| SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; |
| SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; |
| SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; |
| SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; |
| SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16; |
| SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; |
| SPI_InitStructure.SPI_CRCPolynomial = 7; |
| SPI_Init(SPI2, &SPI_InitStructure); |
| |
| SPI_Cmd(SPI2, ENABLE); |
| } |
| |
| //transmit/receive |
| uint8_t spi_transive(uint8_t byte, uint32_t timeout) |
| { |
| uint32_t timer; |
| |
| timer = timeout; |
| while((SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET)&&timer) |
| { |
| timer --; |
| } |
| SPI_I2S_SendData(SPI2, byte); |
| |
| timer = timeout; |
| while((SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET)&&timer) |
| { |
| timer --; |
| } |
| return SPI_I2S_ReceiveData(SPI2); |
| } |