Hi everyone, maybe someone wrote another topic similar like this, but I didn't find.
The problem is that I'm trying to create a really communication between Arduino and Java through message passing, I mean, if I send with Java an string message, I would like to Arduino read the string and depend of the value, return the correct value. For example, if Java send "REQ" Arduino should return "Yes"; if Java send "VAL", Arduino should return "100", etc.
The problem is: If i realize experiment with Arduino serial monitor, this works perfectly, but if I did with java, doesn't work (for example If i send "REQ" and I would like to obtain String+"OK" from the board, Arduino return ROKEOKQOK,instead of REQOK.
My javacode for write and read to/from serial port is:
----READ---
public String read(){
String value="";
try {
while(inputStream.available()>0)
value+=(char)inputStream.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
--write---
public boolean write(String text){
try{
outputStream.write(text.getBytes());
}catch(IOException e){
return false;
}
return true;
}
Serial data transmission is relatively slow. You can read it much faster than it can be sent. Somehow, you need to tell the Arduino when a packet is complete. Send something like "REQ;" or "VAL:".
Then, on the Arduino, read, but don't print or append OK, all serial data until the end of packet marker ( ; ) is received.
mmm..ok..I get it..but now, I have to send two data packets to receive one "answer-data", I mean if I send port.write("REQ"); port.write("REQ"); I receive just one "REQ;OK" and if I send just one port.write("REQ") I don't receive any answer. I think I'm forgetting something....any idea?
I'm not a Java expert, but I'm wondering why you put the thread to sleep after sending the message. Does the receipt of serial data wake the thread? Does serial data get received while the thread is sleeping?
When happens if you send the message, then enter the do/while loop that waits for a reply, without sleeping?