#include "stm32f10x.h" #include "stdio.h" static GPIO_InitTypeDef GPIO_InitStructure; static NVIC_InitTypeDef NVIC_InitStructure; static USART_InitTypeDef USART_InitStructure; #define PB5OUT(n) *(volatile uint32_t *)(0x42000000+((uint32_t)&GPIOB->ODR-0x40000000)*32+n*4) //串口初始化 void led0(void){ //led0-->PB5 //使能端口 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //初始化GPIO引脚 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed= GPIO_Speed_50MHz;//高速响应 GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_SetBits(GPIOB,GPIO_Pin_5); } void usart1_init(uint32_t baud){ //串口PA9 ,PA10 //硬件时钟时钟打开 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能串口1的时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); //tx配置引脚的工作模式 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //设置成复用功能 GPIO_InitStructure.GPIO_Speed= GPIO_Speed_50MHz;//高速响应 GPIO_Init(GPIOA, &GPIO_InitStructure); //USART1_RX GPIOA.10初始化 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入 GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.10 //配置串口 USART_InitStructure.USART_BaudRate = baud;//设置波特率 USART_InitStructure.USART_WordLength = USART_WordLength_8b;//8位数据位 USART_InitStructure.USART_StopBits = USART_StopBits_1;//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); //配置中断优先级 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); //使能串口1 USART_Cmd(USART1, ENABLE); } void USART1_IRQHandler(void){ uint16_t xiao; //检测标志位 if(USART_GetITStatus(USART1, USART_IT_RXNE)==SET) { //接收数据 xiao=USART_ReceiveData(USART1); //将接收到的数据,返发给pc USART_SendData(USART1,xiao); while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); //控制灯 if(xiao=='1') PB5OUT(5)=0; if(xiao=='0') PB5OUT(5)=1; //清空标志位 USART_ClearITPendingBit(USART1,USART_IT_RXNE ); } } int main(){ led0(); usart1_init(115200); USART_SendData(USART1,'A'); while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); USART_SendData(USART1,'B'); while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); USART_SendData(USART1,'C'); while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); while(1){ } }
微信扫码关注
更新实时通知