Create a gist now

Instantly share code, notes, and snippets.

Program to set arbitrary speed
/*
* Allows to set arbitrary speed for the serial device on Linux.
* stty allows to set only predefined values: 9600, 19200, 38400, 57600, 115200, 230400, 460800.
*/
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <asm/termios.h>
int main(int argc, char* argv[]) {
if (argc != 3) {
printf("%s device speed\n\nSet speed for a serial device.\nFor instance:\n %s /dev/ttyUSB0 75000\n", argv[0], argv[0]);
return -1;
}
int fd = open(argv[1], O_RDONLY);
int speed = atoi(argv[2]);
struct termios2 tio;
ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = speed;
tio.c_ospeed = speed;
int r = ioctl(fd, TCSETS2, &tio);
close(fd);
if (r == 0) {
printf("Changed successfully.\n");
} else {
perror("ioctl");
}
}
@peterhurley

Can you add a simple license statement to the comment?

@robs8899

Great thanks for this piece of code! It solved my problem to set a baud rate of 74880 of the UART in my Raspberry Pi to communicate with an ESP8266.

@npatil15

Hi,
I ran this code, where I want to set baud rate of 1.2kbps.

./a.out /dev/ttys0 1200

and it run sucessfully but when I cross check its baud rate using

stty -F /dev/ttys0
speed 38400 baud; line = 0;
min = 1; time = 0;
ignbrk -brkint -icrnl -imaxbel
-opost -onlcr
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke

Here, it doesnt refelct the speed as I mention.
Can you please tell me where I did wrong ?

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