目录
串口设置的一般步骤
1) 串口时钟使能,GPIO 时钟使能
2) 串口复位
3) GPIO 端口模式设置
4) 串口参数初始化
5) 开启中断并且初始化 NVIC(如果需要开启中断才需要这个步骤)
6) 使能串口
7) 编写中断处理函数
8)串口数据收发
9)串口传输状态获取
串口初始化函数
void uart_init(u32 bound){
GPIO_InitTypeDef GPIO_InitStructure; //定义结构体变量
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //使能IO口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //
GPIO_Init(GPIOA, &GPIO_InitStructure);//
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//
GPIO_Init(GPIOA, &GPIO_InitStructure);//
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //
NVIC_Init(&NVIC_InitStructure); //
USART_InitStructure.USART_BaudRate = bound;//
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //打开接收中断
USART_Cmd(USART1, ENABLE); //串口使能
}
串口中断函数
void USART1_IRQHandler(void)
{
u8 Res;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) // 接收中断
{
Res =USART_ReceiveData(USART1); //读取数据
if((USART_RX_STA&0x8000)==0) //接收没完成,没接收到0x0a
{
if(USART_RX_STA&0x4000) //接受到了0x0d
{
if(Res!=0x0a)USART_RX_STA=0; //没接收到0x0a,数据接收错误,重新接受
}
else //没接受到0x0d
{
if(Res==0x0d)USART_RX_STA|=0x4000; //这次接受到了0x0d
else //没接收到0x0d
{
USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ; //存数
USART_RX_STA++; //计数加1
if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0; //超出范围
}
}
}
}
main.c
int main(void)
{
u8 t;
u8 len;
u16 times=0;
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
uart_init(9600);
LED_Init();
while(1)
{
if(USART_RX_STA&0x8000) //接收完成
{
len=USART_RX_STA&0x3fff; //数长
printf("\r\n您发送的消息为:\r\n");
for(t=0;t<len;t++) //接收数据
{
USART_SendData(USART1,USART_RX_BUF[t]);
while((USART1->SR&0X40)==0); //发送完成
}
printf("\r\n\r\n");
USART_RX_STA=0;
}else
{
times++;
if(times%5000==0)
{
printf("\r\nALIENTEK MiniSTM32开发板 串口实验\r\n");
printf("正点原子@ALIENTEK\r\n\r\n\r\n");
}
if(times%200==0)printf("请输入数据,以回车结束\r\n");
if(times%30==0)LED0=!LED0;
delay_ms(10);
}
}
}