STM32CubeIDE에서 printf를 USART와 연결하기

printf 출력을 USART와 연결하여 사용 가능. 디버깅 시 상당한 이점을 가질 수 있음.

main.c 파일에 다음의 함수를 추가.

이때 uart의 인스턴스를 설정해야 하는데, STM32F746G-DISCO 보드에선 USART1번이 ST-Link의 Virtual Com Port와 연결되어 있음. 따라서 huart1를 선택.

int __io_putchar(int ch) 
{
     (void) HAL_UART_Transmit(&huart1, (uint8_t*) &ch, 1, 100);
     return ch;
}

프로젝트 설정에서 printf 문에 float 구문을 사용할 수 있도록 설정.

덧.

위 방법을 사용할 때, FreeRTOS 환경 내에선 알 수 없는 이유로 동작이 되지 않음. 메모리 관련 (heap 등등)의 문제로 추정된다는데… 이를 해결하기 위해선 경량화 되어 구현된 printf 함수를 사용하면 됨.

https://github.com/mpaland/printf

이 Repository의 printf.h, printf.c 파일을 해당 프로젝트에 추가하고, printf.h를 인클루드하여 사용.

사용자의 환경에 따라 _putchar 함수를 구현하면 됨.

void _putchar(char c)
{
    /* 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(&huart1, (uint8_t) &c, 1, 0xFFFF);
}

끝!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.