开发平台:MDK
开发板:正点原子STM32精英
实现功能:利用串口发送与接收数据。
1、原理图:
2、连接方式:
3、代码:
初始化:
g_uart1_handle.Instance = USART_UX;
g_uart1_handle.Init.BaudRate = baudrate;
g_uart1_handle.Init.WordLength = UART_WORDLENGTH_8B;
g_uart1_handle.Init.StopBits = UART_STOPBITS_1;
g_uart1_handle.Init.Parity = UART_PARITY_NONE;
g_uart1_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
g_uart1_handle.Init.Mode = UART_MODE_TX_RX;
HAL_UART_Init(&g_uart1_handle);
HAL_UART_Receive_IT(&g_uart1_handle, (uint8_t *)g_rx_buffer, RXBUFFERSIZE);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART_UX)
{
if ((g_usart_rx_sta & 0x8000) == 0)
{
if (g_usart_rx_sta & 0x4000)
{
if (g_rx_buffer[0] != 0x0a)
{
g_usart_rx_sta = 0;
}
else
{
g_usart_rx_sta |= 0x8000;
}
}
else
{
if (g_rx_buffer[0] == 0x0d)
g_usart_rx_sta |= 0x4000;
else
{
g_usart_rx_buf[g_usart_rx_sta & 0X3FFF] = g_rx_buffer[0];
g_usart_rx_sta++;
if (g_usart_rx_sta > (USART_REC_LEN - 1))
{
g_usart_rx_sta = 0;
}
}
}
}
}
printf("请输入数据\r\n");
len = g_usart_rx_sta & 0x3fff;
printf("\\r\\n发送的数据:\\r\\n");
HAL_UART_Transmit(&g_uart1_handle,(uint8_t*)g_usart_rx_buf, len, 1000);
while(__HAL_UART_GET_FLAG(&g_uart1_handle,UART_FLAG_TC) != SET);
printf("\\r\\n\\r\\n");
g_usart_rx_sta = 0;
4、串口打印出结果
|