STM32CubeMX:UART操作
阿新 • • 發佈:2019-01-06
UART共有三種操作方式,輪詢方式、中斷方式以及DMA方式。
晶片:STM32F103C8T6
應用管腳:
輸出:PA0、PA1
USART1
配置介面
新增中斷配置
新增DMA配置
程式碼應用
1.實現printf函式
/* USER CODE BEGIN 0 */ #ifdef __GNUC__ /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf set to 'Yes') calls __io_putchar() */ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #endif /* __GNUC__ */ /* USER CODE END 0 */
/* USER CODE BEGIN 4 */ /** * @brief Retargets the C library printf function to the USART. * @param None * @retval None */ PUTCHAR_PROTOTYPE { /* Place your implementation of fputc here */ /* e.g. write a character to the USART1 and Loop until the end of transmission */ HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF); return ch; } /* USER CODE END 4 */
2.輪詢方式傳送與接收
傳送資料
</pre><pre name="code" class="cpp">uint8_t senddata[20]="This use Transmit.\r\n";
if(HAL_UART_Transmit(&huart1,senddata,sizeof(senddata),0xFFFF) != HAL_OK)
{
/* Transfer error in reception process */
Error_Handler();
}
輪詢接收採用阻塞式超時接收模式
3.中斷方式傳送與接收uint8_t huart1_RxBuffer[20]; HAL_UART_Receive(&huart1, huart1_RxBuffer, 20,0x10);
增加接收中斷回撥函式
/* USER CODE BEGIN 4 */
/**
* @brief Rx Transfer completed callbacks.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart==&huart1)
{
Rx_flag=1;
HAL_GPIO_WritePin(GPIOA,GPIO_PIN_0,(GPIO_PinState)!HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0));
// if(HAL_UART_Receive_IT(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK)
// {
// /* Transfer error in reception process */
// Error_Handler();
// }
}
}
/* USER CODE END 4 */
傳送資料
uint8_t senddata_IT[23]="This use Transmit IT.\r\n";
if(HAL_UART_Transmit_IT(&huart1,senddata_IT, sizeof(senddata_IT)) != HAL_OK)
{
/* Transfer error in reception process */
Error_Handler();
}
接收資料,呼叫此函式後,接收中斷可執行一次。
<pre name="code" class="cpp">uint8_t huart1_RxBuffer[20];
if(HAL_UART_Transmit_DMA(&huart1,senddata_DMA, sizeof(senddata_DMA))!= HAL_OK)
{
Error_Handler();
}
if(HAL_UART_Receive_IT(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK) {/* Transfer error in reception process */ Error_Handler(); } 3.DMA方式傳送與接收
增加接收中斷回撥函式(與中斷方式相同)
傳送資料
uint8_t senddata_DMA[24]="This use Transmit DMA.\r\n";
if(HAL_UART_Receive_DMA(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK)
{
/* Transfer error in reception process */
Error_Handler();
}
接收資料(特徵與中斷方式相同)
if(HAL_UART_Receive_DMA(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK)
{
/* Transfer error in reception process */
Error_Handler();
}