java 串口通信详细及简单实例

 更新时间:2017年01月11日 11:07:33   投稿:lqh  
这篇文章主要介绍了java 串口通信详细及简单实例的相关资料,在开发硬件与软件结合的时候,就会用到串口,需要的朋友可以参考下

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;

  }


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

  • 解决Mybatis-Plus更新方法不更新NULL字段的问题

    解决Mybatis-Plus更新方法不更新NULL字段的问题

    这篇文章主要介绍了解决Mybatis-Plus更新方法不更新NULL字段的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • mybatis plus条件构造器queryWrapper、updateWrapper

    mybatis plus条件构造器queryWrapper、updateWrapper

    这篇文章主要介绍了mybatis plus条件构造器queryWrapper、updateWrapper,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Java实现游戏抽奖算法

    Java实现游戏抽奖算法

    这篇文章主要为大家详细介绍了Java实现游戏抽奖算法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-11-11
  • Java虚拟机处理异常的最佳方式

    Java虚拟机处理异常的最佳方式

    这篇文章主要给大家介绍了关于Java虚拟机处理异常的最佳方式,文中通过示例代码介绍的非常详细,对大家的学习或者使用Java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-03-03
  • eclipse maven 插件的安装和配置详解

    eclipse maven 插件的安装和配置详解

    这篇文章主要介绍了eclipse maven 插件的安装和配置详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-01-01
  • 详解Spring Security中的HttpBasic登录验证模式

    详解Spring Security中的HttpBasic登录验证模式

    HttpBasic登录验证模式是Spring Security实现登录验证最简单的一种方式,也可以说是最简陋的一种方式,这篇文章主要介绍了Spring Security的HttpBasic登录验证模式,需要的朋友可以参考下
    2019-11-11
  • Java调取创蓝253短信验证码的实现代码

    Java调取创蓝253短信验证码的实现代码

    这篇文章主要介绍了Java调取创蓝253短信验证码的实现代码,需要的朋友可以参考下
    2018-04-04
  • mybatis连接mysql的实现过程

    mybatis连接mysql的实现过程

    通过配置Maven的pom文件,可以简化MyBatis连接数据库的过程,免去手动下载和导入各种依赖包的麻烦,本文介绍了如何利用Maven导入MyBatis及其他相关依赖,如Junit、MySQL连接驱动、Druid连接池和Dbutil等,以简化数据库操作和测试
    2024-10-10
  • SpringBoot配置Spring Security的实现示例

    SpringBoot配置Spring Security的实现示例

    本文主要介绍了SpringBoot配置Spring Security的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-10-10
  • SpringCloud基本Rest微服务工程搭建过程

    SpringCloud基本Rest微服务工程搭建过程

    这篇文章主要介绍了SpringCloud基本Rest微服务工程搭建,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01

最新评论