Skip to content

Instantly share code, notes, and snippets.

@aagontuk
Created October 21, 2016 23:45
Show Gist options
  • Save aagontuk/c8110c4a76ec4f9b98cc9bff127c0b8d to your computer and use it in GitHub Desktop.
Save aagontuk/c8110c4a76ec4f9b98cc9bff127c0b8d to your computer and use it in GitHub Desktop.
Serial Programming Example based on http://xanthium.in/Serial-Port-Programming-on-Linux
/* Serial Port Programming
* Base on the tutorial from
* http://xanthium.in/Serial-Port-Programming-on-Linux
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 100
void settermopt(struct termios *termopt);
void write_serial(int fd, char *buffer);
void read_serial(int fd);
int main(int argc, char *argv[]){
int fd;
struct termios termopt;
char buffer[BUFFSIZE];
fd = open(argv[1], O_RDWR | O_NOCTTY);
if(fd == -1){
fprintf(stderr, "Error opening port: %s\n", argv[1]);
exit(1);
}
fprintf(stdout, "Successfully opened port %s! FD: %d\n", argv[1], fd);
/* set termios options for tty */
tcgetattr(fd, &termopt);
settermopt(&termopt);
tcsetattr(fd, TCSANOW, &termopt);
strcpy(buffer, argv[2]);
write_serial(fd, buffer);
fprintf(stdout, "Reading...\n\n");
read_serial(fd);
close(fd);
return 0;
}
void settermopt(struct termios *termopt){
/* Control Option */
termopt->c_cflag &= ~CRTSCTS; /* Turn off hardware based flow control */
termopt->c_cflag |= CREAD | CLOCAL; /*
* Turn on the receiver(CREAD) and
* dont change owner of the port(CLOCAL)
*/
termopt->c_cflag &= ~(IXON | IXOFF | IXANY); /* Turnoff software based flow control */
termopt->c_cflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* Non canonical mode */
/* Data stream setttings - baud, parity etc */
cfsetispeed(termopt, B9600); /* Input baud rate */
cfsetospeed(termopt, B9600); /* Output baud rate */
termopt->c_cflag &= ~PARENB; /* No Parity */
termopt->c_cflag &= ~CSTOPB; /* 1 stop bit */
termopt->c_cflag &= ~CSIZE; /* Clear bit Mask for data bits */
termopt->c_cflag |= CS8; /* 8 data bit */
termopt->c_cc[VMIN] = 10;
termopt->c_cc[VTIME] = 0;
}
void write_serial(int fd, char *buffer){
int nbytes;
nbytes = write(fd, buffer, strlen(buffer));
fprintf(stdout, "%d bytes written!\n", nbytes);
}
void read_serial(int fd){
char readBuff[BUFFSIZE];
int nbytes, i;
tcflush(fd, TCIFLUSH);
while((nbytes = read(fd, readBuff, BUFFSIZE)) > 0){
for(i = 0; i < nbytes; i++){
fprintf(stdout, "%c", readBuff[i]);
}
}
fprintf(stdout, "\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment