void USART1_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));//中断执行完成后继续返回正常程序
void USART_Config(void)
{
//PA9->TX PA10->RX
GPIO_InitTypeDef GPIO_InitStructure={0};//定义IO口配置结构体
USART_InitTypeDef USART_InitStructure={0};//定义串口配置结构体
NVIC_InitTypeDef NVIC_InitStructure={0};//定义中断配置结构体
//UART4 APB1 GPIOC->APB2 TX->PC10 RX->PC11
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//开GPIOA的时钟
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//设置PA2为推挽复用输出
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;//设置引脚
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//设置传播速度
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIO
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;//设置PA3为浮空输入
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;//设置引脚
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIO
USART_InitStructure.USART_BaudRate=9600;//设置波特率
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//无硬件流
USART_InitStructure.USART_Mode=USART_Mode_Tx|USART_Mode_Rx;//串口模式收发
USART_InitStructure.USART_Parity=USART_Parity_No;//不使用校验位
USART_InitStructure.USART_StopBits=1;//1位的停止位
USART_InitStructure.USART_WordLength=USART_WordLength_8b;//字节长度
USART_Init(USART1, &USART_InitStructure);//初始化USART2
NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1,ENABLE);//使能串口2
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//使能中断
}
//发送单个字符
void USARTx_SendByte(USART_TypeDef* pUSARTx, uint8_t data)
{
USART_SendData(pUSARTx, data);
while(USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);//检测寄存器是否有数据
}
//发送字符串
void USARTx_SendStr(USART_TypeDef* pUSARTx, char *str)
{
uint8_t i = 0;
do
{
USARTx_SendByte(pUSARTx, *(str+i));
i++;
}while(*(str+i) != '\0');
while(USART_GetFlagStatus(pUSARTx, USART_FLAG_TC) == RESET);//检测是否传输完成
}
int fputc(int ch, FILE *f)
{
USART_SendData(USART1,(uint8_t) ch); //发送数据到串口
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE)==RESET);
return ch;
}
int fgetc(FILE *f)
{
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE)==RESET);
return(int)USART_ReceiveData(USART1);
}
void USART1_IRQHandler(void)
{
uint8_t ucTemp;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //中断产生
{
USART_ClearITPendingBit(USART1,USART_IT_RXNE); //清除中断标志
ucTemp = USART_ReceiveData(USART1); //接收数据
USART_SendData(USART1, ucTemp); //发送数据
}
}
串口打印代码如下