I am stuck in a strange issue while reading data from serial port in Java.
I have to read data from serial port via a polling method in a thread which is working fine, but I have a requirement where I need to write data to a serial port and read ACK back. Writing data to the serial port is successful but I am not able to read data back. Here there are two read operations one in thread and one in main thread.
Once I receive serial write data I paused the thread which is reading data from the serial port using a flag and started reading data from serial port again once write is done, but I am not able to read data. I disabled reading serial port after write operation and enabled thread which reads serial port in thread, here I am seeing ACK data from serial port.
Can any suggest what is going on wrong with this serial read operation? It is not buffered read/write operation.
I strongly recommend using only one dedicated thread for accessing serial port reading. The most reliable solution used to be an interrupt handler shoveling all the received data to a threadsafe state machine. Trying to read the serial port from multiple threads calls for problems. Serial port IO doesn’t care that you “paused your thread”, the data can be already fetched in and lost due to context switch.
So simply keep reading what comes in and if ACK is expected and obtained, inform the main thread via semaphore. In a dirty brutally simplified pseudocode:
Main thread loop:
Serial reader thread loop:
You need to set
isAckExpectedbefore sending the write command, because if your serial peer is fast enough, you might get the response back before yoursendWriteCommandeven returns.