stm32cubemx hal学习记录:USART发送+接收

一、配置过程

1、配置RCC、SYS、时钟84MHz

2、添加LED灯PF9、PF10输出模式

3、配置USART1为异步模式,打开中断

4、生成代码

5、配置microLIB,如果要使用printf,则必须要开启

stm32cubemx hal学习记录:USART发送+接收_第1张图片

二、代码编写

1、在main中重写printf和getchar函数

int fputc(int ch,FILE *f)
{
	HAL_UART_Transmit(&huart1,(uint8_t *)&ch,1,0xffff);
	return ch;
}

int fgetc(FILE *f)
{
	uint8_t ch=0;
	HAL_UART_Receive(&huart1,&ch,1,0xffff);
	return ch;
}

2、串口发送

usart.c

uint8_t Serial_TxPacket[]={0x08,0x02,0x04,0x05};;
uint8_t Serial_RxPacket[4];
uint8_t Serial_RxFlag;

//发送一个字节
void Serial_SendByte(uint8_t Byte)
{
	HAL_UART_Transmit(&huart1,&Byte,1,0xffff);
}

//发送数组
void Serial_SendArray(uint8_t *Array)
{
	uint16_t Length;
	
	Length=sizeof(Array)/sizeof(Array[0]);
	
	for(uint16_t i=0;i

main.c

Serial_SendPacket();

编译烧入之后按下复位,发送FE FF 08 02 04 05 FE 

3、串口接收数据

main

uint8_t RxData;
uint8_t i;


HAL_UART_Receive_IT(&huart1,&RxData,1);


while (1)
{
    if (Serial_GetRxFlag() == 1)
	{
		i++;
	}
}

usart.c

extern uint8_t RxData;
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	static uint8_t RxState = 0;
	static uint8_t pRxPacket = 0;
	if (huart->Instance==USART1)
	{
		HAL_UART_Receive_IT(&huart1,&RxData,1);
		
		if (RxState == 0)  //等待包头
		{
			if (RxData == 0xFF)
			{
				RxState = 1;
				pRxPacket = 0;
			}
		}
		else if (RxState == 1)   //接收数据
		{
			Serial_RxPacket[pRxPacket] = RxData;
			pRxPacket ++;
			if (pRxPacket >= 4)  	 //接收4字节的数据
			{
				RxState = 2;
			}
		}
		else if (RxState == 2)   //等待包尾
		{
			if (RxData == 0xFE)
			{
				RxState = 0;
				Serial_RxFlag = 1;
			}
		}
		
	}	
}

你可能感兴趣的:(stm32,stm32,单片机,学习)