STM32F030學(xué)習(xí)之串口收發(fā)程序
使用USART最簡單的情況是只使用3根線:Tx用于 數(shù)據(jù)發(fā)送,Rx用于數(shù)據(jù)接收,GND是信號地線,提供通信雙方的參考電平。
實(shí)現(xiàn)的功能: 1、通過串口發(fā)送數(shù)據(jù);
2、中斷方式接收數(shù)據(jù),并將接收到的數(shù)據(jù)回送。
首先,第一步:配置引腳,將串口映射到PA9(Tx),PA10(Rx)。
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Connect GPIOs to USART1 RX&TX */
GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_1); //Tx
GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_1); //Rx
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10; //USART1_TX | USART1_RX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_1;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
第二步:配置串口。
void USART_Configuration(void)
{
USART_InitTypeDef USART_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_Tx | USART_Mode_Rx;
USART_Init(USART1,&USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_Cmd(USART1,ENABLE);
}
第三步:配置中斷。
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
/*****USART1 interrupt Config****/
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
第四步:添加串口中斷函數(shù),函數(shù)名是固定的:void USART1_IRQHandler(void)。中斷進(jìn)入時(shí)候,先判斷接收寄存器是否有數(shù)據(jù),有數(shù)據(jù)時(shí)候就接收,然后使用USART_SendData()將數(shù)據(jù)發(fā)回PC終端。
void USART1_IRQHandler (void)
{
uint16_t temp;
if(USART_GetITStatus(USART1,USART_IT_RXNE)!= RESET) //Receive Data register not empty interrupt.
{
USART_ClearITPendingBit(USART1,USART_IT_RXNE);
temp = USART_ReceiveData(USART1);
USART_SendData(USART1,temp);
}
}
接下來就是主函數(shù)main了,具體如下:
int main(void)
{
RCC_Configuration();
GPIO_Configuration();
USART_Configuration();
NVIC_Configuration();
TIM_Confguration();
GPIO_SetBits(GPIOC,GPIO_Pin_8);
Uart_Put_String("wangxiaoxurn");
while(1)
{;}
}