c - 设置串口参数

标签 c linux serial-port

我在设置串口参数时遇到困难。
程序在同一设备上运行良好,留下以下 stty 输出:

$ stty -a -F /dev/ttyUSB0  
speed 1200 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>;     swtch = <undef>; start = ^Q;
stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 0; time =     0;
-parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts
ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl noflsh -xcase -tostop -echoprt -echoctl -echoke

我的尝试是这样的:

tcgetattr(fd, &options);

cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~( ICANON | ECHO | ECHOE |ISIG );
options.c_iflag &= ~(IXON | IXOFF | IXANY );
options.c_iflag |= IGNBRK;
options.c_oflag |= ONLCR;

options.c_oflag &= ~(OCRNL|ONLRET|NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);

tcsetattr(fd, TCSANOW, &options);

我尝试过设置 B1200 和 B9600 的速度,但这不起作用(手册中说应该是 B9600)

这个选项有什么问题?

最佳答案

stty 设置似乎适用于 raw 模式,而您的 tcgetattr()/tcsetattr()代码尝试使用非规范模式,但输出处理不完整(OPOST 未清除)。
结果是串口处于half-raw模式进行输出。

尝试使用cfmakeraw()设置非规范模式。

cfmakeraw() sets the terminal to something like the "raw" mode of the old Version 7 terminal driver: input is available character by character, echoing is disabled, and all special processing of terminal input and output characters is disabled. The terminal attributes are set as follows:

termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
            | INLCR | IGNCR | ICRNL | IXON);
termios_p->c_oflag &= ~OPOST;
termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios_p->c_cflag &= ~(CSIZE | PARENB);
termios_p->c_cflag |= CS8;

有关工作示例代码,请参阅 this .
请注意,会检查初始化期间系统调用的返回代码

关于c - 设置串口参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14456137/

相关文章:

c - 有没有办法在 while 或 for 循环中交换数学运算符?

c - 如何使C程序运行得更快?

linux - 如何从 CD-ROM 上刻录数据

serial-port - C中使用termios的Raspberry Pi UART程序接收垃圾(Rx和Tx直接连接)

java - 获取组合序列索引

c - 矩阵定义,添加两个不同数据类型的矩阵

c++ - 细粒度 nanosleep 在 Linux 上的 C++ 程序中效率不高

Java 1.8 安全点超时

C++ 将字节写入串行流

linux - 从 Windows 或 Linux 编译的 Arduino sketch 表现不同