如何在Linux上设置自定义波特率? [英] How can I set a custom baud rate on Linux?
问题描述
我想通过Linux上的串行端口与termios.h
中未定义的非标准波特率的设备进行通信.
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
.
我尝试了这篇文章中的波特率别名"方法,但是当我执行C程序时(我将其命名为"testprogram"),Linux说"testprogram sets custom speed on ttyS0. This is deprecated."
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."
我在Google上进行了一些搜索,看来还有另一种(较新的)方法可以将波特率更改为非标准值:在
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)
.
使用这种方法,可以直接在struct termios
的c_ispeed
和c_ospeed
成员中设置波特率.但是,我不知道如何在C程序中使用此方法.就像作者所说的那样,当我包含termios.h
时,没有定义/c8,所以应该怎么设置这种波特率呢?
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?
推荐答案
我注意到未定义BOTHER的同一件事.就像Jamey Sharp所说的那样,您可以在<asm/termios.h>
中找到它.只是一个警告,我想我同时遇到了包括它和常规<termios.h>
文件的问题.
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.
除此之外,我发现我拥有的glibc仍然无法正常工作,因为glibc的tcsetattr正在为旧版本的struct termios做ioctl,而后者不注意速度设置.我可以通过使用新样式termios2结构手动执行ioctl来设置自定义速度,也可以通过包含<asm/termios.h>
:
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);
这篇关于如何在Linux上设置自定义波特率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!