Skip to content

Instantly share code, notes, and snippets.

@md-jamal
Created January 27, 2019 05:10
Show Gist options
  • Save md-jamal/49b4789e2e3da9ef22fa2df5265bd400 to your computer and use it in GitHub Desktop.
Save md-jamal/49b4789e2e3da9ef22fa2df5265bd400 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/types.h>
#include <termios.h>
#include <fcntl.h>
#include <stdlib.h>
#define SERIAL_DEVICE "/dev/ttyUSB0"
int main()
{
struct termios serial_port_settings;
int fd;
int retval;
char buf[256];
int i, loop = 2;
fd = open(SERIAL_DEVICE, O_RDWR);
if (fd < 0) {
perror("Failed to open SERIAL_DEVICE");
exit(1);
}
retval = tcgetattr(fd, &serial_port_settings);
if (retval < 0) {
perror("Failed to get termios structure");
exit(2);
}
//setting baud rate to B38400
retval = cfsetospeed(&serial_port_settings, B38400);
if (retval < 0) {
perror("Failed to set 38400 output baud rate");
exit(3);
}
retval = cfsetispeed(&serial_port_settings, B38400);
if (retval < 0) {
perror("Failed to set 38400 input baud rate");
exit(4);
}
serial_port_settings.c_lflag |= ICANON;
//Disable ECHO
serial_port_settings.c_lflag &= ~(ECHO | ECHOE);
retval = tcsetattr(fd, TCSANOW, &serial_port_settings);
if (retval < 0) {
perror("Failed to set serial attributes");
exit(5);
}
printf("Successfully set the baud rate\n");
while (loop--) {
retval = read(fd, buf, sizeof(buf));
if (retval < 0) {
perror("Read on SERIAL_DEVICE failed");
exit(6);
}
printf("Read returned %d bytes\n", retval);
for (i = 0; i < retval; i++) {
printf("Read Character:%c \t ASCII:%d\n", buf[i], buf[i]);
}
}
close(fd);
return 0;
}
@corndog2000
Copy link

This is exactly what I was looking for, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment