Question

I am testing the sending and receiving programs with the code as

The main() function is below:

#include "lib.h"

int fd;

int initport(int fd) {
    struct termios options;
    // Get the current options for the port...
    tcgetattr(fd, &options);
    // Set the baud rates to 19200...
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    // Enable the receiver and set local mode...
    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    // Set the new options for the port...
    tcsetattr(fd, TCSANOW, &options);
    return 1;
}

int main(int argc, char **argv) {

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

    printf("baud=%d\n", getbaud(fd));
    initport(fd);
    printf("baud=%d\n", getbaud(fd));

    char sCmd[254];
    sCmd[0] = 0x41;
    sCmd[1] = 0x42;
    sCmd[2] = 0x43;
    sCmd[3] = 0x00;

    if (!writeport(fd, sCmd)) {
        printf("write failed\n");
        close(fd);
        return 1;
    }

    printf("written:%s\n", sCmd);

    usleep(500000);
    char sResult[254];
    fcntl(fd, F_SETFL, FNDELAY); 

    if (!readport(fd,sResult)) {
        printf("read failed\n");
        close(fd);
        return 1;
    }
    printf("readport=%s\n", sResult);
    close(fd);
    return 0;
}


The lib.h contains read and write code as at:

Parse and read data frame in C?

and got the issue:

In order to test with serial port, I used the socat (https://help.ubuntu.com/community/VirtualSerialPort ) to create a pair serial ports on Linux and test my program with these port.

The first time the program sends the data and the program receives data is ok. However, if I read again or even re-write the new data into the serial port, the return data is always null until I stop the virtual serial port and start it again, then the write and read data is ok, but still, only one time.

(In the real case, the sending part will be done by another device, I am just taking care of the reading data from the serial port. I wrote both parts just to test my reading code.)

Does anyone have any ideas?

Was it helpful?

Solution

Either your comment or your code is wrong:

// Set the baud rates to 19200... 
cfsetispeed(&options, B9600); 
cfsetospeed(&options, B9600); 

This says it will be setting the baud rate to 19200, but it really sets it to 9600. Maybe you want this:

// Set the baud rates to 19200... 
cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top