[英]Reading from COM port in Java, Error 0x5 at ..\rxtx\src\termios.c(892)
我正在用Java編寫一個小應用程序來讀取COM端口,因為我們使用64位系統,所以我不得不使用RXTX。 問題是,當我嘗試運行我的應用程序時,我收到以下錯誤:
“錯誤0x5在.. \\ rxtx \\ src \\ termios.c(892):訪問被拒絕”
試過我的代碼以及來自RXTX網站的代碼 ,以前有人有這方面的經驗嗎?
這是我的代碼:
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* This version of the TwoWaySerialComm example makes use of the
* SerialPortEventListener to avoid polling.
*
*/
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
// OutputStream out = serialPort.getOutputStream();
//
// (new Thread(new SerialWriter(out))).start();
serialPort.addEventListener(new SerialReader(in));
serialPort.notifyOnDataAvailable(true);
}
else
{
System.out.println("Not a serial port...");
}
}
}
public static class SerialReader implements SerialPortEventListener
{
private InputStream in;
private byte[] buffer = new byte[1024];
public SerialReader ( InputStream in )
{
this.in = in;
}
public void serialEvent(SerialPortEvent arg0) {
int data;
try
{
int len = 0;
while ( ( data = in.read()) > -1 )
{
if ( data == '\n' ) {
break;
}
buffer[len++] = (byte) data;
}
System.out.print("Result="+new String(buffer,0,len));
}
catch ( IOException e )
{
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("COM1");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我就遇到了這個問題,因為港口是實際使用。 之前的javaw.exe實例出現在Windows任務管理器中,它占用了端口。
Java進程在CommPortIdentifier中掛起的原因是硬件問題:將我碰巧使用的USB-2串行轉換器插入USB2端口時,一切正常。 當插入USB-3端口時,CommPortIdentifier代碼將掛起,然后Java的后續實例收到termios.c:Access Denied錯誤。
這個shell命令在Android中得到了幫助(stty需要busybox):
su
chmod 666 /dev/ttyO2
stty -F /dev/ttyO2 speed 115200
我使用過rxtx api,工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.