Interfacing Java and Arduino

Juraj:
you use BufferedReader which reads all available bytes into a memory buffer.
then you read 2 bytes from it into a buffer with length 2.

Thank you for putting some flesh on the bones of my Reply #17.

I have been assuming the OP knows how to write Java code.

...R

What I am doing is essentially porting my Perl code to Java. In perl I use a function called purge_all and look_clear which clears the input and output RX/TX streams and I don't have this issue....however javas serialPort functions are done a little bit differently. Yes I've used a "Ready Message" in perl and wait a few seconds before sending and receiving data. In Java in the thread portion of the code I wait for 3 seconds before sending and receiving data. I tried increasing the time and still nothing.

PilotinControl:
What I am doing is essentially porting my Perl code to Java.

This is neither a Perl nor a Java Forum.

I have told you how to solve this problem. You need to seek advice on a Java Forum about how to implement my advice.

Or just use Python (rather than Java) and use the code I gave you earlier.

...R

Ok so I was able to get it working using the following code:

// JAVA CODE

if(comPort.isOpen() == false) {	
					try {
						//Open the USB port and initialize the PrintWriter.
						comPort.openPort(1000);
						comPort.clearDTR();
						comPort.clearRTS();
						Thread.sleep(10000);
						outPut = new PrintWriter(comPort.getOutputStream(), true);
						inPut = comPort.getInputStream();
						comPort.getOutputStream().flush();
					String line = t.nextLine();
					if(line.equals("CONNECTED")) { // MESSAGE FROM ARDUINO ON STARTUP
					System.out.println("MESSAGE RECEIVED:" +line);
					outPut.flush();
					} else {
					System.out.println("ERROR...CLOSING PORT...SHUTTING DOWN...EXITING PROGRAM!!");
					comPort.closePort();
					System.exit(0);
					}

And here is the setup code from the Arduino setup() section:

// SETUP
void setup() {
//Start the serial port at 9600 baud rate.
delay(5000);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
//Set pin 13 for output.
pinMode(13, OUTPUT);
Serial.println("CONNECTED"); // MESSAGE SENT TO JAVA
}

I am having an issue now sending messages from other parts of the JAVA code....the messages get sent as I can see the input from the windows console and serial monitor in the IDE...however the correct message isn't being read. I don't think the InputStream isn't being flushed/purged correctly. Is there a way I can do this on the Arduino side? Thanks for the insight

why do you flush the output in Java if you didn't write to it?

To get rid of any stale date left behind? Or doesn't that really matter?

PilotinControl:
To get rid of any stale date left behind? Or doesn't that really matter?

I doubt that comPort.getOutputStream().flush() after open does something, but calling it again over a fresh PrintWriter object is for nothing