流程
(简单的发送数据)
GPIO时钟使能
串口时钟使能
串口的GPIO配置
写初始化串口函数,配置串口USART_Init(USART1,&USART_InitStruct);
开启(使能)串口USART_Cmd(USART1, ENABLE);
附上代码
void NVIC_Config_USART()
{
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(& NVIC_InitStruct);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
}
void Init_UART()
{
GPIO_InitTypeDef GPIOInitstruct;
USART_InitTypeDef USART_InitStruct;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA,ENABLE); //开启串口对应的GPIO时钟
RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1,ENABLE);//开启串口1的时钟 :Tx-A9 RX-A10,开
GPIOInitstruct.GPIO_Mode = GPIO_Mode_AF_PP; //设置串口GPIO模式(有两个)
GPIOInitstruct.GPIO_Pin = GPIO_Pin_9;
GPIOInitstruct.GPIO_Speed = GPIO_Speed_50MHz; //Tx GPIO配置
GPIO_Init(GPIOA,&GPIOInitstruct); //设置TX为推免输出模式
GPIOInitstruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIOInitstruct.GPIO_Pin = GPIO_Pin_10;
GPIOInitstruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIOInitstruct); //设置RX GPIO配置
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1,&USART_InitStruct); //配置好串口
NVIC_Config_USART(); //配置NVIC
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE); // 使能接收中断
USART_Cmd(USART1, ENABLE); //开启串口
//串口接受,会引发中断
}
void UART_SendByte(USART_TypeDef * USARTx, uint8_t dat)
{
USART_SendData(USART1, dat);
while((USART_GetFlagStatus(USART1,USART_FLAG_TC))== RESET);
//发送缓冲区为空,状态置1, 写入一个数据,状态置0,灯数据发送借书,这个状态寄存器就变成1
//实现了串口发送一个字节
}
void UART_SendString(USART_TypeDef * USARTx, char* string)
{
char * str = string;//指向string
while(*str) //只要str不为0,表示字符串还没有结束
{
UART_SendByte(USARTx, *str);
str++;
}
}
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|
RCC_APB2Periph_GPIOE, ENABLE); //使能 PB,PE 端口时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //LED0-->PB.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); //PB.5 输出高
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //LED1-->PE.5 推挽输出
GPIO_Init(GPIOE, &GPIO_InitStructure);
GPIO_SetBits(GPIOE,GPIO_Pin_5); //PE.5 输出高
}
|