Skip to content

Instantly share code, notes, and snippets.

@alisdair
Created November 15, 2011 15:42
Show Gist options
  • Save alisdair/1367372 to your computer and use it in GitHub Desktop.
Save alisdair/1367372 to your computer and use it in GitHub Desktop.
Code to open a TTY with POSIX API, raw mode
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BAUD B19200
int open_port()
{
int fd;
fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY);
if (fd == -1)
{
perror("Unable to open /dev/ttyS1: ");
exit(1);
}
printf("opened port\n");
int ret;
struct termios ts;
bzero(&ts, sizeof(ts));
cfmakeraw(&ts);
cfsetspeed(&ts, BAUD);
ts.c_cflag |= (CLOCAL | CREAD | CSTOPB);
tcflush(fd, TCIOFLUSH);
ret = tcsetattr(fd, TCSANOW, &ts);
if (ret == -1)
{
perror("tcsetattr: ");
exit(1);
}
printf("set attrs\n");
return fd;
}
int main(void)
{
int fd = open_port();
uint8_t c;
while (read(fd, &c, 1) >= 0)
write(STDOUT_FILENO, &c, 1);
perror("read: ");
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment