STM32 串口通訊

本篇建議搭配以下影片進行服用
YT連結
什麼是串口通訊
STM32最小系統板上沒有集成CP210等USB轉TTL的IC,所以沒辦法透過Serial.print的函數直接像電腦串口打印,因此可以借用FTDI等USB轉TTL模組來進行轉換

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

連線方法像是這樣
Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

串口的英文簡稱叫USART或UART
在CubeIDE中.ioc設置中可以點進去Connectivity中設置,筆者這邊選擇USART2通道作為串口

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

按照順序

  1. 選擇Connectivity
  2. 選擇USART2
  3. 選擇Asynchronous模式
  4. 設定波特率、數據位、有無奇偶校驗、數據長度。
  5. 查看腳位,USART的位置在PA2、PA3。

沒有FTDI的替代方案

使用邏輯準位在3.3V的其他有USB轉TTL的開發板 例如ESP32
將接線如下表連接,再透過USB連接到ESP32串口上即可借用ESP32上的USB 轉TTL來進行串口通訊。

STM32 ESP32
PA2(TX) TX0
PA3(RX) RX0
GND GND

接下來我們在main.c中的程式片段定義一個char字串組
並在while循環中不斷向電腦發送字串

 char msg[] = "Hello \r\n";
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	  HAL_UART_Transmit(&huart2, (uint8_t*)msg, strlen(msg), 100);
	  
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }

具體程式碼如圖片擺放

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

接下來打開任何一個串口調適助手將波特率調到115200,然後COM port是ESP32的那個COM
Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

就可以看到打印過來的訊息了
Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →