| 二、串口的使用步骤 (1)中断方式
 基本步骤是初试化时钟,脚位、波特率设置、安装中断服务程序、开中断等,参考代码如下:
 void uart_init(void)
 {
 USART_InitTypeDef USART_InitStructure;
 NVIC_InitTypeDef NVIC_InitStructure;
 GPIO_InitTypeDef  GPIO_InitStructure;
 
 /* Enable GPIO clock  */
 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
 
 /* Enable USART clock */
 RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
 
 /* Connect USART pins to AF7 */
 GPIO_PinAFConfig(GPIOC, GPIO_PinSource10, GPIO_AF_USART3);
 GPIO_PinAFConfig(GPIOC, GPIO_PinSource11,  GPIO_AF_USART3);
 
 /* Configure USART Tx and Rx as  alternate function push-pull */
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
 GPIO_InitStructure.GPIO_Speed =  GPIO_Speed_100MHz;
 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
 GPIO_InitStructure.GPIO_PuPd =  GPIO_PuPd_UP;
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
 GPIO_Init(GPIOC,  &GPIO_InitStructure);
 
 GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_11;
 GPIO_Init(GPIOC,  &GPIO_InitStructure);
 /*  USARTx configuration  ----------------------------------------------------*/
 /* USARTx configured as follow:
 - BaudRate = 3750000 baud
 - Maximum BaudRate that can be achieved when  using the Oversampling by 8
 is: (USART APB Clock / 8)
 Example:
 - (USART3 APB1  Clock / 8) = (30 MHz / 8) = 3750000 baud
 - (USART1 APB2 Clock / 8) = (60 MHz / 8) = 7500000  baud
 - Maximum BaudRate that can  be achieved when using the Oversampling by 16
 is: (USART APB Clock / 16)
 Example: (USART3 APB1 Clock / 16) = (30 MHz / 16)  = 1875000 baud
 Example: (USART1  APB2 Clock / 16) = (60 MHz / 16) = 3750000 baud
 - Word Length = 8 Bits
 - one Stop Bit
 - No parity
 - Hardware flow control disabled (RTS and  CTS signals)
 - Receive and  transmit enabled
 */
 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_Init(USART3,  &USART_InitStructure);
 
 /* NVIC configuration  */
 /* Configure the Priority  Group to 2 bits */
 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
 
 /* Enable the USARTx Interrupt */
 NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
 NVIC_InitStructure.NVIC_IRQChannelSubPriority =  0;
 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
 NVIC_Init(&NVIC_InitStructure);
 
 /* Enable USART  */
 USART_Cmd(USART3,  ENABLE);
 USART_ITConfig(USART3,  USART_IT_RXNE, ENABLE);
 }
 中断服务程序如下:
 void USART3_IRQHandler(void)
 {
 unsigned char ch;
 if(USART_GetITStatus(USART3,  USART_IT_RXNE) != RESET)
 {
 /* Read one byte from the  receive data register */
 ch =  (USART_ReceiveData(USART3));
 
 printf("in[%c].\r\n",ch);
 }
 }
 直接把接收到的字符打印出来。
 更多操作
 |