Java 串口通讯开发实录

运行环境配置

1.Java运行环境:

客户端必须使用JDK1.8_231(64以及32位)及更早版本,为了适配串口通讯rxtxParallel.dll和rxtxSerial.dll

2.外部导入的jar包

串口通讯jar包RXTX ---- RXTXcomm.jar
其文件夹中,RXTXcomm.jar导入,rxtxParallel.dll和rxtxSerial.dll放入 %JAVA_HOME%\bin

3.串口操作类
其中msgQueue中存放了读取的串口信息,可以自定自己想要的存储类型,BlockingQueue是一种自带线程锁的队列,元素推入队列操作和元素推出队列操作分别只允许一个线程操作,防止线程数据共享带来的错误
其操作分为错误抛出异常和错误发生线程阻塞两种方式,我这里用的线程阻塞,其他推入推出方式若学习可自行查找

package Serial;
import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import gnu.io.*;

/**
 * Author ZLH
 * 
 * 完成时间:2021.7.23 15点54分
 */
public class SerialPortUtils extends Thread implements SerialPortEventListener {
    static int Bps = 38400;
    static String comPort = "COM9";
    static CommPortIdentifier portId;
    static Enumeration<?> portList;
    static OutputStream outputStream;
    static SerialPort serialPort;
    private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<>();
    InputStream inputStream;
    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    public static String byte2Hex(byte[] bytes,int length) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
    public boolean startComPort() {
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(comPort)) {
                    try {
                        serialPort = (SerialPort) portId.open(comPort, 2000);
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return false;
                    }
                    try {
                        inputStream = serialPort.getInputStream();
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                    try {
                        serialPort.addEventListener(this);
                    } catch (TooManyListenersException e) {
                        e.printStackTrace();
                        return false;
                    }
                    serialPort.notifyOnDataAvailable(true);
                    try {
                        serialPort.setSerialPortParams(Bps, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                        return false;
                    }
                    return true;
                }
            }
        }
        return false;
    }
@Override
    public void serialEvent(SerialPortEvent event) {//
        switch (event.getEventType()) {
            case SerialPortEvent.DATA_AVAILABLE:
                byte[] readBuffer = new byte[15];
                try {
                    int numBytes = -1;
                    while (inputStream.available() > 0) {
                        numBytes = inputStream.read(readBuffer);
                        System.out.println("inputStream 中的数据量为:"+numBytes);
                        if (numBytes > 0) {
                            try {
                                msgQueue.put(Date.getTime()+"  :  "+byte2Hex(readBuffer,numBytes));
                                readBuffer = new byte[15];
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                msgQueue.put("Nothing");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (IOException e) {
                }
                break;
        }
    }
    @Override
    public void run() {
        try {
            while (true) {
                if (msgQueue.size() > 0) {
                   System.out.println(msgQueue.take());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
	public static void main(String[] args) {
        SerialPortUtils cRead = new SerialPortUtils();
        if (cRead.startComPort()) {
            cRead.start();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值