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.

95 lines
2.2 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
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
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. #include "tim.h"
  8. #define READ_CMD 0x80
  9. #define SPI_TIMEOUT_VALUE 1000
  10. #define SPI_CS_1() HAL_GPIO_WritePin(SPI_SEL_GPIO_Port, SPI_SEL_Pin, GPIO_PIN_SET) /* */
  11. #define SPI_CS_0() HAL_GPIO_WritePin(SPI_SEL_GPIO_Port, SPI_SEL_Pin, GPIO_PIN_RESET) /* */
  12. #define SPI_SCK_1() HAL_GPIO_WritePin(CLK_GPIO_Port, CLK_Pin, GPIO_PIN_SET) /* SCK = 1 */
  13. #define SPI_SCK_0() HAL_GPIO_WritePin(CLK_GPIO_Port, CLK_Pin, GPIO_PIN_RESET) /* SCK = 0 */
  14. #define SPI_MOSI_1() HAL_GPIO_WritePin(MOSI_GPIO_Port, MOSI_Pin, GPIO_PIN_SET) /* MOSI = 1 */
  15. #define SPI_MOSI_0() HAL_GPIO_WritePin(MOSI_GPIO_Port, MOSI_Pin, GPIO_PIN_RESET) /* MOSI = 0 */
  16. #define SPI_READ_MISO() HAL_GPIO_ReadPin(MISO_GPIO_Port, MISO_Pin) /* 读MISO口线状态 */
  17. #define Dummy_Byte 0xFF // 读取时MISO发送的数据,可以为任意数据
  18. void sys_delay_us(uint32_t us)
  19. {
  20. uint16_t counter = 0;
  21. __HAL_TIM_SET_COUNTER(&htim7, 0);
  22. HAL_TIM_Base_Start(&htim7);
  23. while (counter < us)
  24. {
  25. counter = __HAL_TIM_GET_COUNTER(&htim7);
  26. }
  27. HAL_TIM_Base_Stop(&htim7);
  28. }
  29. // SPI可以同时读取和写入数据,因此一个函数即可满足要求
  30. uint8_t SPI_ReadWriteByte(uint8_t txData)
  31. {
  32. uint8_t i;
  33. uint8_t rxData = 0;
  34. SPI_CS_0();
  35. // for (i = 0; i < 8; i++)
  36. // {
  37. // SPI_SCK_0();
  38. // sys_delay_us(1);
  39. // // 数据发送
  40. // if (txData & 0x80)
  41. // {
  42. // SPI_MOSI_1();
  43. // }
  44. // else
  45. // {
  46. // SPI_MOSI_0();
  47. // }
  48. // txData <<= 1;
  49. // sys_delay_us(1);
  50. // SPI_SCK_1();
  51. // sys_delay_us(1);
  52. // // 数据接收
  53. // rxData <<= 1;
  54. // if (SPI_READ_MISO())
  55. // {
  56. // rxData |= 0x01;
  57. // }
  58. // sys_delay_us(1);
  59. // }
  60. // SPI_SCK_0();
  61. SPI_CS_1();
  62. return rxData;
  63. }
  64. uint8_t SPI_ReadByte(void)
  65. {
  66. return SPI_ReadWriteByte(Dummy_Byte);
  67. }
  68. void SPI_WriteByte(uint8_t txData)
  69. {
  70. (void)SPI_ReadWriteByte(txData);
  71. }
  72. void user_main()
  73. {
  74. uint8_t temp;
  75. SPI_CS_1();
  76. while (1)
  77. {
  78. temp = SPI_ReadWriteByte(0x86);
  79. HAL_UART_Transmit(&huart1, &temp, 1, 100);
  80. HAL_Delay(100);
  81. }
  82. }