STM32 USART 串口简单使用串口简单使用
USART_StructInit(&USART_InitStructure);//装填默认值 USART_Init(USART1, &USART_InitStructure);//根据
USART_InitStruct中指定的参数初始化外设USARTx寄存器 USART_Cmd(USART1, ENABLE); //启用
STM32 的库实在强大~!函数长的像句子......
好了开始了:
使用查询方式的USART:
设置时钟:
RCC_APB2Periph_AFIO功能复用IO时钟
RCC_APB2Periph_GPIOAGPIOA时钟
RCC_APB2Periph_USART1 USART1时钟
你可以用
//使能串口1,PA,AFIO总线
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO|RCC_APB2Periph_USART1,ENABLE);
或直接
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ALL,ENABLE); //全部APB2外设时钟开启
注意USART2的你开启为RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
设置GPIO:
GPIO_InitTypeDefGPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_AF_PP;//推挽输出-TX
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入-RX
GPIO_Init(GPIOA, &GPIO_InitStructure);
设置USART:
这里我用的是3.0的库相对于2.0的库来说多了一步,先说2.0
USART_InitTypeDef USART_InitStructure;
USART_StructInit(&USART_InitStructure);//装填默认值
USART_Init(USART1, &USART_InitStructure);//根据USART_InitStruct中指定的参数初始化外设USARTx寄存器
USART_Cmd(USART1, ENABLE); //启用
就好了~!
而3.0的库需要
USART_InitTypeDefUSART_InitStructure;
USART_ClockInitTypeDefUSART_ClockInitStructure;
USART_StructInit(&USART_InitStructure);
USART_ClockStructInit(&USART_ClockInitStructure);