How to store data coming from Arduino in a Java string?

3

I need to store data coming from Arduino on Java via serial communication only that the values sometimes not completely filled. 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 

Do Arduino send data so @678& , But sometimes Java stores @6, 7, 8&, etc or it will take only one piece.

    
asked by anonymous 02.04.2017 / 14:07

1 answer

1

The biggest problem in this case is not getting the data coming from the Arduino but rather how to better control the flow of serial communication. Is the system critical enough that it can not wait 1s to forward the next data? It is important to know that it has to be the most realistic possible time to think about energy consumption as well.

  • If yes, concatenate the inputs sent by Arduino

Note that the data is getting "lost" because while Java is processing the Arduino is submitting a lot of data, and this will do more processing.

In this case you need start and end markers to know when the information has come to an end. Assuming that "@" and "&" are its marking 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.
05.04.2017 / 16:40