1

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


Arduino 读取它从 ALGE 获得的输入信号并将其连续传输到串行端口。当梁未被切割时,这些值在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 {
        }

    }


我在哪里做错了?

4

0 回答 0