spi.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <string.h>
  2. #include "spi.h"
  3. /*
  4. * spi driver for MS5238 and CS1180
  5. */
  6. void spi0_init(void){
  7. rcu_periph_clock_enable(RCU_GPIOA);
  8. rcu_periph_clock_enable(RCU_GPIOB);
  9. rcu_periph_clock_enable(RCU_SPI0);
  10. //spi clk
  11. gpio_mode_output(GPIOB, GPIO_PUPD_NONE, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_3);
  12. //spi MISO
  13. gpio_mode_input(GPIOB, GPIO_PUPD_NONE, GPIO_PIN_4);
  14. //spi MOSI
  15. gpio_mode_output(GPIOB, GPIO_PUPD_NONE, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_5);
  16. gpio_af_set(GPIOB, GPIO_AF_0, GPIO_PIN_3);
  17. gpio_af_set(GPIOB, GPIO_AF_0, GPIO_PIN_4);
  18. gpio_af_set(GPIOB, GPIO_AF_0, GPIO_PIN_5);
  19. //MS5238 cs
  20. gpio_mode_output(GPIOA, GPIO_PUPD_NONE, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_15);
  21. ms5238_cs(1);
  22. //CS1180 cs
  23. gpio_mode_output(GPIOA, GPIO_PUPD_NONE, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
  24. cs1180_cs(1);
  25. spi_parameter_struct spi_init_struct;
  26. /* SPI0 parameter config */
  27. spi_init_struct.trans_mode = SPI_TRANSMODE_FULLDUPLEX;
  28. spi_init_struct.device_mode = SPI_MASTER;;
  29. spi_init_struct.frame_size = SPI_FRAMESIZE_16BIT;
  30. spi_init_struct.clock_polarity_phase = SPI_CK_PL_LOW_PH_1EDGE;
  31. spi_init_struct.nss = SPI_NSS_SOFT;
  32. spi_init_struct.prescale = SPI_PSC_2 ;
  33. spi_init_struct.endian = SPI_ENDIAN_MSB;
  34. spi_init(SPI0, &spi_init_struct);
  35. /* set crc polynomial */
  36. spi_crc_polynomial_set(SPI0,7);
  37. /* enable SPI0 */
  38. spi_enable(SPI0);
  39. }
  40. void spi0_deinit(void){
  41. spi_disable(SPI0);
  42. rcu_periph_clock_disable(RCU_SPI0);
  43. }
  44. #define max_wait_count 1024
  45. int spi0_send_uint16(uint16_t s_data, uint8_t *r_data)
  46. {
  47. /* loop while data register in not emplty */
  48. int count = 0;
  49. while (RESET == spi_i2s_flag_get(SPI0,SPI_FLAG_TBE) && count < max_wait_count){
  50. count ++;
  51. };
  52. if (RESET == spi_i2s_flag_get(SPI0,SPI_FLAG_TBE)){
  53. return -1;
  54. }
  55. /* send byte through the SPI0 peripheral */
  56. spi_i2s_data_transmit(SPI0,s_data);
  57. /* wait to receive a byte */
  58. count = 0;
  59. while(RESET == spi_i2s_flag_get(SPI0,SPI_FLAG_RBNE) && count < max_wait_count){
  60. count ++;
  61. };
  62. if (RESET == spi_i2s_flag_get(SPI0,SPI_FLAG_RBNE)){
  63. return -1;
  64. }
  65. /* return the byte read from the SPI bus */
  66. uint8_t r = spi_i2s_data_receive(SPI0);
  67. if (r_data != NULL){
  68. *r_data = r;
  69. }
  70. return 0;
  71. }