Skip to content
Search

POSIX:termios

lastmod 2024-10-31created 2015-08-2912 edits

Categories

Examples

  • answerjet-relay

Tutorials

  1. Serial communication, part 1
  2. Serial communication - Starting the program breakdown!!
  3. Serial communication - Opening the communication port
  4. Serial communication - Setting the communication speed
  5. Serial communication - start bit and stop bit
  6. Serial communication - data bit size and parity
  7. Full explanation of the serial communication example
  8. Serial communication - poll for receiving data

Download all tutorial files: Falinux_serial_01-08.tar.gz

APIs

open function

termios struct

Serial Communications

Full explanation of the serial communication example

#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

/dev/ttyUSB0 connection drops by itself on Ubuntu

See Universal Serial Bus#/dev/ttyUSB0 connection drops by itself on Ubuntu for details. In short, remove brltty with sudo apt purge brltty.

See also

Favorite site

author Zer0 sitemap