![](/img/trans.png)
[英]Reading from COM port in Java, Error 0x5 at ..\rxtx\src\termios.c(892)
[英]RXTX how to reading from com port
嗨,我有這樣的東西
package compot;
import java.util.Enumeration;
import gnu.io.*;
public class core {
private static SerialPort p;
/**
* @param args
*/
public static void main(String[] args)
{
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("start");
while(ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
System.out.print(port.getName() + " -> " + port.getCurrentOwner() + " -> ");
switch(port.getPortType())
{
case CommPortIdentifier.PORT_PARALLEL:
System.out.println("parell");
break;
case CommPortIdentifier.PORT_SERIAL:
//System.out.println("serial");
try {
p = (SerialPort) port.open("core", 1000);
int baudRate = 57600; // 57600bps
p.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (PortInUseException e) {
System.out.println(e.getMessage());
} catch (UnsupportedCommOperationException e) {
System.out.println(e.getMessage());
}
break;
}
}
System.out.println("stop");
}
}
但我不知道如何從端口讀取?? 我已經閱讀了本教程,但我不知道它們的“演示應用程序”是什么意思??
編輯
OutputStream outStream = p.getOutputStream();
InputStream inStream = p.getInputStream();
BufferedReader in = new BufferedReader( new InputStreamReader(inStream));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
我已經添加了這段代碼,但我收到了
穩定庫 =========================================== 原生庫版本 = RXTX-2.1 -7 Java lib Version = RXTX-2.1-7 start /dev/ttyUSB3 -> null -> 底層輸入 stream 返回零字節停止
這是你的代碼嗎? 你到底想在那里做什么? :p
為了從 SerialPort 讀取,您需要聲明此端口:
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("/dev/tty/USB0"); //on unix based system
然后在這個端口上打開一個連接:
SerialPort serialPort = (SerialPort) portIdentifier.open("NameOfConnection-whatever", 0);
下一步是設置此端口的參數(如果需要):
serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
這是我的配置 - 你的可能會有所不同:)
現在您已准備好在此端口上讀取一些數據,要獲取數據:您需要獲取 serialPorts 輸入流並從中讀取:
InputStream inputStream = serialPort.getInputStream();
while (active) {
try {
byte[] buffer = new byte[22];
while ((buffer[0] = (byte) inputStream.read()) != 'R') {
}
int i = 1;
while (i < 22) {
if (!active) {
break;
}
buffer[i++] = (byte) inputStream.read();
}
//do with the buffer whatever you want!
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
}
}
我實際上在這里做的是使用它的read()
方法從輸入流中讀取。 這將阻塞直到數據可用,如果到達 stream 的末尾,則返回 -1。 在這個例子中,我等到我得到一個“R”字符,然后將接下來的 22 個字節讀入緩沖區。 這就是您讀取數據的方式。
active
設置為 false 從而結束讀取過程。希望這可以幫助
嘗試使用
if (socketReader.ready()) {
}
這樣套接字僅在緩沖區 Stream 中有要讀取的內容時才響應,因此永遠不會發生異常。
在你的 try 塊中是這樣的:
OutputStream outStream = p.getOutputStream();
InputStream inStream = p.getInputStream();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.