我做的代码来读取串口ports.The问题字节流的是我不能因为我没有与这些端口进行交互的设备,以测试代码..测试Java串行端口程序
我已经使用模拟器但上运行的代码和仿真器什么happens.There没有进步,没有错误。
下面是代码
class SimpleRead implements Runnable, SerialPortEventListener{
CommPortIdentifier portId;
Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
/**
* Method declaration
*
*
* @param args
*
* @see
*/
public void main(String[] args) {
boolean portFound = false;
String defaultPort = "/dev/term/a";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
jTextArea1.setText("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
jTextArea1.setText("port " + defaultPort + " not found.");
}
}
/**
* Constructor declaration
*
*
* @see
*/
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 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();
}
/**
* Method declaration
*
*
* @see
*/
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
/**
* Method declaration
*
*
* @param event
*
* @see
*/
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);
}
jTextArea1.setText(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
注:我使用javax.comm和NetBeans IDE。 谢谢
直到你有实际设备的可能性不大,我们可以帮助你。在提出这个问题之前,我不得不因此而无法进行所需的研究。 – 2012-08-16 12:26:33