You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.8 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. #include <stdbool.h>
  2. #include <stdint.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "main.h"
  6. #include "usart.h"
  7. #define READ_CMD 0x80
  8. #define SPI_TIMEOUT_VALUE 1000
  9. #define SPI_CS_1() HAL_GPIO_WritePin(SPI_SEL_GPIO_Port, SPI_SEL_Pin, GPIO_PIN_SET) /* */
  10. #define SPI_CS_0() HAL_GPIO_WritePin(SPI_SEL_GPIO_Port, SPI_SEL_Pin, GPIO_PIN_RESET) /* */
  11. #define SPI_SCK_1() HAL_GPIO_WritePin(CLK_GPIO_Port, CLK_Pin, GPIO_PIN_SET) /* SCK = 1 */
  12. #define SPI_SCK_0() HAL_GPIO_WritePin(CLK_GPIO_Port, CLK_Pin, GPIO_PIN_RESET) /* SCK = 0 */
  13. #define SPI_MOSI_1() HAL_GPIO_WritePin(MOSI_GPIO_Port, MOSI_Pin, GPIO_PIN_SET) /* MOSI = 1 */
  14. #define SPI_MOSI_0() HAL_GPIO_WritePin(MOSI_GPIO_Port, MOSI_Pin, GPIO_PIN_RESET) /* MOSI = 0 */
  15. #define SPI_READ_MISO() GPIO_ReadInputDataBit(MISO_GPIO_Port, MISO_Pin) /* 读MISO口线状态 */
  16. #define Dummy_Byte 0xFF // 读取时MISO发送的数据,可以为任意数据
  17. // SPI可以同时读取和写入数据,因此一个函数即可满足要求
  18. uint8_t SPI_ReadWriteByte(uint8_t txData)
  19. {
  20. uint8_t i;
  21. uint8_t rxData = 0;
  22. for (i = 0; i < 8; i++)
  23. {
  24. SPI_SCK_0();
  25. delay_us(1);
  26. // 数据发送
  27. if (txData & 0x80)
  28. {
  29. SPI_MOSI_1();
  30. }
  31. else
  32. {
  33. SPI_MOSI_0();
  34. }
  35. txData <<= 1;
  36. delay_us(1);
  37. SPI_SCK_1();
  38. delay_us(1);
  39. // 数据接收
  40. rxData <<= 1;
  41. if (SPI_READ_MISO())
  42. {
  43. rxData |= 0x01;
  44. }
  45. delay_us(1);
  46. }
  47. SPI_SCK_0();
  48. return rxData;
  49. }
  50. // uint8_t SPI_ReadByte(void)
  51. // {
  52. // return SPI_ReadWriteByte(Dummy_Byte);
  53. // }
  54. // void SPI_WriteByte(uint8_t txData)
  55. // {
  56. // (void)SPI_ReadWriteByte(txData);
  57. // }
  58. void user_main()
  59. {
  60. uint8_t temp;
  61. SPI_CS_Disable();
  62. while (1)
  63. {
  64. // HAL_UART_Transmit(&huart1, &temp, 1, 100);
  65. HAL_Delay(100);
  66. }
  67. }