steven
steven

Reputation: 15

serial communication write() doesn't work always

I have a problem that I can't seem to figure out :

I have a serial communication through Bluetooth between my RPi and my PC with Putty. I use the following code to send text from my RPi to Putty :

ssize_t serial::writeSerialPort(char const *string)
{
    /*
     write a string to the serial connection
     */

    ssize_t result = write(fd, string, strlen(string));

    tcflush(fd, TCOFLUSH);
    if (result != strlen(string))
        printf("Failed to write to serial port!\n");
    else
        printf("Wrote to serial port!\n");

    return result;
}

The strange thing now is that sometimes the text is being send to Putty and that works a while. Then suddenly it stops working, after a while it starts working again (all in the same session).

When I set a breakpoint and debug my code the text is always being outputted right after the write() function (before the tcflush() ).

This of course makes it hard to find out why I have this "bug".

The result is always equal to strlen(string) so I'm pretty sure that it was correctly written. Anyone that can point me in the right direction?

Upvotes: 0

Views: 538

Answers (1)

I am not sure what you want to achieve by tcflush(fd, TCOFLUSH);. That function call specifically discards - i.e. puts into trash can - all data written to fd, but not yet sent over the serial link.

Quoting Linux manuals:

tcflush() discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of queue_selector:

  • TCOFLUSH

    flushes data written but not transmitted.


Perhaps you wanted to use tcdrain() instead:

tcdrain() waits until all output written to the object referred to by fd has been transmitted.

Upvotes: 2

Related Questions