spi.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "spi.h"
  2. void SPI2_GPIO_Config(void)
  3. {
  4. GPIO_InitTypeDef GPIO_InitStructure;
  5. /* Enable SPI2 and GPIO clock */
  6. RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
  7. RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
  8. /* Configure SPI2 CS pin */
  9. GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
  10. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  11. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  12. GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  13. GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  14. GPIO_Init(GPIOB, &GPIO_InitStructure);
  15. /* Configure SPI2 pins: SCK, MISO and MOSI */
  16. GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
  17. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  18. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  19. GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  20. GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  21. GPIO_Init(GPIOB, &GPIO_InitStructure);
  22. /* Connect GPIO pins to SPI2 alternate function */
  23. GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_SPI2); // SCK
  24. GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_SPI2); // MISO
  25. GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_SPI2); // MOSI
  26. }
  27. void spi_config(void)
  28. {
  29. SPI2_GPIO_Config();
  30. SPI_InitTypeDef SPI_InitStructure;
  31. /* SPI2 configuration */
  32. SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  33. SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  34. SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
  35. SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  36. SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
  37. SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
  38. SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
  39. SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  40. SPI_InitStructure.SPI_CRCPolynomial = 7;
  41. SPI_Init(SPI2, &SPI_InitStructure);
  42. /* Enable SPI2 */
  43. SPI_Cmd(SPI2, ENABLE);
  44. }
  45. /*-------------------------------------------------*/
  46. /*函数名:SPI收发一个字节 */
  47. /*参 数:txd:要发送的数据 */
  48. /*返回值:接收到的数据 */
  49. /*-------------------------------------------------*/
  50. uint8_t SPI2_ReadWriteByte(uint8_t txd)
  51. {
  52. while(SPI_GetFlagStatus(SPI2,SPI_FLAG_TXE)!=1);
  53. SPI_SendData(SPI2,txd);
  54. while(SPI_GetFlagStatus(SPI2,SPI_FLAG_RXNE)!=1);
  55. return SPI_ReceiveData(SPI2);
  56. }
  57. void SpiNSSEnable( uint8_t status )
  58. {
  59. GPIO_WriteBit( GPIOB, GPIO_Pin_12, (BitAction) status );
  60. }