简体   繁体   中英

Can't set serial port configuration in Linux in C

I have writen some Linux program to comunicate my device. I have "same" my program for Windows ("same" because of it's same logic). I'm using 8N2 data frame format @ 9600 bps, with neither software (XOn/XOff) nor hardware (RTS/CTS) flow control. I don't use DTR, DCD, RI, DSR pins of RS-232 9-pin D-sub. I use only RX and TX pins to communicate with my device. In Linux I have this part of code:

 struct termios PortOpts, result;
 int fd; /* File descriptor for the port */

/* Configure Port */
 tcgetattr(fd, &PortOpts);
 // BaudRate - 9600
 cfsetispeed(&PortOpts, B9600);
 cfsetospeed(&PortOpts, B9600);
 // enable reciever and set local mode, frame format - 8N2, no H/W flow control
 PortOpts.c_cflag &= (~(CLOCAL | CREAD | CSIZE | CSTOPB));
 PortOpts.c_cflag |= ((CLOCAL | CREAD | CS8 | CSTOPB) & (~PARENB));
 PortOpts.c_cflag &= (~CRTSCTS);
// PortOpts.c_cflag &= ~PARENB
// PortOpts.c_cflag |= CSTOPB
// PortOpts.c_cflag &= ~CSIZE;
// PortOpts.c_cflag |= CS8;
 // no parity check, no software flow control on input
 PortOpts.c_iflag |= IGNPAR;
 PortOpts.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY | INPCK);
 // raw data input mode
 PortOpts.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
 // raw data output
 PortOpts.c_oflag &= ~OPOST;
 // setting timeouts
 PortOpts.c_cc[VMIN] = 1; // minimum number of chars to read in noncanonical (raw mode)
 PortOpts.c_cc[VTIME] = 5; // time in deciseconds to wait for data in noncanonical mode (raw mode)

 if (tcsetattr(fd, TCSANOW, &PortOpts) ==  0) {
    tcgetattr(fd, &result);
    if ( (result.c_cflag != PortOpts.c_cflag) ||
         (result.c_oflag != PortOpts.c_oflag) ||
         (result.c_iflag != PortOpts.c_iflag) ||
         (result.c_cc[VMIN] != PortOpts.c_cc[VMIN]) ||
         (result.c_cc[VTIME] != PortOpts.c_cc[VTIME]) ) {
        perror("While configuring port1");
        close(fd);
        return 1;
    }
 } else {
    perror("While configuring port2");
    close(fd);
    return 1;
 };

File descriptor 'fd' is for '/dev/ttyS0' device. I get that message: While configuring port2: Input/output error I have a laptop, though I don't have any serial ports except for USB. Is this a reason? I run program as 'root'.

Sorry for my broken English.

Can you run strace on the program; that will give more specifics of just where the IO error is occurring.

One thing to keep in mind - errno doesn't get reset, so the actual error could be from any system call before the perror.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM