我试图在Linux系统上编写c代码,在这里我设置了串口参数,然后打开了串口,然后我发现即使代码编译和运行,我也不能从该串口读写(所以串口没有被成功打开)!
有效的代码(不需要):
int fd;
char *portname;
portname = "/dev/ttyUSB0";
struct termios tty;
fd = open(portname, O_RDWR | O_NOCTYY | O_SYNC );
memset(&tty,0,sizeof tty);
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOP;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS;
tcsetattr(fd,TCSANOW,&tty);不工作的代码(需要)
int fd;
char *portname;
portname = "/dev/ttyUSB0";
struct termios tty;
memset(&tty,0,sizeof tty);
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOP;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS;
tcsetattr(fd,TCSANOW,&tty);
fd = open(portname, O_RDWR | O_NOCTYY | O_SYNC );实心问题:我的应用程序顺序要求我设置串口参数,然后打开串口。有办法这样做吗?如果是,怎么做?
谢谢你的帮助。
发布于 2014-06-20 09:50:00
更新:@Alter注意到的删除C++代码。
更新:移除了@锯末注意到的termios结构。
在第一种情况下,您将得到实际的文件描述符fd,然后使用它。在第二种情况下,您尝试设置未初始化的文件描述符 fd (如果在全局范围中声明,则可能是0 ),并在获得它的实际值之后进行设置。
下面是适合我的解决办法:
#include <fcntl.h>
#include <termios.h>
#include <strings.h>
#include <stdlib.h>
int main (int argc, char * argv [])
{
struct termios tty;
const char * portname = "/dev/ttyUSB0";
const int fd = open (portname, O_RDONLY);
if (-1 == fd) {
// Problem...
return EXIT_FAILURE;
}
if (tcgetattr (fd, &tty) < 0) {
// Problem...
return EXIT_FAILURE;
}
cfsetospeed (&tty, (speed_t) B9600);
cfsetispeed (&tty, (speed_t) B9600);
tty.c_cflag |= B9600;
tty.c_cflag |= (tty.c_cflag & ~CSIZE) | CS8;
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~(PARENB | PARODD);
tty.c_cflag |= IGNPAR;
tty.c_cflag &= ~(CRTSCTS);
tty.c_cflag &= ~(CSTOPB);
tty.c_iflag |= IGNBRK;
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_lflag = 0;
tty.c_oflag = 0;
tcflush (fd, TCIFLUSH);
if (tcsetattr (fd, TCSANOW, &tty) ) {
// Problem...
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}https://stackoverflow.com/questions/24324338
复制相似问题