Arduino串口通信

时间:2017-10-03 06:53:50

标签: java database arduino

我正在尝试建立Java-Arduino串行通信。所以我下载了谷歌搜索的源代码。但我无法将正确的数据从Arduino发送到数据库(MySQL)。

public class Serial implements SerialPortEventListener {
  SerialPort serialPort;
  private static final String PORT_NAMES[] = {
    "/dev/tty.usbserial-A9007UX1", // Mac OS X
    "/dev/ttyUSB0", // Linux
    "COM3", // Windows
  };

  private InputStream input;
  private OutputStream output;
  private static final int TIME_OUT = 2000;
  private static final int DATA_RATE = 9600;

  public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
          portId = currPortId;
          break;
        }
      }
    }

    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);
      input = serialPort.getInputStream();
      output = serialPort.getOutputStream();
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }

  public synchronized void close() {
    if (serialPort != null) {
      serialPort.removeEventListener();
      serialPort.close();
    }
  }

  public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
      try {
        int available = input.available();
        byte chunk[] = new byte[available];
        input.read(chunk, 0, available);
        // print to console
        System.out.print(new String(chunk));
        Frequency frequnecy = new Frequency();
        FrequencyDAO frequencyDAO = new FrequencyDAO();
        frequencyDAO.insertFrequency(new String(chunk));
      } catch (Exception e) {
        System.err.println(e.toString());
      }
    }
  }
}

我得到的输出:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您想要将字段input的类型更改为BufferedReader 并初始化它像:

input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

使用缓冲的阅读器,您可以一次读取一行,我认为,您想要在数据库中存储的内容。

然后相应地更新事件处理程序:

public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String line = input.readLine();
            System.out.println(line);

            FrequencyDAO frequencyDAO = new FrequencyDAO();
            frequencyDAO.insertFrequency(line);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
}