微波EDA网,见证研发工程师的成长!
首页 > 研发问答 > 嵌入式设计讨论 > MCU和单片机设计讨论 > 串口测试及注意点

串口测试及注意点

时间:10-02 整理:3721RD 点击:
本节我们测试NUCLEO-F412ZG的串口,在测试工程中由于没有注意,发现串口发送的数据乱码,后来才发现是数据位数和奇偶检验的问题,大家在运用过程中要注意是否使用奇偶校验,奇偶校验为包含在数据长度中。程序说明如下
int main(void)
{
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user
         can eventually implement his proper time base source (a general purpose
         timer for example or other time source), keeping in mind that Time base
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
     */
  HAL_Init();//初始化HAL库
  /* Configure the system clock to 100 MHz */
  SystemClock_Config();//配置系统时钟为100MHz
  /* Initialize BSP Led for LED2 */
  BSP_LED_Init(LED2);//初始化LED2
  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits (7 data bit + 1 parity bit) :
                          BE CAREFUL : Program 7 data bits + 1 parity bit in PC HyperTerminal
      - Stop Bit    = One Stop bit
      - Parity      = ODD parity
      - BaudRate    = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance        = USARTx;//串口号为USARTx
  UartHandle.Init.BaudRate   = 9600;//波特率为9600
  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;//8位数据长度
  UartHandle.Init.StopBits   = UART_STOPBITS_1;//1位停止位
  UartHandle.Init.Parity     = UART_PARITY_ODD;//偶检验
  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;//无流控制
  UartHandle.Init.Mode       = UART_MODE_TX_RX;//开启发送和接收
  UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;//过采样设置为16等级
  if (HAL_UART_Init(&UartHandle) != HAL_OK)//初始化串口,判断是否初始化成功
  {
    /* Initialization Error */
    Error_Handler();//初始化错误执行函数
  }
  /* Output a message on Hyperterminal using printf function */
  printf("\n\r UART Printf Example: retarget the C library printf function to the UART\n\r");//打印数据
  printf("** Test finished successfully. ** \n\r");
  /* Infinite loop */
  while (1)
  {
  }
}


Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top