Serial communication; read function hangs

I’m trying to retrieve data from the /dev/ttyO2 buffer, and my program works exactly half of the time. The first time I run it from terminal, it hangs on the read function. I then press CTRL+Z to kill it, then I run it again, and it works. Run it a third time, it hangs as it did the first time. Rinse, repeat.

Observing the buffer in minicom, I noticed that every time it hangs, the data shows up on minicom; every time it works, I don’t see it on minicom and the data is properly processed.

If I try Canonical mode instead of Non-Canonical mode then I end up losing a few bytes of data (the ones that haven’t arrived yet).

I understand that in Non-Canonical mode, the read() function hangs because it’s being blocked from going through until it gets something. My question is why does this happen if the data arrives, as shown in the garbage screen? How can I get it to work ALL of the time? The code in question is below:

`

int readSensor(){
        struct termios UM6;
        char byte_in[ARRAY_SIZE];
        short int fd, bytes_read, checksum1 = 0, checksum0 = 0;
        short int phi_in = 0, theta_in = 0, psi_in = 0;
        unsigned int checksum = 0;
        unsigned long bytes_sum = 0;
        if ((fd = open("/dev/ttyO2", O_RDWR | O_NOCTTY)) < 0){
             return false;
        }
        if (tcgetattr(fd, &UM6) != 0){ //Obtain current terminal device settings in order to modify them at a later time.
             return -1;
        }
        if (cfsetispeed(&UM6, B115200) < 0){
             return -1;
        }
//No parity, 1 stop bit.
        UM6.c_iflag = 0;
        UM6.c_oflag = 0;
//       UM6.c_lflag |= ICANON;
//       UM6.c_cflag |= (CS8 | CREAD);
  *     * UM6.c_cc[VMIN] = 1; //Minimum # of bytes to appear in the receiver buffer before reading.
        UM6.c_cc[VTIME] = 0;
        tcsetattr(fd, TCSANOW, &UM6); //Set newly-modified attributes
        bytes_read = read(fd, byte_in, ARRAY_SIZE); //Program hangs HERE.
        if (bytes_read == -1){
                cout << "Read error." << endl;
                close(fd);
                return -1;
        }
        else if (bytes_read == 0) {
                close(fd);
                cout << "Nothing read." << endl;
                return 0;
        }
        close(fd);
}

`

I should also include that i’m using the following header files:

#include <termios.h> #include <fcntl.h> #include <unistd.h>