Skip to content

Instantly share code, notes, and snippets.

@md-jamal
Last active January 27, 2019 05:04
#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;
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);
}
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");
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment