ubuntu java serial,在ubuntu上使用Java进行串行端口识别

I'm trying to connect a serial application on ubuntu with Java

After searching and reading resources,I add comm.jar and RXTXcomm.jar in the library.

I use the following code to identify the comports. In my system there are three ports but it is showing false in ports.hasMoreElements() method.

Kindly look into the code and help me.

String wantedPortName = "/dev/ttya";

///dev/ttyS0 و /dev/ttyS1 نیز تست شد

Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();

CommPortIdentifier portId = null; // will be set if port found

while (portIdentifiers.hasMoreElements())

{

CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();

if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&

pid.getName().equals(wantedPortName))

{

portId = pid;

break;

}

}

if(portId == null)

{

System.err.println("Could not find serial port " + wantedPortName);

System.exit(1);

}

解决方案

In my case, I'm using Ubuntu, and my notebook does not have any serial or paralel ports.

So, you have to simulate this kind of port:

apt-get install socat

Run it:

socat -d -d pty,raw,echo=0, pty,raw,echo=0

According to output, pay attention to "devices" created:

2014/02/05 01:04:32 socat[7411] N PTY is /dev/pts/2

2014/02/05 01:04:32 socat[7411] N PTY is /dev/pts/3

2014/02/05 01:04:32 socat[7411] N starting data transfer loop with FDs [3,3] and [5,5]

Stop socat [CTRL]+[C] and symlink it to a location that RXTX will recognise as a device, due to "tty" prefix:

sudo ln -s /dev/pts/2 /dev/ttyUSB02

sudo ln -s /dev/pts/3 /dev/ttyUSB03

Now, run socat again

socat -d -d pty,raw,echo=0 pty,raw,echo=0

Now, using following code, you will see 2 virtual ports:

Enumeration portList = CommPortIdentifier.getPortIdentifiers();//this line was false

System.out.println(portList.hasMoreElements());

while(portList.hasMoreElements()){

System.out.println("Has more elements");

CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

System.out.println(portId.getName());

}

else{

System.out.println(portId.getName());

}

}

system.out:

true

Has more elements

/dev/ttyUSB03

Has more elements

/dev/ttyUSB02

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值