本帖最后由 lihui567 于 2017-12-1 08:40 编辑
用的单片机为STM32F105RBT6,串口一直有问题,看一下简单的串口接受程序
- <div class="blockcode"><blockquote>void uart_init(u32 bound)
- {
- //GPIO¶Ë¿ÚÉèÖÃ
- GPIO_InitTypeDef GPIO_InitStructure;
- USART_InitTypeDef USART_InitStructure;
- NVIC_InitTypeDef NVIC_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO, ENABLE);
- //USART1_TX PA.9
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
- GPIO_Init(GPIOA, &GPIO_InitStructure);
-
- //USART1_RX PA.10
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
- GPIO_Init(GPIOA, &GPIO_InitStructure);
- //Usart1 NVIC ÅäÖÃ
- NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;
- NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //
- NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨµÀʹÄÜ
- NVIC_Init(&NVIC_InitStructure); //¸ù¾ÝNVIC_InitStructÖÐÖ¸¶¨µÄ²ÎÊý³õʼ»¯ÍâÉèNVIC¼Ä´æÆ÷USART1
-
- //USART ³õʼ»¯ÉèÖÃ
-
- USART_InitStructure.USART_BaudRate = bound;//Ò»°ãÉèÖÃΪ9600;
- 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_Init(USART1, &USART_InitStructure);
-
- USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//¿ªÆôÖжÏ
-
- USART_Cmd(USART1, ENABLE); //ʹÄÜ´®¿Ú
- }
- void USART1_IRQHandler(void) //´®¿Ú1ÖжϷþÎñ³ÌÐò
- {
- u8 Res;
- static u8 i;
-
-
- // if(USART_GetFlagStatus(USART1, USART_FLAG_RXNE)==1)
- if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
- {
- GPIO_ResetBits(GPIOC, GPIO_Pin_0);
- // Res =USART_ReceiveData(USART1);
-
- USART_ClearFlag(USART1,USART_FLAG_RXNE);
- // USART_SendData(USART1,Res);
-
- if(rec_flag==0)
- {
- // USART_SendData(USART1,rec_flag);
- // GPIO_ResetBits(GPIOC, GPIO_Pin_1);
- if(USART_ReceiveData(USART1)==0xff)
- {
- GPIO_ResetBits(GPIOC, GPIO_Pin_1);
- rec_flag=1;
- // USART_SendData(USART1,rec_flag);
- i=0;
- }
- }
|