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.

89 lines
2.0 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
  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() GPIO_ReadInputDataBit(MISO_GPIO_Port, MISO_Pin) /* 读MISO口线状态 */
  17. #define Dummy_Byte 0xFF // 读取时MISO发送的数据,可以为任意数据
  18. void sys_sys_delay_us(uint32_t us) {
  19. uint16_t counter = 0;
  20. __HAL_TIM_SET_COUNTER(&htim7, 0);
  21. HAL_TIM_Base_Start(&htim7);
  22. while (counter < us) {
  23. counter = __HAL_TIM_GET_COUNTER(&htim7);
  24. }
  25. HAL_TIM_Base_Stop(&htim7);
  26. }
  27. // SPI可以同时读取和写入数据,因此一个函数即可满足要求
  28. uint8_t SPI_ReadWriteByte(uint8_t txData)
  29. {
  30. uint8_t i;
  31. uint8_t rxData = 0;
  32. for (i = 0; i < 8; i++)
  33. {
  34. SPI_SCK_0();
  35. sys_delay_us(1);
  36. // 数据发送
  37. if (txData & 0x80)
  38. {
  39. SPI_MOSI_1();
  40. }
  41. else
  42. {
  43. SPI_MOSI_0();
  44. }
  45. txData <<= 1;
  46. sys_delay_us(1);
  47. SPI_SCK_1();
  48. sys_delay_us(1);
  49. // 数据接收
  50. rxData <<= 1;
  51. if (SPI_READ_MISO())
  52. {
  53. rxData |= 0x01;
  54. }
  55. sys_delay_us(1);
  56. }
  57. SPI_SCK_0();
  58. return rxData;
  59. }
  60. // uint8_t SPI_ReadByte(void)
  61. // {
  62. // return SPI_ReadWriteByte(Dummy_Byte);
  63. // }
  64. // void SPI_WriteByte(uint8_t txData)
  65. // {
  66. // (void)SPI_ReadWriteByte(txData);
  67. // }
  68. void user_main()
  69. {
  70. uint8_t temp;
  71. SPI_CS_Disable();
  72. while (1)
  73. {
  74. // HAL_UART_Transmit(&huart1, &temp, 1, 100);
  75. HAL_Delay(100);
  76. }
  77. }