我在设置串口参数时遇到困难。
程序在同一设备上运行良好,留下以下 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/