java 实现串口通信

最近做了一个与硬件相关的项目,刚开始听说用java和硬件打交道,着实下了一大跳。java也可以操作硬件?

后来接触到是用java通过串口通信控制硬件感觉使用起来还不错,也很方便。

特拿出来和大家一起分享一下。


准备工作:

首先到SUN官网下载一个zip包:javacomm20-win32.zip


其中重要的有这几个文件:

win32com.dll

comm.jar

javax.comm.properties


按照说明配置好环境,如下:

将win32com.dll复制到<JDK>\bin目录下;将comm.jar复制到<JDK>\lib;把 javax.comm.properties也同样拷贝到<JDK>\lib目录下。然而在真正运行使用串口包的时候,仅作这些是不够的。因 为通常当运行“java MyApp”的时候,是由JRE下的虚拟机启动MyApp的。而我们只复制上述文件到JDK相应目录下,所以应用程序将会提示找不到串口。解决这个问题的 方法很简单,我们只须将上面提到的文件放到JRE相应的目录下就可以了

到这一个可以java 串口开发环境就搭建完成了


确认本机可以使用的串口:

package test;

import java.util.Enumeration;
import java.util.HashMap;

import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;

public class GetSerialPorts {

    public void listPortChoices() {
        CommPortIdentifier portId;
        Enumeration en = CommPortIdentifier.getPortIdentifiers();
        // iterate through the ports.
        while (en.hasMoreElements()) {
            portId = (CommPortIdentifier) en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println(portId.getName());
            }
        }

    }

    public static void main(String[] args) {

        GetSerialPorts GSP = new GetSerialPorts();
        GSP.listPortChoices();

    }

}


打开串口,关闭串口:

package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;

public class GetSerialPorts {

    private CommPortIdentifier portId;

    private SerialPort testPort;

    private CommPortIdentifier myPort;

    private InputStream is;

    private OutputStream os;

    public void listPortChoices() {

        Enumeration en = CommPortIdentifier.getPortIdentifiers();
        // iterate through the ports.
        while (en.hasMoreElements()) {
            portId = (CommPortIdentifier) en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println(portId.getName());
            }
            myPort = portId;// 任意取一个串口,比如com1
        }

    }

    public boolean openPort() {
        try {
            testPort = (SerialPort) myPort.open("COM1", 500);// 注意这里必须换成一个真实的串口
            try {
                this.testPort.setSerialPortParams(38400, SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
            } catch (UnsupportedCommOperationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                this.testPort.enableReceiveTimeout(30);
            } catch (UnsupportedCommOperationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.testPort.setOutputBufferSize(1024);
            this.testPort.setInputBufferSize(1024);

            try {
                this.is = this.testPort.getInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                this.os = this.testPort.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.testPort.notifyOnDataAvailable(true);
            this.testPort.notifyOnOutputEmpty(true);
            this.testPort.notifyOnBreakInterrupt(true);

            // this.printerPort.addEventListener(new PrintPortListener(is));
            System.out.println("打开com1机串口成功");
            return true;
        } catch (PortInUseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }

    /**
     * TODO 关闭端口
     * 
     * @param
     * @return Map
     * @throws
     */
    public boolean closePort() {
        // TODO Auto-generated method stub
        try {
            if (null != this.testPort) {
                is.close();
                os.close();
                this.testPort.close();
            }
            System.out.println("关闭COM1串口成功");
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            System.out.println("关闭COM1串口失败");
            return false;
        }
    }

    public static void main(String[] args) {

        GetSerialPorts GSP = new GetSerialPorts();
        GSP.listPortChoices();
        GSP.openPort();

    }

}


读数据:

/**
     * TODO 接收端口數據
     * 
     * @param InputStream
     * @return String
     * @throws
     */
    public String readData(InputStream is) {
        // 读取缓冲区域
        byte[] readBuffer = new byte[4096];
        int readDataLength = 0;
        try {
            readDataLength = is.read(readBuffer);
            // for (byte b : readBuffer) {
            // System.out.print(b);
            // }
            // System.out.println();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        // 将真实数据保存到零时数组中
        byte[] readTemp = new byte[readDataLength];
        for (int i = 0; i < readDataLength; i++) {
            readTemp[i] = readBuffer[i];
        }

        // 将byte数组转换为16进制字符串
        String stringTemp = FeelTheBase.bytesToHexString(readTemp);
        // System.out.println("指令返回值" + stringTemp);

        return stringTemp;

    }

时间紧迫,到此为止,希望能够对初学者有些帮助,此文章同时在博客园发布。



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Java可以通过串口通信实现与外部设备的数据交互。下面是Java实现串口通信的基本步骤: 1. 导入扩展包和依赖库,例如RXTXcomm.jar和RXTXcomm.dll等。 2. 配置串口参数,例如波特率、数据位、停止位、校验位等。 3. 打开串口并获取输入输出流。 4. 通过输入输出流进行数据的读写操作。 5. 关闭串口。 下面是一个简单的Java串口通信示例代码: ```java import gnu.io.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class SerialPortTest implements SerialPortEventListener { private SerialPort serialPort; public void init() { try { // 获取系统中可用的串口列表 CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1"); // 打开串口,并设置串口参数 serialPort = (SerialPort) portIdentifier.open("SerialPortTest", 2000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // 获取串口的输入输出流 InputStream inputStream = serialPort.getInputStream(); OutputStream outputStream = serialPort.getOutputStream(); // 监听串口数据 serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); // 发送数据 outputStream.write("Hello, Serial Port!".getBytes()); } catch (NoSuchPortException | PortInUseException | UnsupportedCommOperationException | IOException | TooManyListenersException e) { e.printStackTrace(); } } @Override public void serialEvent(SerialPortEvent serialPortEvent) { if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try { // 读取串口数据 InputStream inputStream = serialPort.getInputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inputStream.read(buffer)) != -1) { System.out.println(new String(buffer, 0, len)); } } catch (IOException e) { e.printStackTrace(); } } } public void close() { // 关闭串口 if (serialPort != null) { serialPort.removeEventListener(); serialPort.close(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值