컴퓨터/Linux

Raspberry Pi UART 사용 (C 프로그램)

Begi 2022. 9. 22. 00:53
반응형

라즈베리파이에서 UART를 사용하는 C 코드는 다음과 같다.

 

 

#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

 

// Configure

int uart0_filestream = -1;
uart0_filestream = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);  //Open in non blocking read/write mode
if (uart0_filestream == -1)
{
    printf("Error - Unable to open UART. Ensure it is not in use by another application\n");
}

 

struct termios options;
tcgetattr(uart0_filestream, &options);
options.c_cflag = B9200 | CS8 | CLOCAL | CREAD; //<Set baud rate
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0_filestream, TCIFLUSH);

tcsetattr(uart0_filestream, TCSANOW, &options);

 

// Transmit
unsigned char tx_buf[20];
strcpy(tx_buf, "Hi!\r\n");

if (uart0_filestream != -1)
{
    int count = write(uart0_filestream, &tx_buf[0], strlen(tx_buf));
    if (count < 0)
    {
        printf("UART TX error\n");
    }
}

// Receive
sleep(1);
if (uart0_filestream != -1)
{
    unsigned char rx_buf[256];
    int rx_buf_len = read(uart0_filestream, (void*)rx_buf, 255);
    if (rx_buf_len < 0)
    {
        //An error occured (will occur if there are no bytes)
    }
    else if (Rx_buf_len == 0) 
    {
        //No data waiting
    }
    else 
    {
        rx_buf[rx_buf_len] = '\0';
        printf("%d bytes read : %s\n", rx_buf_len, rx_buf);
    }
}

// Close
close(uart0_filestream);

반응형