Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@peterhurley

peterhurley Jul 10, 2015

Can you add a simple license statement to the comment?

peterhurley commented Jul 10, 2015

Can you add a simple license statement to the comment?

@robs8899

This comment has been minimized.

Show comment
Hide comment
@robs8899

robs8899 May 16, 2016

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.

robs8899 commented May 16, 2016

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

This comment has been minimized.

Show comment
Hide comment
@npatil15

npatil15 Jun 29, 2016

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 ?

npatil15 commented Jun 29, 2016

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