[STM32L4] STM32 HAL库怎么使用SPI的发送和接收函数?

[复制链接]
7713|3
 楼主| dianhang 发表于 2017-4-22 21:40 | 显示全部楼层 |阅读模式
请讲讲怎么使用HAL_SPI_Transmit()​;HAL_SPI_Receive();HAL_SPI_TransmitReceive()​;发送和接收一个Byte吗?​
用的CUBEMX生成的SPI3的配置
void MX_SPI3_Init(void)
{

  hspi3.Instance = SPI3;
  hspi3.Init.Mode = SPI_MODE_MASTER;
  hspi3.Init.Direction = SPI_DIRECTION_2LINES;
  hspi3.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi3.Init.NSS = SPI_NSS_SOFT;
  hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
  hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi3.Init.CRCPolynomial = 7;
  hspi3.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
  hspi3.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
  if (HAL_SPI_Init(&hspi3) != HAL_OK)
  {
    Error_Handler();
  }

}

我下面这样写对吗?

void SPI_WriteByte(uint8_t TxData)
{         
    HAL_SPI_Transmit(&hspi3,&TxData,1,0xffff);
}
uint8_t SPI_ReadByte(uint8_t RxData)
{         
    HAL_SPI_Receive(&hspi3,RxData, 1, 0xffff);
}

