Skip to content

POSIX:termios

Categories

Examples

  • answerjet-relay

Tutorials

  1. 시리얼 통신 첫회
  2. 시리얼 통신 - 프로그램 분해 설명 시작!!
  3. 시리얼 통신 - 통신포트 열기
  4. 시리얼 통신 - 통신 속도 결정
  5. 시리얼 통신 - start bit와 stop bit
  6. 시리얼 통신 - data bit size와 parity
  7. 시리얼 통신 예제 전체 설명
  8. 시리얼 통신 - 자료 수신을 위한 poll

전체 강좌 파일 다운로드: Falinux_serial_01-08.tar.gz

APIs

open function

termios struct

Serial Communications

시리얼 통신 예제 전체 설명

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

#define BAUD_RATE    B9600
#define DEVICE_PATH  "/dev/ttyUSB0"
#define CMD_ON       "RY 1 1\r"
#define CMD_OFF      "RY 1 0\r"

int main()
{
    int fd = open(DEVICE_PATH, O_RDWR);

    if (fd < 0) {
        perror("Failed to open serial port");
        return 1;
    }

    struct termios tty;
    memset(&tty, 0, sizeof tty);

    if (tcgetattr(fd, &tty) != 0) {
        perror("Error from tcgetattr");
        return 1;
    }

    tty.c_cflag = BAUD_RATE | CS8 | CLOCAL | CREAD;
    tty.c_iflag = IGNPAR;
    tty.c_oflag = 0;
    tty.c_lflag = 0;

    tcflush(fd, TCIFLUSH);

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        perror("Error from tcsetattr");
        return 1;
    }

    write(fd, CMD_ON, strlen(CMD_ON));
    printf("ON command sent\n");

    sleep(2);

    write(fd, CMD_OFF, strlen(CMD_OFF));
    printf("OFF command sent\n");

    close(fd);

    return 0;
}

Troubleshooting

Ubuntu 에서 /dev/ttyUSB0 연결이 저절로 끊기는 현상

Universal Serial Bus#Ubuntu 에서 /dev/ttyUSB0 연결이 저절로 끊기는 현상 항목 참조. 간단히, sudo apt purge brlttybrltty를 제거하면 된다.

See also

Favorite site