I am using the JSSC class to receive a string from an Arduino Uno. The Arduino is connected to my computer via COM3. In the setup void on the Arduino, it sends a string to the java program saying that the Arduino is ready to read serial data. What happens is when the java program reads the serial port, it splits up the string from the Arduino onto multiple lines with spaces. I imagine it is that java program is printing the data when its received instead of waiting for the full string. How could I make it so that the program reads the string from the Arduino and saves it to a string and then prints it to console.
Java:
package jtac;
import jssc.*;
public class JTAC {
public static SerialPort serialPort = new SerialPort("COM3");
public static PortReader portreader = new PortReader(serialPort);
public static boolean ready = false;
public static void main(String[] args) {
try {
serialPort.openPort();//Open serial port
//Thread.sleep(2000);
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
serialPort.addEventListener(portreader, SerialPort.MASK_RXCHAR);
while(!ready) {} //Wait for Arduino to fire up
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
class PortReader implements SerialPortEventListener {
SerialPort serialPort;
public PortReader(SerialPort serialPort) {
this.serialPort = serialPort;
}
@Override
public void serialEvent(SerialPortEvent event) {
if (event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = serialPort.readString(event.getEventValue());
System.out.println(receivedData);
if(receivedData == "Arduino Ready") JTAC.ready = true;
} catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}
}
Arduino:
String input;
void setup() {
Serial.begin(9600);
Serial.print("Arduino Ready");
}
void loop() {
}
This is what the console outputs:
Ard
uino
Rea
dy
The spaces in front of Ard couldn't be copied from the console output. Is there a way I could make this all on one line? I might need to receive data from the Arduino again in the future as well. Thanks.