xixi2017 发表于 2017-4-22 21:55 | 显示全部楼层
楼主,你没有发现那个包里面还有例程吗
xixi2017 发表于 2017-4-22 21:58 | 显示全部楼层
  1. /**
  2.   ******************************************************************************
  3.   * [url=home.php?mod=space&uid=288409]@file[/url]    SPI/SPI_FullDuplex_AdvComPolling/Master/Src/main.c
  4.   * [url=home.php?mod=space&uid=187600]@author[/url]  MCD Application Team
  5.   * [url=home.php?mod=space&uid=895143]@version[/url] V1.2.6
  6.   * [url=home.php?mod=space&uid=212281]@date[/url]    06-May-2016
  7.   * [url=home.php?mod=space&uid=247401]@brief[/url]   This sample code shows how to use STM32F4xx SPI HAL API to transmit
  8.   *          and receive a data buffer with a communication process based on
  9.   *          Polling transfer.
  10.   *          The communication is done using 2 boards.
  11.   ******************************************************************************
  12.   * @attention
  13.   *
  14.   * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
  15.   *
  16.   * Redistribution and use in source and binary forms, with or without modification,
  17.   * are permitted provided that the following conditions are met:
  18.   *   1. Redistributions of source code must retain the above copyright notice,
  19.   *      this list of conditions and the following disclaimer.
  20.   *   2. Redistributions in binary form must reproduce the above copyright notice,
  21.   *      this list of conditions and the following disclaimer in the documentation
  22.   *      and/or other materials provided with the distribution.
  23.   *   3. Neither the name of STMicroelectronics nor the names of its contributors
  24.   *      may be used to endorse or promote products derived from this software
  25.   *      without specific prior written permission.
  26.   *
  27.   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  28.   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  29.   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  30.   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  31.   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  32.   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  33.   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  34.   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  35.   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  36.   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37.   *
  38.   ******************************************************************************
  39.   */

  40. /* Includes ------------------------------------------------------------------*/
  41. #include "main.h"

  42. /** @addtogroup STM32F4xx_HAL_Examples
  43.   * @{
  44.   */

  45. /** @addtogroup SPI_FullDuplex_AdvComPolling
  46.   * @{
  47.   */

  48. /** @addtogroup Master
  49.   * @{
  50.   */

  51. /* Private typedef -----------------------------------------------------------*/
  52. /* Private define ------------------------------------------------------------*/
  53. #define SPI_ACK_BYTES             0xA5A5
  54. #define SPI_NACK_BYTES            0xDEAD
  55. #define SPI_TIMEOUT_MAX           0x1000
  56. #define SPI_SLAVE_SYNBYTE         0x53
  57. #define SPI_MASTER_SYNBYTE        0xAC

  58. /* Defines used for transfer communication */
  59. #define ADDRCMD_MASTER_READ                         ((uint16_t)0x1234)
  60. #define ADDRCMD_MASTER_WRITE                        ((uint16_t)0x5678)
  61. #define CMD_LENGTH                                  ((uint16_t)0x0004)
  62. #define DATA_LENGTH                                 ((uint16_t)0x0020)         
  63. /* Private macro -------------------------------------------------------------*/
  64. /* Private variables ---------------------------------------------------------*/
  65. /* SPI handler declaration */
  66. SPI_HandleTypeDef SpiHandle;
  67. FlagStatus TestReady = RESET;

  68. /* Buffer used for transmission */
  69. uint8_t aTxMasterBuffer[] = "SPI - MASTER - Transmit message";
  70. uint8_t aTxSlaveBuffer[]  = "SPI - SLAVE - Transmit message ";
  71. /* Buffer used for reception */
  72. uint8_t aRxBuffer[DATA_LENGTH];

  73. /* Private function prototypes -----------------------------------------------*/
  74. static void Master_Synchro(void);
  75. static void SystemClock_Config(void);
  76. static void Error_Handler(void);
  77. static uint16_t Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength);
  78. static void Flush_Buffer(uint8_t* pBuffer, uint16_t BufferLength);
  79. /* Private functions ---------------------------------------------------------*/

  80. /**
  81.   * @brief  Main program
  82.   * @param  None
  83.   * @retval None
  84.   */
  85. int main(void)
  86. {
  87.   uint8_t addrcmd[CMD_LENGTH] = {0};
  88.   uint16_t ackbytes = 0x0000;

  89.   /* STM32F4xx HAL library initialization:
  90.        - Configure the Flash prefetch, instruction and Data caches
  91.        - Configure the Systick to generate an interrupt each 1 msec
  92.        - Set NVIC Group Priority to 4
  93.        - Global MSP (MCU Support Package) initialization
  94.      */
  95.   HAL_Init();
  96.   
  97.   /* Configure the system clock to 168 MHz */
  98.   SystemClock_Config();
  99.   
  100.   /* Configure LED3, LED4, LED5 and LED6 */
  101.   BSP_LED_Init(LED3);
  102.   BSP_LED_Init(LED4);
  103.   BSP_LED_Init(LED5);
  104.   BSP_LED_Init(LED6);
  105.   
  106.   /*##-1- Configure the SPI peripheral #######################################*/
  107.   /* Set the SPI parameters */
  108.   SpiHandle.Instance               = SPIx;
  109.   SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
  110.   SpiHandle.Init.Direction         = SPI_DIRECTION_2LINES;
  111.   SpiHandle.Init.CLKPhase          = SPI_PHASE_2EDGE;
  112.   SpiHandle.Init.CLKPolarity       = SPI_POLARITY_LOW;
  113.   SpiHandle.Init.CRCCalculation    = SPI_CRCCALCULATION_DISABLE;
  114.   SpiHandle.Init.CRCPolynomial     = 7;
  115.   SpiHandle.Init.DataSize          = SPI_DATASIZE_8BIT;
  116.   SpiHandle.Init.FirstBit          = SPI_FIRSTBIT_MSB;
  117.   SpiHandle.Init.NSS               = SPI_NSS_SOFT;
  118.   SpiHandle.Init.TIMode            = SPI_TIMODE_DISABLE;
  119.   SpiHandle.Init.Mode = SPI_MODE_MASTER;
  120.   
  121.   if(HAL_SPI_Init(&SpiHandle) != HAL_OK)
  122.   {
  123.     /* Initialization Error */
  124.     Error_Handler();
  125.   }
  126.   
  127.   /* Configure USER Button */
  128.   BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  129.   
  130.   /* Wait for user Button press before starting the communication. Toggles LED3 until then */
  131.   while (TestReady != SET)
  132.   {
  133.     BSP_LED_Toggle(LED3);
  134.     HAL_Delay(40);
  135.   }
  136.   BSP_LED_Off(LED3);
  137.   
  138.   /* Infinite loop */  
  139.   while(1)
  140.   {
  141.     /* Synchronization between Master and Slave */
  142.     Master_Synchro();
  143.    
  144.     /* Receive Data from the Slave ###########################################*/
  145.     addrcmd[0] = (uint8_t) (ADDRCMD_MASTER_READ >> 8);
  146.     addrcmd[1] = (uint8_t) ADDRCMD_MASTER_READ;
  147.     addrcmd[2] = (uint8_t) (DATA_LENGTH >> 8);
  148.     addrcmd[3] = (uint8_t) DATA_LENGTH;
  149.     /* Send Master READ command to slave */
  150.     if(HAL_SPI_Transmit(&SpiHandle, addrcmd, CMD_LENGTH, SPI_TIMEOUT_MAX) != HAL_OK)
  151.     {
  152.       Error_Handler();
  153.     }
  154.     /* Synchronization between Master and Slave */
  155.     Master_Synchro();
  156.    
  157.     /* Receive ACK from the Slave */
  158.     ackbytes = 0;
  159.     if(HAL_SPI_Receive(&SpiHandle, (uint8_t *)&ackbytes, sizeof(ackbytes), SPI_TIMEOUT_MAX) != HAL_OK)
  160.     {
  161.       Error_Handler();
  162.     }
  163.     /* Check the received ACK */
  164.     if(ackbytes == SPI_ACK_BYTES)
  165.     {
  166.       /* Synchronization between Master and Slave */
  167.       Master_Synchro();
  168.       
  169.       /* Receive the requested data from the slave */
  170.       if(HAL_SPI_Receive(&SpiHandle, aRxBuffer, DATA_LENGTH, SPI_TIMEOUT_MAX) != HAL_OK)
  171.       {
  172.         Error_Handler();
  173.       }
  174.       /* Synchronization between Master and Slave */
  175.       Master_Synchro();
  176.       
  177.       /* Send ACK to the Slave */
  178.       ackbytes = SPI_ACK_BYTES;
  179.       if(HAL_SPI_Transmit(&SpiHandle, (uint8_t *)&ackbytes, sizeof(ackbytes), SPI_TIMEOUT_MAX) != HAL_OK)
  180.       {
  181.         Error_Handler();
  182.       }
  183.     }   
  184.     else
  185.     {
  186.       /* Transfer error in transmission process */
  187.       Error_Handler();
  188.     }
  189.    
  190.     /* Compare received buffer with one expected from slave */
  191.     if(Buffercmp((uint8_t*)aTxSlaveBuffer, (uint8_t*)aRxBuffer, CMD_LENGTH))
  192.     {
  193.       /* Transfer error in transmission process */
  194.       Error_Handler();
  195.     }
  196.     else
  197.     {
  198.       /* Turn LED6 on: Reception is correct */
  199.       BSP_LED_Toggle(LED6);
  200.     }

  201.     /* Synchronization between Master and Slave */
  202.     Master_Synchro();
  203.    
  204.     /* Transmit Data To Slave ################################################*/
  205.     addrcmd[0] = (uint8_t) (ADDRCMD_MASTER_WRITE >> 8);
  206.     addrcmd[1] = (uint8_t) ADDRCMD_MASTER_WRITE;
  207.     addrcmd[2] = (uint8_t) (DATA_LENGTH >> 8);
  208.     addrcmd[3] = (uint8_t) DATA_LENGTH;
  209.     /* Send Master WRITE command to the slave */
  210.     if(HAL_SPI_Transmit(&SpiHandle, addrcmd, CMD_LENGTH, SPI_TIMEOUT_MAX) != HAL_OK)
  211.     {
  212.       Error_Handler();
  213.     }
  214.     /* Synchronization between Master and Slave */
  215.     Master_Synchro();
  216.    
  217.     /* Receive ACK from the Slave */
  218.     ackbytes = 0;
  219.     if(HAL_SPI_Receive(&SpiHandle, (uint8_t *)&ackbytes, sizeof(ackbytes), SPI_TIMEOUT_MAX) != HAL_OK)
  220.     {
  221.       Error_Handler();
  222.     }
  223.     /* Check the received ACK */
  224.     if(ackbytes == SPI_ACK_BYTES)
  225.     {
  226.       /* Synchronization between Master and Slave */
  227.       Master_Synchro();
  228.       /* Send the requested data from the slave */
  229.       if(HAL_SPI_Transmit(&SpiHandle, aTxMasterBuffer, DATA_LENGTH, SPI_TIMEOUT_MAX) != HAL_OK)
  230.       {
  231.         Error_Handler();
  232.       }
  233.       /* Synchronization between Master and Slave */
  234.       Master_Synchro();
  235.       
  236.       /* Receive ACK from the Slave */
  237.       ackbytes = 0;
  238.       if(HAL_SPI_Receive(&SpiHandle, (uint8_t *)&ackbytes, sizeof(ackbytes), SPI_TIMEOUT_MAX) != HAL_OK)
  239.       {
  240.         Error_Handler();
  241.       }
  242.     }   
  243.     else
  244.     {
  245.       /* Transfer error in transmission process */
  246.       Error_Handler();
  247.     }
  248.    
  249.     /* Flush Rx buffer for next transmission */
  250.     Flush_Buffer(aRxBuffer, DATA_LENGTH);
  251.    
  252.     /* Toggle LED4 */
  253.     BSP_LED_Toggle(LED4);
  254.     /* This delay permit to user to see LED4 toggling*/
  255.     HAL_Delay(100);
  256.   }
  257. }

  258. /**
  259.   * @brief  EXTI line detection callbacks.
  260.   * @param  GPIO_Pin: Specifies the pins connected EXTI line
  261.   * @retval None
  262.   */
  263. void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
  264. {
  265. if(KEY_BUTTON_PIN == GPIO_Pin)
  266. {
  267.    TestReady = SET;
  268. }
  269. }

  270. /**
  271.   * @brief  Master Synchronization with Slave.
  272.   * @param  None
  273.   * @retval None
  274.   */
  275. static void Master_Synchro(void)
  276. {
  277.   uint8_t txackbytes = SPI_MASTER_SYNBYTE, rxackbytes = 0x00;
  278.   do
  279.   {
  280.     /* Call SPI write function to send command to slave */
  281.     if(HAL_SPI_TransmitReceive(&SpiHandle, (uint8_t *)&txackbytes, (uint8_t *)&rxackbytes, 1, HAL_MAX_DELAY) != HAL_OK)
  282.     {
  283.       Error_Handler();
  284.     }
  285.   }while(rxackbytes != SPI_SLAVE_SYNBYTE);
  286. }

  287. /**
  288.   * @brief  System Clock Configuration
  289.   *         The system Clock is configured as follow :
  290.   *            System Clock source            = PLL (HSE)
  291.   *            SYSCLK(Hz)                     = 168000000
  292.   *            HCLK(Hz)                       = 168000000
  293.   *            AHB Prescaler                  = 1
  294.   *            APB1 Prescaler                 = 4
  295.   *            APB2 Prescaler                 = 2
  296.   *            HSE Frequency(Hz)              = 8000000
  297.   *            PLL_M                          = 8
  298.   *            PLL_N                          = 336
  299.   *            PLL_P                          = 2
  300.   *            PLL_Q                          = 7
  301.   *            VDD(V)                         = 3.3
  302.   *            Main regulator output voltage  = Scale1 mode
  303.   *            Flash Latency(WS)              = 5
  304.   * @param  None
  305.   * @retval None
  306.    */
  307. static void SystemClock_Config(void)
  308. {
  309.   RCC_ClkInitTypeDef RCC_ClkInitStruct;
  310.   RCC_OscInitTypeDef RCC_OscInitStruct;

  311.   /* Enable Power Control clock */
  312.   __HAL_RCC_PWR_CLK_ENABLE();
  313.   
  314.   /* The voltage scaling allows optimizing the power consumption when the device is
  315.      clocked below the maximum system frequency, to update the voltage scaling value
  316.      regarding system frequency refer to product datasheet.  */
  317.   __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  318.   
  319.   /* Enable HSE Oscillator and activate PLL with HSE as source */
  320.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  321.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  322.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  323.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  324.   RCC_OscInitStruct.PLL.PLLM = 8;
  325.   RCC_OscInitStruct.PLL.PLLN = 336;
  326.   RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  327.   RCC_OscInitStruct.PLL.PLLQ = 7;
  328.   HAL_RCC_OscConfig(&RCC_OscInitStruct);
  329.   
  330.   /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
  331.      clocks dividers */
  332.   RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  333.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  334.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  335.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;  
  336.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;  
  337.   HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5);

  338.   /* STM32F405x/407x/415x/417x Revision Z devices: prefetch is supported  */
  339.   if (HAL_GetREVID() == 0x1001)
  340.   {
  341.     /* Enable the Flash prefetch */
  342.     __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
  343.   }
  344. }

  345. /**
  346.   * @brief  This function is executed in case of error occurrence.
  347.   * @param  None
  348.   * @retval None
  349.   */
  350. static void Error_Handler(void)
  351. {
  352.   /* Turn LED5 on */
  353.   BSP_LED_On(LED5);
  354.   while(1)
  355.   {
  356.   }
  357. }

  358. /**
  359.   * @brief  Compares two buffers.
  360.   * @param  pBuffer1, pBuffer2: buffers to be compared.
  361.   * @param  BufferLength: buffer's length
  362.   * @retval 0  : pBuffer1 identical to pBuffer2
  363.   *         >0 : pBuffer1 differs from pBuffer2
  364.   */
  365. static uint16_t Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength)
  366. {
  367.   while (BufferLength--)
  368.   {
  369.     if((*pBuffer1) != *pBuffer2)
  370.     {
  371.       return BufferLength;
  372.     }
  373.     pBuffer1++;
  374.     pBuffer2++;
  375.   }

  376.   return 0;
  377. }

  378. /**
  379.   * @brief  Flushes the buffer
  380.   * @param  pBuffer: buffers to be flushed.
  381.   * @param  BufferLength: buffer's length
  382.   * @retval None
  383.   */
  384. static void Flush_Buffer(uint8_t* pBuffer, uint16_t BufferLength)
  385. {
  386.   while (BufferLength--)
  387.   {
  388.     *pBuffer = 0;

  389.     pBuffer++;
  390.   }
  391. }

  392. #ifdef  USE_FULL_ASSERT

  393. /**
  394.   * @brief  Reports the name of the source file and the source line number
  395.   *         where the assert_param error has occurred.
  396.   * @param  file: pointer to the source file name
  397.   * @param  line: assert_param error line source number
  398.   * @retval None
  399.   */
  400. void assert_failed(uint8_t* file, uint32_t line)
  401. {
  402.   /* User can add his own implementation to report the file name and line number,
  403.      ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  404.   /* Infinite loop */
  405.   while (1)
  406.   {
  407.   }
  408. }
  409. #endif

  410. /**
  411.   * @}
  412.   */

  413. /**
  414.   * @}
  415.   */

  416. /**
  417.   * @}
  418.   */

  419. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
cos12a 发表于 2017-5-25 10:50 | 显示全部楼层
样办在哪呀,怎么没有找到?
您需要登录后才可以回帖 登录 | 注册

本版积分规则

37

主题

273

帖子

3

粉丝
快速回复 在线客服 返回列表 返回顶部