C程序在打开端口失败前设置端口参数

标签 c linux serial-port

我想在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 );

正题:我的应用程序序列需要设置串口参数,然后打开串口。有没有办法做到这一点?如果是,怎么办?

感谢您的帮助。

最佳答案

更新:删除了@Alter Mann 注意到的 C++ 代码。
更新:删除了由@sawdust 注意到的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;
}

关于C程序在打开端口失败前设置端口参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24324338/

相关文章:

在 C 中创建通用链表

java - 为什么我不能远程调试?我怎样才能找出原因?

r - 在 R foreach() 下并行运行时无法识别动态库依赖项

Linux 中的 Java - root 用户和非 root 用户的不同外观类

c++ - 通过 RS232 串行端口从条码扫描器读取异步数据

C中创建shell,execv()无法执行大部分命令

c - 临时 C 字符串具有相同的地址

c - 移位扩展 ASCII 码

Python串口监听器

c - 串行端口输入缓冲区的字节数