Question:
I need to store data coming from Arduino
in Java
via serial communication but the values sometimes not filled in completely. I'm using the rxtx
library.
//trecho do código para leitura
int available = input.available();
byte chunk[] = new byte[available];
input.read(chunk, 0, available);
output.write(0);
output.flush();
String teste = new String(chunk);
System.out.println(teste);
close();//fecha comunicação serial
From Arduino
sends the data like this @678&
, But sometimes Java
stores like this @6, 7, 8&, etc
other words, it only takes a piece.
Answer:
The biggest problem in this case is not getting the data coming from Arduino, but how to better control the flow of serial communication. Is the system critical enough that it cannot wait 1s to forward the next data? It is important to know that it needs to be as real as possible to think about energy consumption as well.
- If yes, concatenate the inputs sent by Arduino
Note that the data is "losing" because while Java is processing Arduino is submitting a lot of data and this will do even more processing.
In this case, start and end markers are needed to know when the information has reached the end. Assuming "@" and "&" are your bullet characters:
int available = input.available();
byte chunk[] = new byte[available];
input.read(chunk, 0, available);
output.write(0);
output.flush();
String teste = new String(chunk);
String dado = "";
if("@".equals(teste)){
//Limpar lixo de dado anterior
dado = "";
}else if(teste.contains("@") && teste.contains("&")){
//Dado foi pego por completo
dado = teste;
}else{
if(teste.contains("@")){
dado += teste.replaceAll("@", "");
}else if("&".equals(teste)){
//Dado foi pego por completo.
//A partir daqui pode realizar operações como salvar no BD, tratar dado etc
}else if(teste.contains("&")){
dado += teste.replaceAll("&", "");
}
}
- If not, I suggest using the delay or sleep functions in the Arduino code