summaryrefslogtreecommitdiff
path: root/util/tty.c
diff options
context:
space:
mode:
Diffstat (limited to 'util/tty.c')
-rw-r--r--util/tty.c48
1 files changed, 48 insertions, 0 deletions
diff --git a/util/tty.c b/util/tty.c
new file mode 100644
index 0000000..be56b44
--- /dev/null
+++ b/util/tty.c
@@ -0,0 +1,48 @@
+#include <stdlib.h>
+
+#include <fcntl.h>
+#include <termios.h>
+#include <unistd.h>
+
+int tty_open(char *tty_fn) {
+ struct termios tty;
+ int tty_fd;
+ int rv;
+
+ tty_fd = open(tty_fn, O_RDWR);
+ if (tty_fd < 0) return tty_fd;
+
+ rv = tcgetattr(tty_fd, &tty);
+ if (rv) return -1;
+
+ tty.c_cflag &= ~PARENB; // No parity
+ tty.c_cflag &= ~CSTOPB; // One stop bit
+ tty.c_cflag &= ~CSIZE; // Clear all bits that set the data size
+ tty.c_cflag |= CS8; // 8 bits per byte
+ tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hw flow control
+ tty.c_cflag |= (CREAD | CLOCAL); // Turn on READ & ignore ctrl lines (CLOCAL = 1)
+
+ tty.c_lflag &= ~ICANON;
+ tty.c_lflag &= ~(ECHO | ECHOE |ECHONL); // Disable echo
+ tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP signals
+ tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off sw flow ctrl
+ tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes
+
+ tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
+ tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
+#ifndef __linux__
+ tty.c_oflag &= ~OXTABS; // Prevent conversion of tabs to spaces (NOT PRESENT ON LINUX)
+ tty.c_oflag &= ~ONOEOT; // Prevent removal of C-d chars (0x004) in output (NOT PRESENT ON LINUX)
+#endif
+
+ tty.c_cc[VTIME] = 10; // Wait for up to 1s (10 deciseconds), returning as soon as any data is received.
+ tty.c_cc[VMIN] = 0;
+
+ cfsetispeed(&tty, B115200);
+ cfsetospeed(&tty, B115200);
+
+ rv = tcsetattr(tty_fd, TCSANOW, &tty);
+ if (rv) return -1;
+
+ return tty_fd;
+};