java 串口通信实现流程

1、下载64位rxtx for java 链接:http://fizzed.com/oss/rxtx-for-java

2、下载下来的包解压后按照说明放到JAVA_HOME即JAVA的安装路径下面去

3、在maven的pom.xml下添加

    <dependency>
    <groupId>org.rxtx</groupId>
    <artifactId>rxtx</artifactId>
    <version>2.1.7</version>
  </dependency>

4、串口API

  CommPort:端口的抽象类
  CommPortIdentifier:对串口访问和控制的核心类
  SerialPort:通过它可以直接对串口进行读、写及设置工作

5、列出本机可用端口

Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers();
  while (em.hasMoreElements()) {
    String name = em.nextElement().getName();
    System.out.println(name);
  }

6、一般步骤:打开串口得到串口对象==》设置参数==》对串口进行读写==》关闭串口,其中对串口进行读操作比较常用

//打开串口
  CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM4");//COM4是串口名字
  CommPort commPort = portIdentifier.open("COM4", 2000);    //2000是打开超时时间
  serialPort = (SerialPort) commPort;
  //设置参数(包括波特率,输入/输出流控制,数据位数,停止位和齐偶校验)
  serialPort.setSerialPortParams(9600,
  SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
  SerialPort.PARITY_NONE);
  //监听串口事件
  serialPort.addEventListener(new Abc()); //Abc是实现SerialPortEventListener接口的类,具体读操作在里面进行
  // 设置当有数据到达时唤醒监听接收线程
  serialPort.notifyOnDataAvailable(true);
  // 设置当通信中断时唤醒中断线程
  serialPort.notifyOnBreakInterrupt(true);
  //    in.close(); //关闭串口

Abc类内容,即读串口的具体操作:

public class Abc implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent arg0) {
        // TODO Auto-generated method stub
        //对以下内容进行判断并操作
        /*
        BI -通讯中断
      CD -载波检测
      CTS -清除发送
      DATA_AVAILABLE -有数据到达
      DSR -数据设备准备好
      FE -帧错误
      OE -溢位错误
      OUTPUT_BUFFER_EMPTY -输出缓冲区已清空
      PE -奇偶校验错
        RI - 振铃指示
        */
        //switch多个,if单个
        if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                InputStream in = null;
                byte[] bytes = null;
                in = App.serialPort.getInputStream();

                int bufflenth = in.available();
                while (bufflenth != 0) {
                    // 初始化byte数组为buffer中数据的长度
                    bytes = new byte[bufflenth];
                    in.read(bytes);
                    System.out.println(new String(bytes));
                    bufflenth = in.available();
                }
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }    
}

写操作:

OutputStream out = serialPort.getOutputStream();
out.write(data); //byte[] data;
out.flush();

7、打开关闭串口等动作要有触发,异常要处理。—wxws

 

 

 

posted @ 2017-11-23 17:52  zhyemmmm  阅读(11710)  评论(2编辑  收藏  举报