初始化设置:
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
USART_InitTypeDef USART_InitStructure;
USART_ClockInitTypeDef USART_CLK_InitStructure;
RCC_AHBPeriphClockCmd( RCC_AHBPeriph_GPIOA, ENABLE );
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); /* Configure USART1 Rx (PA10) as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
GPIO_Init( GPIOA, &GPIO_InitStructure ); /* Configure USART1 Tx (PA9) as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init( GPIOA, &GPIO_InitStructure );
/*-----------中断组初始化----------------------------------*/
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init( &NVIC_InitStructure ); USART_InitStructure.USART_BaudRate = 115200; //波特率初始化
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_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_CLK_InitStructure.USART_Clock = USART_Clock_Disable;
// USART_CLK_InitStructure.USART_CPOL = USART_CPOL_Low;
// USART_CLK_InitStructure.USART_CPHA = USART_CPHA_2Edge;
// USART_CLK_InitStructure.USART_LastBit = USART_LastBit_Disable;
USART_Init( USART1, &USART_InitStructure );
// STM_EVAL_COMInit(COM1, &USART_InitStructure);
// USART_ClockInit( USART1, &USART_CLK_InitStructure);
USART_ITConfig( USART1, USART_IT_RXNE, ENABLE );
USART_Cmd( USART1, ENABLE );
GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
相应的串口发送程序
void Uart1_Char(unsigned char ch)
{
USART1->DR = ch;
while((USART1->SR & 0x40)==0);
}
中断处理程序
void USARTx_IRQHANDLER(void)
{
if(USART_GetITStatus(EVAL_COMX, USART_IT_RXNE) != RESET)
{
/* Read one byte from the receive data register */
RxBuffer[RxCounter++] = (USART_ReceiveData(EVAL_COMX) & 0x7F); if(RxCounter == NbrOfDataToRead)
{
/* Disable the EVAL_COMX Receive interrupt */
USART_ITConfig(EVAL_COMX, USART_IT_RXNE, DISABLE);
}
} if(USART_GetITStatus(EVAL_COMX, USART_IT_TXE) != RESET)
{
/* Write one byte to the transmit data register */
USART_SendData(EVAL_COMX, TxBuffer[TxCounter++]); if(TxCounter == NbrOfDataToTransfer)
{
/* Disable the EVAL_COMX Transmit interrupt */
USART_ITConfig(EVAL_COMX, USART_IT_TXE, DISABLE);
}
}
}