串口编程问题

config_man config_man 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
程序运行总是报告如下异常:
javax.comm.PortInUseException: Port currently owned by Serial
at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:337)
at com.test.Test.<init>(Test.java:38)
at com.test.Test.main(Test.java:30)


Test.java类代码如下:

import java.io.*;
import java.util.*;
import javax.comm.*;

/**
* 读串口的例程
* @author zcj
*/

public class Test {
static CommPortIdentifier portId;
static Enumeration portList;// 枚举类
InputStream inputStream;
SerialPort serialPort;

public static void main(String[] args) {
//枚举出系统所有的RS232端口
portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {

portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
if (portId.getName().equals("COM1"))/* 找Windows下的第一个串口*/ {
//if (portId.getName().equals("/dev/term/a"))/* 找Unix-like系统下的第一个串口 */{
new Test().print();
}
}
}
}

public void print() {
try {
//获得串口对象
serialPort = (SerialPort) portId.open("TestApp", 2000);

// 获取端口的输入流对象
inputStream = serialPort.getInputStream();

//读取输入流
int ch;
StringBuffer sb = new StringBuffer();
while((ch=inputStream.read())>0){
sb.append((char)ch);
}
System.out.println("读取到的内容为:"+sb.toString());

}catch (Exception e) {
e.printStackTrace();
}
serialPort.close();
}
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
config_man
Java SE 62,620 成员 307,251 内容