farry

Linux set arbitrary baud rate

Oct 29th, 2018
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.85 KB | None | 0 0
  1. /*
  2.  * Set arbitrary baud rate for the serial device on Linux
  3.  * because stty etc only allows you to set predefined values.
  4.  */
  5. #include <stdio.h>
  6. #include <fcntl.h>
  7. #include <errno.h>
  8. #include <asm/termios.h>
  9.  
  10. int main(int argc, char* argv[]) {
  11.  
  12.     if (argc != 3) {
  13.         printf("%s device speed\n\nSet speed for a serial device.\nFor instance:\n    %s /dev/ttyUSB0 75000\n", argv[0], argv[0]);                  
  14.         return -1;
  15.     }
  16.  
  17.     int fd = open(argv[1], O_RDONLY);
  18.  
  19.     int speed = atoi(argv[2]);
  20.  
  21.     struct termios2 tio;
  22.     ioctl(fd, TCGETS2, &tio);
  23.     tio.c_cflag &= ~CBAUD;
  24.     tio.c_cflag |= BOTHER;
  25.     tio.c_ispeed = speed;
  26.     tio.c_ospeed = speed;
  27.     int r = ioctl(fd, TCSETS2, &tio);
  28.     close(fd);
  29.  
  30.     if (r == 0) {
  31.         printf("Changed successfully.\n");
  32.     } else {
  33.         perror("ioctl");
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment