2
I have a java app that reads on the serial port with 7 data from a rotational sensor coming from the Arduino, via jssc. The code works, but the data is not formatted. I read 4 in 4 bytes, but sometimes comes numbers like 0080, 8000, etc. I need to leave the output formatted, how can I do this? Follows the code.
package tanio;
import java.io.UnsupportedEncodingException;
import javax.swing.SwingWorker;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class obterrpm extends SwingWorker{
protected Object doInBackground() throws Exception {
String[] portNames = SerialPortList.getPortNames();
for (String portName : portNames) {
// System.out.println(portName);
}
SerialPort serialPort = new SerialPort("COM7");
try {
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
//System.out.println("successfully writen to port: " + serialPort.writeBytes(new byte[]{0x04}));
while(true){
delay.delay(100);
byte[] buffer = serialPort.readBytes(4);//Read 10 bytes from serial port
String convertido = new String(buffer);
//System.out.println(convertido);
chamarTelaPrincipal.rpm.setText(String.format("%s",convertido));
// Runnable enviarResposta2 = new SocketRespostaRPM(convertido);
// new Thread(enviarResposta2).start();
}
//System.out.println("Port closed: " + serialPort.closePort());
} catch (SerialPortException ex) {
System.out.println(ex);
}
return null;
}
}
I saw no obvious error in your code. Maybe the error is in the communication. Have you tried using Javino? It allows a transmission between Arduino and Java with a full string of up to 256 characters. This can facilitate the way communication is done and your code, in addition it has send and receive message check so that it does not have lost or mixed data. I always use it in cases that I need Java-ATMEGA communication.
– Pantoja