最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java讀寫串口數(shù)據(jù)你了解多少

 更新時間:2022年02月07日 15:57:00   作者:LinWenLi  
這篇文章主要為大家詳細介紹了java讀寫串口數(shù)據(jù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

最近接觸到了串口及其讀寫,在此記錄java進行串口讀寫的過程。

1.導入支持java串口通信的jar包:

在maven項目的pom.xml中添加RXTXcomm的依賴 或者 下載RXTXcomm.jar并導入到項目中。

支持Java串口通信操作的jar包,java.comm比較老,而且不支持64位系統(tǒng),推薦使用Rxtx這個jar包(32位/64位均支持)。

下載地址:

https://pan.baidu.com/s/1L66Y268OOtb7KeN0-vMmrw 提取碼: ydj2 

注意:運行過程中拋出java.lang.UnsatisfiedLinkError錯誤或gnu.io下的類找不到時,將rxtx解壓包中的rxtxParallel.dll,rxtxSerial.dll 這兩個文件復制到C:\Windows\System32 目錄下可解決該錯誤。

2.編寫代碼操作串口:

串口必要參數(shù)類:包含連接串口所必須的參數(shù),方便在調用串口時設置和傳遞串口參數(shù)

/**
 * 串口必要參數(shù)接收類
 * @author: LinWenLi
 * @date: 2018年7月21日 下午4:30:40
 */
public class ParamConfig {
    private String serialNumber;// 串口號
    private int baudRate;        // 波特率
    private int checkoutBit;    // 校驗位
    private int dataBit;        // 數(shù)據(jù)位
    private int stopBit;        // 停止位
    public ParamConfig() {}
    /**
     * 構造方法
     * @param serialNumber    串口號
     * @param baudRate        波特率
     * @param checkoutBit    校驗位
     * @param dataBit        數(shù)據(jù)位
     * @param stopBit        停止位
     */
    public ParamConfig(String serialNumber, int baudRate, int checkoutBit, int dataBit, int stopBit) {
        this.serialNumber = serialNumber;
        this.baudRate = baudRate;
        this.checkoutBit = checkoutBit;
        this.dataBit = dataBit;
        this.stopBit = stopBit;
    }
    getter()...
    setter()...
}

串口操作類:(其中包含的CustomException是自定義異常類,僅用于拋出異常原因。)

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
/**
 * 串口參數(shù)的配置 串口一般有如下參數(shù)可以在該串口打開以前進行配置: 包括串口號,波特率,輸入/輸出流控制,數(shù)據(jù)位數(shù),停止位和奇偶校驗。
 */
// 注:串口操作類一定要繼承SerialPortEventListener
public class SerialPortUtils implements SerialPortEventListener {
    // 檢測系統(tǒng)中可用的通訊端口類
    private CommPortIdentifier commPortId;
    // 枚舉類型
    private Enumeration<CommPortIdentifier> portList;
    // RS232串口
    private SerialPort serialPort;
    // 輸入流
    private InputStream inputStream;
    // 輸出流
    private OutputStream outputStream;
    // 保存串口返回信息
    private String data;
    // 保存串口返回信息十六進制
    private String dataHex;/**
     * 初始化串口
     * @author LinWenLi
     * @date 2018年7月21日下午3:44:16
     * @Description: TODO
     * @param: paramConfig  存放串口連接必要參數(shù)的對象(會在下方給出類代碼)    
     * @return: void      
     * @throws
     */
    @SuppressWarnings("unchecked")
    public void init(ParamConfig paramConfig) {
        // 獲取系統(tǒng)中所有的通訊端口
        portList = CommPortIdentifier.getPortIdentifiers();
        // 記錄是否含有指定串口
        boolean isExsist = false;
        // 循環(huán)通訊端口
        while (portList.hasMoreElements()) {
            commPortId = portList.nextElement();
            // 判斷是否是串口
            if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // 比較串口名稱是否是指定串口
                if (paramConfig.getSerialNumber().equals(commPortId.getName())) {
                    // 串口存在
                    isExsist = true;
                    // 打開串口
                    try {
                        // open:(應用程序名【隨意命名】,阻塞時等待的毫秒數(shù))
                        serialPort = (SerialPort) commPortId.open(Object.class.getSimpleName(), 2000);
                        // 設置串口監(jiān)聽
                        serialPort.addEventListener(this);
                        // 設置串口數(shù)據(jù)時間有效(可監(jiān)聽)
                        serialPort.notifyOnDataAvailable(true);
                        // 設置串口通訊參數(shù):波特率,數(shù)據(jù)位,停止位,校驗方式
                        serialPort.setSerialPortParams(paramConfig.getBaudRate(), paramConfig.getDataBit(),
                                paramConfig.getStopBit(), paramConfig.getCheckoutBit());
                    } catch (PortInUseException e) {
                        throw new CustomException("端口被占用");
                    } catch (TooManyListenersException e) {
                        throw new CustomException("監(jiān)聽器過多");
                    } catch (UnsupportedCommOperationException e) {
                        throw new CustomException("不支持的COMM端口操作異常");
                    }
                    // 結束循環(huán)
                    break;
                }
            }
        }
        // 若不存在該串口則拋出異常
        if (!isExsist) {
            throw new CustomException("不存在該串口!");
        }
    }
    /**
     * 實現(xiàn)接口SerialPortEventListener中的方法 讀取從串口中接收的數(shù)據(jù)
     */
    @Override
    public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
        case SerialPortEvent.BI: // 通訊中斷
        case SerialPortEvent.OE: // 溢位錯誤
        case SerialPortEvent.FE: // 幀錯誤
        case SerialPortEvent.PE: // 奇偶校驗錯誤
        case SerialPortEvent.CD: // 載波檢測
        case SerialPortEvent.CTS: // 清除發(fā)送
        case SerialPortEvent.DSR: // 數(shù)據(jù)設備準備好
        case SerialPortEvent.RI: // 響鈴偵測
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 輸出緩沖區(qū)已清空
            break;
        case SerialPortEvent.DATA_AVAILABLE: // 有數(shù)據(jù)到達
            // 調用讀取數(shù)據(jù)的方法
            readComm();
            break;
        default:
            break;
        }
    }
    /**
     * 讀取串口返回信息
     * @author LinWenLi
     * @date 2018年7月21日下午3:43:04
     * @return: void      
     */
    public void readComm() {
        try {
            inputStream = serialPort.getInputStream();
            // 通過輸入流對象的available方法獲取數(shù)組字節(jié)長度
            byte[] readBuffer = new byte[inputStream.available()];
            // 從線路上讀取數(shù)據(jù)流
            int len = 0;
            while ((len = inputStream.read(readBuffer)) != -1) {         // 直接獲取到的數(shù)據(jù)
                data = new String(readBuffer, 0, len).trim();         // 轉為十六進制數(shù)據(jù)
                dataHex = bytesToHexString(readBuffer);
                System.out.println("data:" + data);
                System.out.println("dataHex:" + dataHex);// 讀取后置空流對象
                inputStream.close();
                inputStream = null;
                break;
            }
        } catch (IOException e) {
            throw new CustomException("讀取串口數(shù)據(jù)時發(fā)生IO異常");
        }
    }
    /**
     * 發(fā)送信息到串口
     * @author LinWenLi
     * @date 2018年7月21日下午3:45:22
     * @param: data      
     * @return: void      
     * @throws
     */
    public void sendComm(String data) {
        byte[] writerBuffer = null;
        try {
            writerBuffer = hexToByteArray(data);
        } catch (NumberFormatException e) {
            throw new CustomException("命令格式錯誤!");
        }
        try {
            outputStream = serialPort.getOutputStream();
            outputStream.write(writerBuffer);
            outputStream.flush();
        } catch (NullPointerException e) {
            throw new CustomException("找不到串口。");
        } catch (IOException e) {
            throw new CustomException("發(fā)送信息到串口時發(fā)生IO異常");
        }
    }
    /**
     * 關閉串口
     * @author LinWenLi
     * @date 2018年7月21日下午3:45:43
     * @Description: 關閉串口
     * @param:       
     * @return: void      
     * @throws
     */
    public void closeSerialPort() {
        if (serialPort != null) {
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    throw new CustomException("關閉輸入流時發(fā)生IO異常");
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException e) {
                    throw new CustomException("關閉輸出流時發(fā)生IO異常");
                }
            }
            serialPort.close();
            serialPort = null;
        }
    }
    /**
     * 十六進制串口返回值獲取
     */
    public String getDataHex() {
        String result = dataHex;
        // 置空執(zhí)行結果
        dataHex = null;
        // 返回執(zhí)行結果
        return result;
    }
    /**
     * 串口返回值獲取
     */
    public String getData() {
        String result = data;
        // 置空執(zhí)行結果
        data = null;
        // 返回執(zhí)行結果
        return result;
    }
    /**
     * Hex字符串轉byte
     * @param inHex 待轉換的Hex字符串
     * @return 轉換后的byte
     */
    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }
    /**
     * hex字符串轉byte數(shù)組
     * @param inHex 待轉換的Hex字符串
     * @return 轉換后的byte數(shù)組結果
     */
    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            // 奇數(shù)
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            // 偶數(shù)
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }
    /**
     * 數(shù)組轉換成十六進制字符串
     * @param byte[]
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}

調用串口操作類的代碼:

public static void main(String[] args) {
         // 實例化串口操作類對象
         SerialPortUtils serialPort = new SerialPortUtils();
         // 創(chuàng)建串口必要參數(shù)接收類并賦值,賦值串口號,波特率,校驗位,數(shù)據(jù)位,停止位
         ParamConfig paramConfig = new ParamConfig("COM4", 9600, 0, 8, 1);
         // 初始化設置,打開串口,開始監(jiān)聽讀取串口數(shù)據(jù)
         serialPort.init(paramConfig);
         // 調用串口操作類的sendComm方法發(fā)送數(shù)據(jù)到串口
         serialPort.sendComm("FEF10A000000000000000AFF");
         // 關閉串口(注意:如果需要接收串口返回數(shù)據(jù)的,請不要執(zhí)行這句,保持串口監(jiān)聽狀態(tài))
         serialPort.closeSerialPort();
     }

當執(zhí)行main方法中的代碼且未執(zhí)行關閉串口時,程序將一直處于開啟狀態(tài),自動監(jiān)聽,接收讀取來自串口的數(shù)據(jù)。

注意:一個串口只能打開一次,并只支持一個程序調用。

以上所記錄的是簡單測試java是否能成功操作串口數(shù)據(jù),至于本人所寫的Web端的讀卡器調試功能則是在串口操作類的基礎上編寫網(wǎng)頁界面,通過請求來控制串口的開啟關閉及相應的設置,功能比較簡單,放個界面記錄一下:

總結

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!   

相關文章

  • Mybatis數(shù)據(jù)批量插入如何實現(xiàn)

    Mybatis數(shù)據(jù)批量插入如何實現(xiàn)

    這篇文章主要介紹了Mybatis數(shù)據(jù)批量插入如何實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-07-07
  • spring mvc4中相關注解的詳細講解教程

    spring mvc4中相關注解的詳細講解教程

    這篇文章主要給大家介紹了關于spring mvc4中相關注解的相關資料,其中詳細介紹了關于@Controller、@RequestMapping、@RathVariable、@RequestParam及@RequestBody等等注解的相關內容,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-06-06
  • Spring中的refresh方法分析

    Spring中的refresh方法分析

    這篇文章主要介紹了Spring中的refresh方法分析,文章圍繞主題展開詳細的refresh方法相關資料介紹,需要的小伙伴可以參考一下
    2022-05-05
  • spring boot中各個版本的redis配置問題詳析

    spring boot中各個版本的redis配置問題詳析

    這篇文章主要給大家介紹了關于spring boot中各個版本的redis配置問題的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-12-12
  • spring中ioc是什么

    spring中ioc是什么

    IoC是一種讓服務消費者不直接依賴于服務提供者的組件設計方式,是一種減少類與類之間依賴的設計原則。下面通過本文給大家分享spring中ioc的概念,感興趣的朋友一起看看吧
    2017-09-09
  • Java正則表達式(匹配、切割、替換、獲取)等方法

    Java正則表達式(匹配、切割、替換、獲取)等方法

    這篇文章主要介紹了Java正則表達式(匹配、切割、替換、獲取)等方法的相關資料,需要的朋友可以參考下
    2017-06-06
  • RabbitMQ中的prefetch_count參數(shù)詳解

    RabbitMQ中的prefetch_count參數(shù)詳解

    這篇文章主要介紹了RabbitMQ中的prefetch_count參數(shù)用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Java實現(xiàn)經(jīng)典俄羅斯方塊游戲

    Java實現(xiàn)經(jīng)典俄羅斯方塊游戲

    俄羅斯方塊是一個最初由阿列克謝帕吉特諾夫在蘇聯(lián)設計和編程的益智類視頻游戲。本文將利用Java實現(xiàn)這一經(jīng)典的小游戲,需要的可以參考一下
    2022-01-01
  • Intellij IDEA 熱部署處理方法(圖解)

    Intellij IDEA 熱部署處理方法(圖解)

    本文通過圖文并茂的形式給大家介紹了Intellij IDEA 熱部署處理方法,需要的朋友可以參考下
    2018-02-02
  • 實例解析Java關于static的作用

    實例解析Java關于static的作用

    只要是有學過Java的都一定知道static,也一定能多多少少說出一些作用和注意事項。文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04

最新評論

双鸭山市| 莎车县| 晋州市| 台中市| 高密市| 漳州市| 上蔡县| 突泉县| 朝阳市| 舒兰市| 章丘市| 蒙城县| 响水县| 常宁市| 万载县| 商河县| 海林市| 阜城县| 武定县| 娄底市| 六枝特区| 剑川县| 炉霍县| 禹城市| 筠连县| 九江市| 南涧| 民县| 深水埗区| 察隅县| 沁阳市| 固安县| 平果县| 交城县| 泾源县| 邹城市| 会同县| 新乐市| 黄冈市| 门源| 江陵县|