user_spi.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "user_spi.h"
  2. /*******************************************************************************
  3. * @函数名称 SPI_FullDuplex_Init
  4. * @函数说明 SPI初始化
  5. * @输入参数 无
  6. * @输出参数 无
  7. * @返回参数 无
  8. *******************************************************************************/
  9. void user_spi_Init(void)
  10. {
  11. GPIO_InitTypeDef GPIO_InitStructure = {0};
  12. SPI_InitTypeDef SPI_InitStructure = {0};
  13. USER_NFC_SPI_RCC_ENABLE;
  14. GPIO_InitStructure.GPIO_Pin = USER_NFC_SCLK_PIN;
  15. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  16. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  17. GPIO_Init(USER_NFC_SCLK_GPIO, &GPIO_InitStructure);
  18. GPIO_InitStructure.GPIO_Pin = USER_NFC_MISO_PIN;
  19. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  20. GPIO_Init(USER_NFC_MISO_GPIO, &GPIO_InitStructure);
  21. GPIO_InitStructure.GPIO_Pin = USER_NFC_MOSI_PIN;
  22. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  23. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  24. GPIO_Init(USER_NFC_MOSI_GPIO, &GPIO_InitStructure);
  25. SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  26. SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  27. SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
  28. SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  29. SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
  30. SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
  31. SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
  32. SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  33. SPI_InitStructure.SPI_CRCPolynomial = 10;
  34. SPI_Init(USER_NFC_SPI, &SPI_InitStructure);
  35. SPI_Cmd(USER_NFC_SPI, ENABLE);
  36. }
  37. /*******************************************************************************
  38. * Function Name : SPI_ReadWriteByte
  39. * Description : SPI读写字节
  40. * Input : unsigned char TxData 写入字节
  41. * Output : None
  42. * Return : unsigned char RxData 读取字节
  43. Flash_ReadWriteByte
  44. *******************************************************************************/
  45. uint8_t SPI_ReadWriteByte(uint8_t TxData)
  46. {
  47. uint8_t timeout = 0;
  48. uint8_t RxData = 0;
  49. while(SPI_I2S_GetFlagStatus(USER_NFC_SPI, SPI_I2S_FLAG_TXE) == RESET)
  50. {
  51. timeout++;
  52. if(timeout > 200)
  53. {
  54. return 0;
  55. }
  56. }
  57. SPI_I2S_SendData(USER_NFC_SPI, TxData);
  58. timeout = 0;
  59. while(SPI_I2S_GetFlagStatus(USER_NFC_SPI, SPI_I2S_FLAG_RXNE) == RESET)
  60. {
  61. timeout++;
  62. if(timeout > 200)
  63. {
  64. return 0;
  65. }
  66. }
  67. RxData = SPI_I2S_ReceiveData(USER_NFC_SPI);
  68. return (uint8_t)RxData;
  69. }