zongqiang.zhang | 0c6a088 | 2019-08-07 14:48:21 +0800 | [diff] [blame^] | 1 | #include "spi.h" |
| 2 | |
| 3 | static void spi_gpio_init(void) |
| 4 | { |
| 5 | GPIO_InitTypeDef GPIO_InitStructure; |
| 6 | |
| 7 | RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE); |
| 8 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15|GPIO_Pin_13; |
| 9 | GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; |
| 10 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; |
| 11 | GPIO_Init(GPIOB, &GPIO_InitStructure); |
| 12 | |
| 13 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; |
| 14 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; |
| 15 | GPIO_Init(GPIOB, &GPIO_InitStructure); |
| 16 | } |
| 17 | |
| 18 | static void spi_cs_init(void) |
| 19 | { |
| 20 | GPIO_InitTypeDef GPIO_InitStructure; |
| 21 | |
| 22 | RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC|RCC_APB2Periph_GPIOA, ENABLE); |
| 23 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; |
| 24 | GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; |
| 25 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; |
| 26 | GPIO_Init(GPIOB, &GPIO_InitStructure); |
| 27 | |
| 28 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; |
| 29 | GPIO_Init(GPIOC, &GPIO_InitStructure); |
| 30 | |
| 31 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; |
| 32 | GPIO_Init(GPIOA, &GPIO_InitStructure); |
| 33 | |
| 34 | GPIO_SetBits(GPIOB, GPIO_Pin_12); |
| 35 | GPIO_SetBits(GPIOC, GPIO_Pin_7); |
| 36 | GPIO_SetBits(GPIOA, GPIO_Pin_8); |
| 37 | } |
| 38 | |
| 39 | void spi_init(void) |
| 40 | { |
| 41 | SPI_InitTypeDef SPI_InitStructure; |
| 42 | |
| 43 | spi_cs_init(); |
| 44 | spi_gpio_init(); |
| 45 | |
| 46 | RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); |
| 47 | SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; |
| 48 | SPI_InitStructure.SPI_Mode = SPI_Mode_Master; |
| 49 | SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; |
| 50 | SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; |
| 51 | SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; |
| 52 | SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; |
| 53 | SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16; |
| 54 | SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; |
| 55 | SPI_InitStructure.SPI_CRCPolynomial = 7; |
| 56 | SPI_Init(SPI2, &SPI_InitStructure); |
| 57 | |
| 58 | SPI_Cmd(SPI2, ENABLE); |
| 59 | } |
| 60 | |
| 61 | //transmit/receive |
| 62 | uint8_t spi_transive(uint8_t byte, uint32_t timeout) |
| 63 | { |
| 64 | uint32_t timer; |
| 65 | |
| 66 | timer = timeout; |
| 67 | while((SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET)&&timer) |
| 68 | { |
| 69 | timer --; |
| 70 | } |
| 71 | SPI_I2S_SendData(SPI2, byte); |
| 72 | |
| 73 | timer = timeout; |
| 74 | while((SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET)&&timer) |
| 75 | { |
| 76 | timer --; |
| 77 | } |
| 78 | return SPI_I2S_ReceiveData(SPI2); |
| 79 | } |