1.串口配置过程 使能时钟(GPIO口以及串口)->初始化GPIO口->打开中断->初始化中断->编写服务函数
int main(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); usart1init(); while(1) { } } void usart1init(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitTypeDef g; g.GPIO_Pin = GPIO_Pin_9; g.GPIO_Speed = GPIO_Speed_50MHz; g.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &g); g.GPIO_Pin = GPIO_Pin_10; g.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &g); USART_InitTypeDef u; u.USART_BaudRate=115200; u.USART_HardwareFlowControl=USART_HardwareFlowControl_None; u.USART_Mode=USART_Mode_Rx|USART_Mode_Tx; u.USART_Parity=USART_Parity_No; u.USART_StopBits=USART_StopBits_1; u.USART_WordLength=USART_WordLength_8b; USART_Init(USART1, &u); USART_Cmd(USART1,ENABLE); USART_ITConfig(USART1, USART_IT_RXNE,ENABLE); NVIC_InitTypeDef n; n.NVIC_IRQChannel=USART1_IRQn; n.NVIC_IRQChannelCmd=ENABLE; n.NVIC_IRQChannelPreemptionPriority=0; n.NVIC_IRQChannelSubPriority=0; NVIC_Init(&n); } void USART1_IRQHandler(void) { u8 res; if(USART_GetITStatus(USART1,USART_IT_RXNE)!= RESET) { res=USART_ReceiveData(USART1); USART_SendData(USART1,res); USART_ClearITPendingBit(USART1,USART_IT_RXNE); } }
2.串口配置为空闲中断
//注意 1 USART_ITConfig(USART1, USART_IT_RXNE,ENABLE); USART_ITConfig(USART1, USART_IT_IDLE,ENABLE);
另外 注意 IDLE IT Flag不会自动清除
void usart1init(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //ê1?üUSART1£?GPIOAê±?ó GPIO_InitTypeDef g; g.GPIO_Pin = GPIO_Pin_9; g.GPIO_Speed = GPIO_Speed_50MHz; g.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &g); g.GPIO_Pin = GPIO_Pin_10; g.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &g); USART_InitTypeDef u; u.USART_BaudRate=115200; u.USART_HardwareFlowControl=USART_HardwareFlowControl_None; u.USART_Mode=USART_Mode_Rx|USART_Mode_Tx; u.USART_Parity=USART_Parity_No; u.USART_StopBits=USART_StopBits_1; u.USART_WordLength=USART_WordLength_8b; USART_Init(USART1, &u); USART_Cmd(USART1,ENABLE); USART_ITConfig(USART1, USART_IT_RXNE,ENABLE); USART_ITConfig(USART1, USART_IT_IDLE,ENABLE); NVIC_InitTypeDef n; n.NVIC_IRQChannel=USART1_IRQn; n.NVIC_IRQChannelCmd=ENABLE; n.NVIC_IRQChannelPreemptionPriority=0; n.NVIC_IRQChannelSubPriority=0; NVIC_Init(&n); } void USART1_IRQHandler(void) { u8 res; static u8 n=0; static u8 flag_idle=1; if(USART_GetITStatus(USART1,USART_IT_RXNE)!= RESET) { flag_idle=1; if(n<99) { res=USART_ReceiveData(USART1); buff[n]=res; n++; } } if(USART_GetITStatus(USART1,USART_IT_IDLE)!= RESET&&flag_idle==1) { memcpy(data,buff,sizeof buff); memset(buff, 0, sizeof buff); n=0; flag_idle=0; } }
3.搭配DMA使用
4.printf,scanf函数映射到串口如何操作
#include "stm32f10x.h" #include "stdlib.h" #include "stdio.h" #include "stm32f10x_conf.h" int fputc(int c, FILE *stream) { USART1->DR = c; while(!(USART1->SR & (1 << 7))){}; return c; } int fgetc(FILE *stream) { while(!(USART1->SR & (1 << 5))){};//等待数据接收完成 return USART1->DR; }
5.【接近应用】
通过串口远程设置某些参数并存储