Skip to content

Instantly share code, notes, and snippets.

@Oxore
Last active December 22, 2023 17:28
Show Gist options
  • Save Oxore/81dc8f3d6d27ac1659a7cde0ec71432d to your computer and use it in GitHub Desktop.
Save Oxore/81dc8f3d6d27ac1659a7cde0ec71432d to your computer and use it in GitHub Desktop.
/*
stty -F /dev/ttyUSB0 38400 \
clocal cread cs8 cstopb -parenb -crtscts \
-ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon \
-echo -echonl -icanon -isig -iexten \
-opost \
min 1 time 1
*/
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
static int serial_open(const char *port, speed_t baud)
{
int fd;
struct termios tty;
if ((fd = open(port, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
{
fprintf(stderr, "Failed to open port \"%s\"\n", port);
return -1;
}
if (tcgetattr(fd, &tty) < 0)
{
fprintf(stderr, "Failed to tcgetattr of port \"%s\"\n", port);
return -1;
}
cfsetospeed(&tty, baud);
cfsetispeed(&tty, baud);
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~PARENB;
tty.c_cflag |= CSTOPB;
tty.c_cflag &= ~CRTSCTS;
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty))
{
fprintf(stderr, "Failed to tcsetattr of port \"%s\"\n", port);
return -1;
}
fprintf(stderr, "Port \"%s\" opened\n", port);
return fd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment