从Java中的串行端口获取错误的值

时间:2013-09-11 12:50:41

标签: java serial-port arduino rxtx

我正在尝试通过ALGE-TIMING读取连接到串口的Arduino设备的值。


Arduino从AL​​GE读取输入信号并连续发送到串口。当光束未被切割时,这些值在 10-30 的范围内。当光束被切断时,它发送 0
我可以在Arduino的串行监视器中看到这个值但是当我尝试通过Java读取这个值时,即使没有任何光束切换,我也会得到随机0。

以下是我正在做的事情:

    static final String PORT_NAME = "COM10"; 
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 9600;  


    public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAME.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
                if (currPortId.getName().equals(PORT_NAME)) {
                    portId = currPortId;
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            }

            try {
                serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
                serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                is = serialPort.getInputStream();

                //console = System.console();
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
                //serialPort.enableReceiveTimeout(500);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
@Override
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            int val = 111;
            try {
                Scanner sc = new Scanner(serialPort.getInputStream());
                if (sc.hasNext()) {
                    val = Integer.parseInt(sc.next()); //sc.nextInt() didn't solved the problem either
                    cRead(val);
                }
            } catch (Exception e) {
                System.err.println(e.toString());
                System.out.println("Error reading");
            }
        }

    }

    public synchronized void cRead(int data) {
        if (data == 0) {
            System.out.println(data);
            getTimestamp(); // Returns String
        } else {
        }

    }


我在哪里做错了?

0 个答案:

没有答案