I am sending data through a serial port and am having a couple of problems. I have read the serial and serial programming HOWTOs.
My application basically sends data in Buffer (byte*) using the following code:
BytesLeft = BufLen;
TxCount = write(handle, Buffer, BytesLeft);
if(TxCount >= 0)
BytesLeft -= TxCount;
printf("TXStr error: %d\r\n", TxCount);
}while (BytesLeft > 0);
I use the while loop to ensure that all characters are sent; if write() returns less than BufLen, it sends the rest. This may be unnecessary.
This code works, but I'm having a problem if I call my send function too frequently. If I call the function twice in succession, write returns -1. Adding a sleep(1) before the while prevents the error, but I'd appreciate a more viable fix.
I have noticed from serial libraries on places such as Sourceforge.net that the while loop is not used, so my first question is "is the while loop necessary". if not, is there any need to monitor the return value from write() other than to catch the error condition?
My second question is regarding the sleep I need to add. It seems that there is some buffer still being written to after the write() has returned, and if I try to write again too soon, I get an error. is there anything I can check to see whether the port is ready to be written to?