라즈베리파이에서 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);
'컴퓨터 > Linux' 카테고리의 다른 글
[Linux C] TCP 서버 프로그램 (0) | 2022.10.05 |
---|---|
Raspberry Pi UART 교환 (0) | 2022.09.23 |
Raspberry Pi UART 설정 (0) | 2022.09.21 |
Raspberry Pi의 GPIO 사용 (직접제어) (0) | 2022.09.21 |
Raspberry Pi 설치 방법 (0) | 2022.09.20 |
댓글