如何在linux上使用cfsetispeed和tcsetattr命令将端口的波特率配置为9600?

如何在linux上使用cfsetispeed和tcsetattr命令将端口的波特率配置为9600?

问题描述:

我现在正在使用下面的代码,我想知道它错在哪里。如何在linux上使用cfsetispeed和tcsetattr命令将端口的波特率配置为9600?

struct termios options; 
int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY); 
fcntl(fd, F_SETFL, 0); 
tcgetattr(fd, &options); 
cfsetispeed(&options, B9600); 
tcsetattr(fd, TCSANOW, &options); 

你可以试试下面的代码,看看它是否有帮助吗?

int open_port(void) 
{ 
    int fd; 

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY); 
if (fd == -1) 
{ 
    perror("open_port: Unable to open /dev/ttyS0 - "); 
} 
else 
    fcntl(fd, F_SETFL, 0); 

struct termios options; 

tcgetattr(fd, &options); 

cfsetispeed(&options, B9600); 
cfsetospeed(&options, B9600); 

tcsetattr(fd, TCSANOW, &options); 

return (fd); 
} 
+0

是的,这是一个错字。我更新了它。 – Cacheing 2013-03-03 20:43:06

+0

你认为代码是正确的吗?我只是不确定它是否正确... – Cacheing 2013-03-03 20:45:04

+0

您需要检查每个命令的返回代码,以查看哪个失败。 – 2013-03-03 20:53:46