Serial connection (Arduino & # 8594; Java)

This will be my first post, and I will do my best to be clear and concise. I checked some other posts on this forum, but could not find a satisfactory answer.

My question relates to the use of the JavaFX library and jSSC (java simple serial connection). I developed a very simple graphics application that will contain four different graphics. Two of the charts will display readings from temperature and sun sensors for the last hour, while the other two display data over a long period - a 14-hour period. In the end, I would like to make it more flexible and set the application to "sleep" when the readings become approximately zero (night).

How can I transfer data to display this data in real time?

After linking to several sources on the Internet and from "JavaFX 8 Intro. By Example", I was able to build most of the serial connection class. I am having problems processing the data so that it can be displayed on a chart.

public class SerialComm  implements SerialPortEventListener {
Date time = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("mm");

boolean connected;
StringBuilder sb;
private SerialPort serialPort;

final StringProperty line = new SimpleStringProperty("");

//Not sure this is necessary
private static final String [] PORT_NAMES = {
    "/dev/tty.usbmodem1411", // Mac OS X
    "COM11", // Windows
};
//Baud rate of communication transfer with serial device
public static final int DATA_RATE = 9600;

//Create a connection with the serial device
public boolean connect() {
    String [] ports = SerialPortList.getPortNames();
    //First, Find an instance of serial port as set in PORT_NAMES.
    for (String port : ports) {
         System.out.print("Ports: " + port);
         serialPort = new SerialPort(port);
    }
    if (serialPort == null) {
        System.out.println("Could not find device.");
        return false;
    }

    //Operation to perform is port is found
    try {
        // open serial port
        if(serialPort.openPort()) {
             System.out.println("Connected");
        // set port parameters
        serialPort.setParams(DATA_RATE,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
                serialPort.setEventsMask(SerialPort.MASK_RXCHAR);

        serialPort.addEventListener(event -> {
            if(event.isRXCHAR()) {
                try {
                    sb.append(serialPort.readString(event.getEventValue()));
                    String str = sb.toString();
                    if(str.endsWith("\r\n")) {
                            line.set(Long.toString(time.getTime()).concat(":").concat(
                                    str.substring(0, str.indexOf("\r\n"))));
                                                System.out.println("line" + line);

                        sb = new StringBuilder();
                    }
                } catch (SerialPortException ex) {
                    Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);                    }
            }            
        });
    }                          
} catch (Exception e) {
    System.out.println("ErrOr");
    e.printStackTrace();
        System.err.println(e.toString());
    }       
    return serialPort != null;
}

@Override
public void serialEvent(SerialPortEvent spe) {
    throw new UnsupportedOperationException("Not supported yet."); 
}

public StringProperty getLine() {
    return line;
}

}

In the try block, I understand the parameters of the port, but eventListener is where I am having difficulty. The value of stringbuilder is to add data to new data as it is read from the device. How will I account for two sensor readings? Can I do this by creating separate data rates to distinguish between incoming data from each sensor?

I hope this is clear and that I have provided enough information, but not too much. Thanks for any help.

------------------------------- UPDATE --------------- -----------

Jose, . JavaFX, . NullPointerException, , , [], SerialCommunication.

serialPort.addEventListener(event -> {
            if(event.isRXCHAR()) {
                try {
                    sb.append(serialPort.readString(event.getEventValue()));
                    String str = sb.toString();

                    if(str.endsWith("\r\n")) {
                            line.set(Long.toString(time.getTime()).concat(":").concat(
                                    str.substring(0, str.indexOf("\r\n"))));
                                                System.out.println("line" + line);
                        sb = new StringBuilder();
                    }
                } catch (SerialPortException ex) {
                    Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }            
        });
    }                          
} catch (Exception e) {
        System.err.println(e.toString());
    }       

. , arduino, : Serial.print( "Solar:" ); Serial.println(solarData);

JavaFx:

serialPort.getLine().addListener((ov, t, t1) -> {
        Platform.runLater(()-> {
            String [] data = t1.split(":");

            try {
                 //data[0] is the timestamp
                //data[1] will contain the label printed by arduino "Solar: data"

                switch (data[1]) {
                    case "Solar":
                        data[0].replace("Solar:" , "");
                        solarSeries.getData().add(new XYChart.Data(data[0], data[1]));
                        break;
                    case "Temperature":
                        temperatureSeries.getData().add(new XYChart.Data(data[0], data[1]));
                        break;
                }

, NullPointerException, String [] ?

:/dev/tty.usbmodem1411Connected "EventThread/dev/tty.usbmodem1411" java.lang.NullPointerException    SerialComm.lambda $connect $0 (SerialComm.java:61)    SerialComm $$ Lambda $1/1661773475.serialEvent( )    jssc.SerialPort $LinuxEventThread.run(SerialPort.java:1299)

+4
2

SerialPortEventListener, jssc, . RXCHAR, , Arduino , .

event.getEventValue() int , serialPort.readString(event.getEventValue()) String .

, , . "\r\n", reset StringBuilder :

sb.append(serialPort.readString(event.getEventValue()));
String str=sb.toString();
if(str.endsWith("\r\n")){
    line.set(str.substring(0,str.indexOf("\r\n")));
    sb=new StringBuilder();
}

line String:

final StringProperty line=new SimpleStringProperty("");

Arduino, , Arduino , .

, , :

ID1,val1
ID1,val2
ID2,val3
ID1,val4
ID3,val5
...

, JavaFX line String, . - :

serial.getLine().addListener(
    (ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
    Platform.runLater(()->{
        String[] data=newValue.split("\\,");
        if(data[0].equals("ID1"){
            // add to chart from sensor 1, value data[1]; 
        } else if(data[0].equals("ID2"){
            // add to chart from sensor 2, value data[1]; 
        } else if(data[0].equals("ID3"){
            // add to chart from sensor 3, value data[1]; 
        }
    });        
});

, Platform.runLater(), , line, JavaFX.

+2

, Arduino, -, , Java, .

String[] stringSeparate = str.split(",");
0

All Articles