Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a custom baud rate on Linux?

I want to communicate over my serial port on Linux to a device with a non-standard-baud rate that is not defined in termios.h.

I tried the "baud rate aliasing"-method from this post, but when I execute my C-program (I’ve named it "testprogram"), Linux says "testprogram sets custom speed on ttyS0. This is deprecated."

I did some search on Google, and it seems that there is another (newer?) method to change the baud rate to a non-standard-value: On http://sourceware.org/ml/libc-help/2009-06/msg00016.html the author says that the c_flag of struct termios must be OR’d with BOTHER (=CBAUDEX | B0).

With this method the baud rates are set directly in the c_ispeed and c_ospeed-members of the struct termios. However, I don’t know how I use this method in my C program. Like the author said, there is no BOTHER defined/available when I include termios.h, so what should be done to set the baud rate this way?

How can I set the baud rate to a non-standard-value without changing the kernel?

like image 589
Felix Avatar asked Sep 28 '12 19:09

Felix


People also ask

How do I set baud rate?

If the port number is not specified, the baud rate is set on the current port. A -1 can also be specified to indicate the current port. The baud rate can be one of these supported baud rates: 110, 150, 300, 600, 1200, 2400, 4800, 9600, 19200. The default baud rate for each port is 9600.

How do you increase your baud rate?

There are many ways one can cause timer 1 to overflow at a rate that determines a baud rate, but the most common method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set a reload value (TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.


1 Answers

I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>. Just a forewarning, I think I ran into problems including both it and the regular <termios.h> file at the same time.

Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>:

struct termios2 tio;  ioctl(fd, TCGETS2, &tio); tio.c_cflag &= ~CBAUD; tio.c_cflag |= BOTHER; tio.c_ispeed = 12345; tio.c_ospeed = 12345; ioctl(fd, TCSETS2, &tio); 
like image 143
dougg3 Avatar answered Oct 03 '22 00:10

dougg3