한국어
Embedded
 

펌웨어 STM32 & LibOpenCM3, printf함수사용

makersweb 2019.08.08 13:14 조회 수 : 3115

개발시 어떤 값을 화면을 통해 출력해서 디버깅해야할때 printf를 사용하면 많은 도움이된다.

 

프로젝트의 개발환경마다 다르겠지만 일반적으로 임베디드장치를 타겟(Target)으로 하는경우 printf의 표준 출력을 Serial통신으로 구현하게된다. 

 

STM32에서 printf()함수로 출력할 문자열이 호스트의 콘솔 화면에 찍히도록 먼저 USART설정하는 방법알아보자.

 

호스트 운영체제: 윈도우10

IDE: Visual Studio Code + PlatformIO

 

여기서도 LibOpenCM3을 사용할 것이며 다음은 전송 속도가 115200이고 전송 핀이 포트 A핀 9에 연결된 USART1을 초기화하는 예를 보여준다.

#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>

static void clock_setup(void)
{
    rcc_clock_setup_in_hse_8mhz_out_24mhz();

    /* Enable clocks for GPIO port A (for GPIO_USART1_TX) and USART1. */
    rcc_periph_clock_enable(RCC_GPIOA);
    rcc_periph_clock_enable(RCC_USART1);
}

static void usart_setup(void)
{
    /* Setup GPIO pin GPIO_USART1_TX/GPIO9 on GPIO port A for transmit. */
    gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ,
              GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_USART1_TX);

    /* Setup UART parameters. */
    usart_set_baudrate(USART1, 115200);
    usart_set_databits(USART1, 8);
    usart_set_stopbits(USART1, USART_STOPBITS_1);
    usart_set_mode(USART1, USART_MODE_TX);
    usart_set_parity(USART1, USART_PARITY_NONE);
    usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);

    /* Finally enable the USART. */
    usart_enable(USART1);
}

 

운영 체제가 없는 임베디드 시스템을 대상으로 할 때 시스템에서 열기, 읽기 및 종료와 같은 syscall은 실제로 의미가 없으므로 전체 표준 라이브러리에 연결하지 않고 컴파일하는 경향이 있다. 이것은 -lnosys와 연결하여 수행되는 작업의 일부로 syscall을 스텁 함수로 대체한다.

예를 들어 POSIX 쓰기 호출은 결국 프로토 타입이있는 함수를 호출한다.

ssize_t _write  (int file, const char *ptr, ssize_t len);

 

따라서 printf가 결국 write를 호출 할 경우 백업 _write 메소드를 다시 구현하여 대신 해당 데이터를 serial로 푸시하면 stdout 및 stderr을 실제로 볼 수있는 곳(Host)으로 리디렉션 할 수 있다.

int _write(int file, const char *ptr, ssize_t len) {
    // If the target file isn't stdout/stderr, then return an error
    // since we don't _actually_ support file handles
    if (file != STDOUT_FILENO && file != STDERR_FILENO) {
        // Set the errno code (requires errno.h)
        errno = EIO;
        return -1;
    }

    // Keep i defined outside the loop so we can return it
    int i;
    for (i = 0; i < len; i++) {
        // If we get a newline character, also be sure to send the carriage
        // return character first, otherwise the serial console may not
        // actually return to the left.
        if (ptr[i] == '\n') {
            usart_send_blocking(USART1, '\r');
        }

        // Write the character to send to the USART1 transmit buffer, and block
        // until it has been sent.
        usart_send_blocking(USART1, ptr[i]);
    }

    // Return the number of bytes we sent
    return i;
}

 

만약 C++ 코드 인 경우 다음과 같이 선언하는 것을 잊지 말자.

extern "C" {
    ssize_t _write(int file, const char *ptr, ssize_t len);
}

 

다음의 헤더를 포함한다.

#include <stdio.h>
#include <errno.h>
#include <unistd.h>

 

이제 printf출력은 serial 콘솔로 확인할 수 있다.

int main(void)
{
    int i = 0;

    clock_setup();
    usart_setup();

    while (1) {
        printf("Hello World!\n");
        for (i = 0; i < 800000; i++) /* Wait a bit. */
            __asm__("NOP");
    }
    return 0;
}

 

helloworld.png

번호 제목 글쓴이 날짜 조회 수
51 윈도우10에서 Prolific USB to Serial 드라이버 인식문제 file makersweb 2016.01.24 22759
50 USB OTG 기술의 개념 file pjk 2014.11.03 15118
49 yocto project, 라즈베리파이를 위한 Qt + 임베디드리눅스 빌드 file makersweb 2019.02.01 10952
48 [Uboot 명령어 및 환경 변수 요약]U-Boot에 Command 및 Parameter에 대한 설명 pjk 2014.01.09 10238
47 ESP-IDF 의 A2DP리뷰 (ESP32) file makersweb 2019.10.28 9491
46 ST, STM32 MCU용 ‘통합 개발 환경(IDE)’ 무료 제공 makersweb 2015.03.04 8852
45 이클립스에서 IAR프로젝트 사용방법 file makersweb 2015.07.09 8769
44 USB 핀아웃 file pjk 2014.10.11 8423
43 AVRISP mkII 펌웨어 업그레이드 file makersweb 2015.07.22 6923
42 라즈베리파이3와 PC간 Serial 통신 테스트 [1] file makersweb 2019.05.20 6338
41 플랫폼 디바이스 및 드라이버에 대해서 makersweb 2020.02.01 6061
40 임베디드 리눅스 부팅 절차 file makersweb 2019.10.21 6031
39 폴링(Polling), 인터럽트(Interrupt), DMA(Direct Memory Access) file pjk 2014.10.24 5960
38 실시간 운영 체제 또는 RTOS(Real Time Operating System) pjk 2014.12.02 5832
37 HelloWorld 커널 모듈과 yocto 레시피 추가 방법 file makersweb 2019.12.09 5547
36 STM32와 CAN(Controller Area Network) Loop Back file makersweb 2017.01.23 5375
35 디바이스 트리(Device Tree, DT) makersweb 2020.01.12 5349
34 printk() makersweb 2014.02.27 5149
33 블루투스(Bluetooth) 기초 file makersweb 2019.08.02 4865
32 AVR(AT90USB162)을 USB to Serial 로 이용하기 file makersweb 2015.02.14 4818