package application; import jssc.SerialPort; import jssc.SerialPortEvent; import jssc.SerialPortEventListener; import jssc.SerialPortException; import java.io.IOException; public class SerialReader { static SerialPort serialPort; static double temp; public static double getTemp() { return temp; } public static void Listener() { try { serialPort = new SerialPort("COM3"); serialPort.openPort(); // Låt stå eller är redan satt i enhetshanteraren? serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR); } catch (SerialPortException ex) { System.out.println("There is an error here " + ex); } } private static class PortReader implements SerialPortEventListener { @Override public void serialEvent(SerialPortEvent event) { if (event.isRXCHAR() && event.getEventValue() > 0) { try { int[] receivedData = serialPort.readIntArray(event.getEventValue()); if (receivedData.length == 2) { System.out.println(receivedData[0] + " " + receivedData[1]); int temp1 = (receivedData[0] << 8) + receivedData[1]; // read System.out.println(temp1); // serial // port temp = 5 * (double) temp1 / 1023; // Converts AD value to voltage temp = temp * 100 - 273.0; // Voltage is 100*equal to // temp in kelvin, convert // to celsius System.out.println("Received response: " + temp + " " + receivedData.length); } else { System.out.println("fail"); } } catch (SerialPortException ex) { System.out.println("Error in receiving string from COM-port: " + ex); } } } } }