Setting non-standard baud rate to Serial Port
Using stty, we can only set standard baud rates such as 9600, 19200, 38400, 57600 and so on using the following command:
stty -F /dev/ttyUSB0 115200
stty does not allow us to set non-standard baud rate , for example 7667.
stty -F /dev/ttyUSB0 7667
We will get the following error: "stty: invalid argument '7667'
We can set a custom baud rate using new style termios2 struct with setting BOTHER flag in c_flag member of termios2 struct.
Sample Code for setting custom baud rate
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <asm/termios.h>
int main()
{
int fd, ret;
struct termios2 config;
fd = open("/dev/ttyUSB0", O_RDWR);
if (fd < 0)
printf("Failed to open /dev/ttyUSB0 - fd = %d\n", fd);
// Set custom buad rate
ret = ioctl(fd, TCGETS2, &config);
if (!ret) {
config.c_cflag &= ~CBAUD;
config.c_cflag |= BOTHER;
config.c_ispeed = 7667;
config.c_ospeed = 7667;
ret = ioctl(fd, TCSETS2, &config);
}
close(fd);
return ret;
}
Comments
Post a Comment