实例介绍
【实例截图】
【核心代码】串口方法类
public class serialTool {
public static int flag=0;
static byte[] bytes = null;
public static List<String> findPort() {
// TODO Auto-generated method stub
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
List<String> portNameList = new ArrayList<>();
//将可用串口名添加到List并返回该List
while (portList.hasMoreElements()) {
String portName = portList.nextElement().getName();
portNameList.add(portName);
}
return portNameList;
}
public static SerialPort openPort(String commName, int btln) {
// TODO Auto-generated method stub
try {
//通过端口名识别端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(commName);
//打开端口,并给端口名字和一个timeout(打开操作的超时时间)
CommPort commPort = portIdentifier.open(commName, 2000);
//判断是不是串口
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
//设置一下串口的波特率等参数
serialPort.setSerialPortParams(btln, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
return serialPort;
}
}catch(NoSuchPortException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "错误:串口找不到!");
}catch(PortInUseException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "错误:串口已被占用!");
}catch(UnsupportedCommOperationException e2) {
e2.printStackTrace();
JOptionPane.showMessageDialog(null, "错误:操作不允许!");
}
return null;
}
public static void addListener(SerialPort port, SerialListener listener)throws TooManyListenersException {
// TODO Auto-generated method stub
//给串口添加监听器
port.addEventListener(listener);
//设置当有数据到达时唤醒监听接收线程
port.notifyOnDataAvailable(true);
//设置当通信中断时唤醒中断线程
port.notifyOnBreakInterrupt(true);
}
public static void closePort(SerialPort serialPort) {
// TODO Auto-generated method stub
if (serialPort != null) {
serialPort.close();
serialPort = null;
}
}
public static void sendToPort(SerialPort serialPort, String sendData) throws IOException{
// TODO Auto-generated method stub
OutputStream out = null;
out = serialPort.getOutputStream();
out.write(hexStringToByte(sendData));
out.flush();
out.close();
}
public static byte[] intToByteArray(int i) {
byte[] result = new byte[4];
//由高位到低位
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
private static byte[] hexStringToByte(String hex) {
// TODO Auto-generated method stub
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i ) {
int pos = i * 2;
result[i] = (byte)( (toByte(achar[pos]) << 4 | toByte(achar[pos 1]))&0xff);
}
return result;
}
private static int toByte(char c) {
byte b = (byte) "0123456789abcdef".indexOf(c);
return b;
}
public static byte[] readFromPort(SerialPort serialPort)throws IOException {
// TODO Auto-generated method stub
InputStream in = null;
try {
in = serialPort.getInputStream();
while (true) {
// PacketLength为数据包长度
int PacketLength=10;
int newData=0;
byte[] bytes = new byte[PacketLength];
for(int i = 0; i < PacketLength; i ){
if( ( newData = in.read()) != -1){
bytes[i] = (byte)newData;
}else {
break;
}
}
return bytes;
}
} catch (IOException e) {
try {
throw e;
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
/*Timer timer=new Timer(true);
timer.schedule(new TimerTask() {
@Override
public void run() {
bytes=doit(serialPort);
}
}, 0,900);*/
}
protected static byte[] doit(SerialPort serialPort) {
// TODO Auto-generated method stub
InputStream in = null;
try {
in = serialPort.getInputStream();
while (true) {
// PacketLength为数据包长度
int PacketLength=10;
int newData=0;
byte[] bytes = new byte[PacketLength];
for(int i = 0; i < PacketLength; i ){
if( ( newData = in.read()) != -1){
bytes = intToByteArray(newData);
}
}
return bytes;
}
/* int bufflenth = in.available(); //获取buffer里的数据长度
while (bufflenth != 0) {
bytes = new byte[bufflenth]; //初始化byte数组为buffer中数据的长度
in.read(bytes);
String str=printHexString(bytes);
bufflenth = in.available();
}*/
} catch (IOException e) {
try {
throw e;
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytes;
//return bytes;
}
private static String printHexString(byte[] data) {
// TODO Auto-generated method stub
StringBuffer sbf=new StringBuffer();
for (int i = 0; i < data.length; i ) {
String hex = Integer.toHexString(data[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' hex;
}
sbf.append(hex.toUpperCase() " ");
}
return sbf.toString().trim();
}
}
相关软件
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论