使用SW4STM32建置STM32 HAL專案
上學期修課時需要的一些小技巧紀錄一下。有人蠻多人問過我,所以打一篇文章。
步驟
其實滿簡單的,只要在建立新專案時多勾選一個選項即可。
![]() |
當選擇完板子時不要急著案完成,繼續按下一步。 |
下一步後,勾選Hardware Abstraction Layer(HAL),即可導入ST官方提供之HAL library。其他還有一些第三方library如FreeRTOS等,也可在這裡新增。
結果
SW4STM32會建立如下專案:
其中HAL會獨立在HAL_Driver下。有幾個檔案要特別注意。
src/stm32l4xx_it.c和inc/stm32l4xx_it.h這兩個檔案為放置Interrupt handler用的檔案,如有新增的Interrupt handler最好是放在這裡。
src/system_stm32l4xx.c:這個檔案放置系統開機時的初始化(clock和RCC)。
src/syscalls.c:這個檔案放置syscall,如果需要將printf的輸出導到UART,就需要在這個檔案動手腳。如下重新定義_io_putchar(int ch)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//extern int __io_putchar(int ch) __attribute__((weak)); | |
extern int __io_getchar(void) __attribute__((weak)); | |
register char * stack_ptr asm("sp"); | |
char *__env[1] = { 0 }; | |
char **environ = __env; | |
int __io_putchar(int ch) | |
{ | |
/* Place your implementation of fputc here */ | |
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */ | |
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF); | |
return ch; | |
} |
其他
若要將其他的STM32CubeMX產生出的檔案放入SW4STM32產生之HAL專案,編譯時可能會遇到一些問題。如:void HAL_MspInit(void) redefination。原因是HAL_Driver/Src/stm32l4xx_hal_msp_template.c這個檔案會有衝突,處理方法即是刪除此檔。