一、配置时钟:GPIO时钟、串口时钟、复用引脚时钟
二、配置GPIO结构体
三、配置串口结构体
//串口初始化示例
void usart_init(void)
{
//创建结构体
GPIO_InitTypeDef gpioinitStructure;
USART_InitTypeDef usartinitStructure;
NVIC_InitTypeDef NVICinitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
//设置时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE );
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE );
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE );
//A9 TX
gpioinitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
gpioinitStructure.GPIO_Pin = GPIO_Pin_9 ;
gpioinitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOA, &gpioinitStructure);
//10 Rx
gpioinitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
gpioinitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_Init(GPIOA, &gpioinitStructure);
//串口结构体
usartinitStructure.USART_BaudRate = 115200;
usartinitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//硬件流
usartinitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx ;//配置输入和输出模式
usartinitStructure.USART_Parity = USART_Parity_No;//校验位
usartinitStructure.USART_StopBits = USART_StopBits_1;//停止位
usartinitStructure.USART_WordLength = USART_WordLength_8b;//有效数据长度
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//配合中断配置使能
USART_Init(USART1, &usartinitStructure);//初始化
USART_Cmd(USART1, ENABLE);//使能串口
//内核外设中断
NVICinitStructure.NVIC_IRQChannel = EXTI1_IRQn;//中断通道
NVICinitStructure.NVIC_IRQChannelPreemptionPriority = 1;//抢占优先级
NVICinitStructure.NVIC_IRQChannelSubPriority = 1;//子优先级
NVICinitStructure.NVIC_IRQChannelCmd = ENABLE;//使能
NVIC_Init(&NVICinitStructure);
}
四、串口发送与中断接收
//发送字符
void USARTSendByte(USART_TypeDef* USARTx, uint16_t Data)
{
USART_SendData(USARTx, Data);
while( USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
}
//发送字符串
void USARTSendstr(USART_TypeDef* USARTx, char *str)
{
uint16_t i = 0;
do
{
USARTSendByte(USARTx, *(str + i)) ;
i++;
}while( *(str + i) != '