본문 바로가기
Embedded/nRF52 BLE 개발 안내서

nRF52 BLE 개발하기 - uart

by 큐찡 2021. 1. 24.
반응형

시작하기

이번에는 통신으로 가장 많이 사용되는 UART 인터페이스에 대해서 알아보도록 하자.

UART 인터페이스를 통해 RS-232/485 등 다양한 통신을 사용할 수 있으므로 중요한 인터페이스 중 하나이다.

\examples\peripheral\uart\pca10040\blank\ses 폴더에서 프로젝트를 실행시키고 main 함수를 살펴보자.

//#define ENABLE_LOOPBACK_TEST  /**< if defined, then this example will be a loopback test, which means that TX should be connected to RX to get data loopback. */

#define MAX_TEST_DATA_BYTES     (15U)                /**< max number of test bytes to be used for tx and rx. */
#define UART_TX_BUF_SIZE 256                         /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 256                         /**< UART RX buffer size. */

void uart_error_handle(app_uart_evt_t * p_event)
{
    if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}


#ifdef ENABLE_LOOPBACK_TEST
/* Use flow control in loopback test. */
#define UART_HWFC APP_UART_FLOW_CONTROL_ENABLED

/** @brief Function for setting the @ref ERROR_PIN high, and then enter an infinite loop.
 */
static void show_error(void)
{

    bsp_board_leds_on();
    while (true)
    {
        // Do nothing.
    }
}


/** @brief Function for testing UART loop back.
 *  @details Transmitts one character at a time to check if the data received from the loopback is same as the transmitted data.
 *  @note  @ref TX_PIN_NUMBER must be connected to @ref RX_PIN_NUMBER)
 */
static void uart_loopback_test()
{
    uint8_t * tx_data = (uint8_t *)("\r\nLOOPBACK_TEST\r\n");
    uint8_t   rx_data;

    // Start sending one byte and see if you get the same
    for (uint32_t i = 0; i < MAX_TEST_DATA_BYTES; i++)
    {
        uint32_t err_code;
        while (app_uart_put(tx_data[i]) != NRF_SUCCESS);

        nrf_delay_ms(10);
        err_code = app_uart_get(&rx_data);

        if ((rx_data != tx_data[i]) || (err_code != NRF_SUCCESS))
        {
            show_error();
        }
    }
    return;
}
#else
/* When UART is used for communication with the host do not use flow control.*/
#define UART_HWFC APP_UART_FLOW_CONTROL_DISABLED
#endif


/**
 * @brief Function for main application entry.
 */
int main(void)
{
    uint32_t err_code;

    bsp_board_init(BSP_INIT_LEDS);

    const app_uart_comm_params_t comm_params =
      {
          RX_PIN_NUMBER,
          TX_PIN_NUMBER,
          RTS_PIN_NUMBER,
          CTS_PIN_NUMBER,
          UART_HWFC,
          false,
#if defined (UART_PRESENT)
          NRF_UART_BAUDRATE_115200
#else
          NRF_UARTE_BAUDRATE_115200
#endif
      };

    APP_UART_FIFO_INIT(&comm_params,
                         UART_RX_BUF_SIZE,
                         UART_TX_BUF_SIZE,
                         uart_error_handle,
                         APP_IRQ_PRIORITY_LOWEST,
                         err_code);

    APP_ERROR_CHECK(err_code);

#ifndef ENABLE_LOOPBACK_TEST
    printf("\r\nUART example started.\r\n");

    while (true)
    {
        uint8_t cr;
        while (app_uart_get(&cr) != NRF_SUCCESS);
        while (app_uart_put(cr) != NRF_SUCCESS);

        if (cr == 'q' || cr == 'Q')
        {
            printf(" \r\nExit!\r\n");

            while (true)
            {
                // Do nothing.
            }
        }
    }
#else

    // This part of the example is just for testing the loopback .
    while (true)
    {
        uart_loopback_test();
    }
#endif
}

comm_params에 UART RX 핀, TX 핀, RTS 핀, CTS 핀, 흐름 제어, 패리티 비트, 통신속도 설정을 해주고 APP_UART_FIFO_INIT 함수의 전달 인자로 넘겨준다.

APP_UART_FIFO_INIT 함수에 RX, TX 버퍼 사이즈, uart_error_handle 함수를 전달하여 UART 인터페이스 사용을 활성화한다.

app_uart_get 함수로 UART 수신을 대기하고 수신이 되면 app_uart_put 함수로 UART 송신을 한다.

이렇게 해서 터미널 프로그램에서 입력한 문자열이 그대로 다시 출력되게 된다.

만약 q 또는 Q 문자열이 들어왔다면 프로그램은 아무것도 하지 않게 된다.

이제 USB to UART 컨버터(이하 UART 컨버터)를 nRF52832 DK에 연결해보도록 하자.

UART 컨버터는 시중에 판매되고 있는 제품 중 마음에 드는 걸로 선택하자.

이 예제에서 사용하는 터미널 프로그램은 SerialPortMon이다.

링크를 통해 제작자 블로그에 가서 다운로드하여 감사한 마음으로 사용하도록 하자.

PC와 UART 컨버터 연결을 하고 터미널 프로그램을 실행시킨 다음 예제를 돌려보자.

printf("\r\nUART example started.\r\n")가 터미널 프로그램에 출력되는 것을 확인할 수 있다.

이제 보내는 문자열 편집에 문자열을 입력하고 보내기를 해보자.

보낸 문자열이 그대로 출력되는 것을 확인할 수 있다.

앞으로

지금까지 간단하게 UART 인터페이스 사용 방법에 대해서 알아보았다.

앞으로 진행되는 예제들의 메시지 출력으로 UART 인터페이스를 사용할지 NRF_LOG를 사용할지 편한 방법을 선택하면 된다.

반응형

댓글