jav读取对应的串口程序的2种方式

2023-12-28 11:07:30

Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.

目录

在这里插入图片描述

概述

jav读取对应的串口程序在物联网中是一个非常常见的需求。

需求:

设计思路

实现思路分析

1.demo1

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
 
public class SerialPortReader implements SerialPortEventListener {
    private SerialPort serialPort;
 
    private void connect(String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            // 打开串口
            int timeout = 2000;
            serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), timeout);
 
            // 设置串口参数
            int baudRate = 9600;
            serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
 
            // 获取串口输入流
            InputStream inputStream = serialPort.getInputStream();
 
            // 创建一个读取串口数据的缓冲流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
 
            // 添加串口监听器
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
 
            // 读取串口数据
            String line = bufferedReader.readLine();
            System.out.println("Received data: " + line);
        }
    }
 
    @Override
    public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
                String line = bufferedReader.readLine();
                System.out.println("Received data: " + line);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        SerialPortReader serialPortReader = new SerialPortReader();
        try {
            serialPortReader.connect("/dev/ttyUSB0");  // 请根据实际串口设备名称修改
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.demo2

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
 
public class SerialPortReader implements SerialPortEventListener {
    private SerialPort serialPort;
 
    private void connect(String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            // 打开串口
            int timeout = 2000;
            serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), timeout);
 
            // 设置串口参数
            int baudRate = 9600;
            serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
 
            // 获取串口输入流
            InputStream inputStream = serialPort.getInputStream();
 
            // 创建一个读取串口数据的缓冲流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
 
            // 添加串口监听器
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
 
            // 读取串口数据
            String line = bufferedReader.readLine();
            System.out.println("Received data: " + line);
        }
    }
 
    @Override
    public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
                String line = bufferedReader.readLine();
                System.out.println("Received data: " + line);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        SerialPortReader serialPortReader = new SerialPortReader();
        try {
            serialPortReader.connect("/dev/ttyUSB0");  // 请根据实际串口设备名称修改
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

demo3 使用JSerialComm读取串口数据

import com.fazecast.jSerialComm.SerialPort;
 
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
 
public class JSerialCommReader {
    public static void main(String[] args) {
        SerialPort serialPort = SerialPort.getCommPort("COM3");
        serialPort.openPort();
        serialPort.setBaudRate(9600);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(1);
        serialPort.setParity(SerialPort.NO_PARITY);
 
        InputStream input = serialPort.getInputStream();
 
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
                    Date date = new Date(System.currentTimeMillis());
                    Scanner scanner = new Scanner(input);
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        System.out.println("串口发送: " + line + "  " + formatter.format(date));
                    }
                } catch (Exception e) {
                    System.err.println("从串口读取失败:" + e.getMessage());
                }
            }
        };
 
        // 每隔1秒执行一次任务
        timer.scheduleAtFixedRate(task, 0, 1000);
 
        // 运行后请记得在合适的地方关闭串口连接,例如在应用程序退出时
        // serialPort.closePort();
    }
}

参考资料和推荐阅读

参考资料
官方文档
开源社区
博客文章
书籍推荐
1.暂无

欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!同时,期望各位大佬的批评指正~

文章来源:https://blog.csdn.net/xiamaocheng/article/details/135259550
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。