• Increase font size
  • Default font size
  • Decrease font size
  • default color
  • cyan color
  • red color

Arduino.TW樂園

Member Area
RS232 Example Using JAVA
站長Blog文章單元 - 程式語法類(arduino basic, arduinoTW language)
作者是 xlinx   
週三, 28 七月 2010 13:04

使用Java讀取rs232範例

  • 基本javaComm用法 (easy)
  • 傾聽者Java Observer (not easy)
  • 反射機制Java Reflection (not easy)

相關連結:[eclipse][RXTX]

Above SourceCode:[link]

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

public class MainClass implements Runnable, SerialPortEventListener {
  static CommPortIdentifier portId;

  static Enumeration portList;

  InputStream inputStream;

  SerialPort serialPort;

  Thread readThread;

  public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        // if (portId.getName().equals("COM1")) {
        if (portId.getName().equals("/dev/tty.usbserial-A9007KyX")) {
          MainClass reader = new MainClass();
        }
      }
    }
  }

  public MainClass() {
    try {
      serialPort = (SerialPort) portId.open("MainClassApp", 2000);
    } catch (PortInUseException e) {
    }
    try {
      inputStream = serialPort.getInputStream();
    } catch (IOException e) {
    }
    try {
      serialPort.addEventListener(this);
    } catch (TooManyListenersException e) {
    }
    serialPort.notifyOnDataAvailable(true);
    try {
      serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
          SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {
    }
    readThread = new Thread(this);
    readThread.start();
  }

  public void run() {
    try {
      Thread.sleep(20000);
    } catch (InterruptedException e) {
    }
  }

  public void serialEvent(SerialPortEvent event) {
    switch (event.getEventType()) {
    case SerialPortEvent.BI:
    case SerialPortEvent.OE:
    case SerialPortEvent.FE:
    case SerialPortEvent.PE:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
      break;
    case SerialPortEvent.DATA_AVAILABLE:
      byte[] readBuffer = new byte[20];

      try {
        while (inputStream.available() > 0) {
          int numBytes = inputStream.read(readBuffer);
        }
//        System.out.print(readBuffer);
        System.out.print(new String(readBuffer));
      } catch (IOException e) {
      }
      break;
    }
  }
}

blog comments powered by Disqus
最近更新在 週三, 28 七月 2010 13:23