1.HAL库中断方式进行串口通信
1.创建工程
1.1引脚配置
1.2配置RCC
1.3配置SYS
1.4配置USART1
1.5配置时钟
2.编写代码
2.1添加初始化和声明
/* USER CODE BEGIN PV */
#define LENGTH 4 //接受缓冲区大小
uint8_t RxBuffer[LENGTH]; //接受缓冲区
uint8_t RxFlag = 0; //接收完成标志;0表示接受未完成,1表示接收完成
/* USER CODE END PV */
2.2在int main( )
中while
外添加代码
/* USER CODE BEGIN WHILE */
//发送提示信息
HAL_UART_Transmit(&huart1,(uint8_t *)"****UART commucition using IT****\n",34,HAL_MAX_DELAY);
HAL_UART_Transmit(&huart1,(uint8_t *)"Please enter 4 characters: \n",30,HAL_MAX_DELAY);
//使能接收中断
HAL_UART_Receive_IT(&huart1, (uint8_t *)RxBuffer,LENGTH);
2.3在while
中添加代码
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
//添加下面代码
HAL_UART_Transmit(&huart1, (uint8_t *)"hello windows!\r\n", 16 , HAL_MAX_DELAY);
HAL_Delay(1000); //延时1s
if(RxFlag == 1) //如果接受完成,不在发送数据
{
HAL_UART_Transmit(&huart1,(uint8_t *)"Recevie Success!\n",17,HAL_MAX_DELAY); //提示接受成功
break; //退出循环,不在发送数据
}
}
3,结果
2.基于HAL库实现DMA串口通信
1.创建工程
1.1配置RCC
1.2配置SYS
1.3配置USART1
1.4配置时钟
2.编写代码
2.1添加代码
#include <string.h>
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#define RX_BUFFER_SIZE 64
/* UART reception buffer */
uint8_t rxBuffer[RX_BUFFER_SIZE];
uint8_t rxData = 0;
uint8_t txData[] = "Hello Windows!\r\n";
uint8_t sending = 1;
/* USER CODE END Includes */
2.2在while
中添加代码
/* USER CODE BEGIN WHILE */
HAL_UART_Receive_IT(&huart1, &rxData, 1); // Start UART reception
while (1) {
if (sending) {
// Send data using DMA
HAL_UART_Transmit_DMA(&huart1, txData, strlen((char *)txData));
// You can also add a delay here if needed
HAL_Delay(1000);
}
}
/* USER CODE END 3 */
2.3重写中断处理函数
/* USER CODE BEGIN 0 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
if (huart == &huart1) {
// Process received data here
// For example, check if "stop" or "start" was received
if (strncmp((char *)rxBuffer, "stop", 4) == 0) {
sending = 0; // Stop sending
} else if (strncmp((char *)rxBuffer, "start", 5) == 0) {
sending = 1; // Start sending
}
// Clear the buffer
memset(rxBuffer, 0, sizeof(rxBuffer));
// Restart reception
HAL_UART_Receive_IT(&huart1, &rxData, 1);
}
}
/* USER CODE END 0 */
3,结果
3.串口输出波形
由图可知时序状态正确,波特率实际为0.98325Hz