Java RXTX串口可以发送数据,但接收不到数据。

english1255 2014-03-09 04:41:58
刚接触串口,写了以下代码。利用软件虚拟了两个串口,运行以下代码时,可以发送数据,却不接收不到数据,多次测试,发现监听(serialEvent)一直进不去,求各位大大指教。



package com.red.test;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;

public class Demo implements SerialPortEventListener{

protected static CommPortIdentifier portid = null; //通讯端口标识符
protected static SerialPort comPort = null; //串行端口
protected int BAUD = 9600; //波特率
protected int DATABITS = SerialPort.DATABITS_8;; //数据位
protected int STOPBITS = SerialPort.STOPBITS_1; //停止位
protected int PARITY = SerialPort.PARITY_NONE; //奇偶检验
private static OutputStream oStream; //输出流
private static InputStream iStream; //输入流
StringBuilder buf = new StringBuilder(128);

public static void main(String[] args) {
Timer t = new Timer();

t.schedule(new TimerTask() {
@Override
public void run() {

Demo test = new Demo();
// 查看所有串口
test.listPortChoices();
//设置串口号
test.setSerialPortNumber();

}},3000,3000);
}

/**
* 读取所有串口名字
*/
private 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());
}
}
}

/**
* 设置串口号
* @param Port
* @return
*/
private void setSerialPortNumber() {

String osName = null;
String osname = System.getProperty("os.name", "").toLowerCase();
if (osname.startsWith("windows")) {
// windows
osName = "COM1";
} else if (osname.startsWith("linux")) {
// linux
osName = "/dev/ttyS1";
}

try {
portid = CommPortIdentifier.getPortIdentifier(osName);
// portid = CommPortIdentifier.getPortIdentifier(Port);
if(portid.isCurrentlyOwned()){
System.out.println("端口在使用");
}else{
comPort = (SerialPort) portid.open(this.getClass().getName(), 1000);
}
} catch (PortInUseException e) {
System.out.println("端口被占用");
e.printStackTrace();

} catch (NoSuchPortException e) {
System.out.println("端口不存在");
e.printStackTrace();
}

try {
iStream = comPort.getInputStream(); //从COM1获取数据
oStream = comPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}


try {
comPort.addEventListener(this); //给当前串口增加一个监听器
comPort.notifyOnDataAvailable(true); //当有数据是通知
} catch (TooManyListenersException e) {
e.printStackTrace();
}

try {
//设置串口参数依次为(波特率,数据位,停止位,奇偶检验)
comPort.setSerialPortParams(this.BAUD, this.DATABITS, this.STOPBITS, this.PARITY);
} catch (UnsupportedCommOperationException e) {
System.out.println("端口操作命令不支持");
e.printStackTrace();
}

try {

//# testData
String testData = "1";
oStream.write(testData.getBytes());


iStream.close();
comPort.close();
} catch (IOException e) {
e.printStackTrace();
}
}

@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:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据
byte[] readBuffer = new byte[20];;
try {
char b;
while (iStream.available() > 0) {
b = (char)iStream.read(readBuffer);
buf.append(b);
}
} catch (IOException e) {
System.out.println(e.toString());
}
break;
}
}
}



以下是虚拟端口软件。(从图片中可以看出发送和接收的字节数)



...全文
1592 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
suotaihui0007 2016-07-14
  • 打赏
  • 举报
回复
引用 8 楼 XSX127 的回复:
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;

import javax.print.attribute.standard.PrinterMessageFromOperator;

import com.sun.glass.ui.TouchInputSupport;
 
public class aaa implements SerialPortEventListener{
     
    protected static CommPortIdentifier portid = null;  //通讯端口标识符
    protected static SerialPort comPort = null;         //串行端口
    protected int BAUD = 9600;  //波特率
    protected int DATABITS = SerialPort.DATABITS_8;;  //数据位
    protected int STOPBITS = SerialPort.STOPBITS_1;  //停止位
    protected int PARITY = SerialPort.PARITY_NONE;  //奇偶检验
    private static OutputStream oStream;    //输出流
    private static InputStream iStream;     //输入流
    StringBuilder buf = new StringBuilder(128);
     
    public static void main(String[] args) {
    	aaa my = new aaa();
    	my.setSerialPortNumber();
    }
     
    /**
     * 读取所有串口名字
     */
     private 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());
             }
         }
     }
      
     /**
      * 设置串口号
      * @param Port
      * @return
      */
     private void setSerialPortNumber() {
       
         String osName = null;
         String osname = System.getProperty("os.name", "").toLowerCase();
         if (osname.startsWith("windows")) {
             // windows
             osName = "COM1";
         } else if (osname.startsWith("linux")) {
             // linux
             osName = "/dev/ttyS1";
         }
          System.out.println(osName);
         try {
             portid = CommPortIdentifier.getPortIdentifier(osName);
             // portid = CommPortIdentifier.getPortIdentifier(Port);
             if(portid.isCurrentlyOwned()){
                 System.out.println("端口在使用");
             }else{
                 comPort = (SerialPort) portid.open(this.getClass().getName(), 1000);
             }
         } catch (PortInUseException e) {
             System.out.println("端口被占用");
             e.printStackTrace();
          
         } catch (NoSuchPortException e) {
             System.out.println("端口不存在");
             e.printStackTrace();
         }
 
         try {
            iStream = comPort.getInputStream(); //从COM1获取数据
            oStream = comPort.getOutputStream();
         } catch (IOException e) {
                e.printStackTrace();
        }
          
          
        try {
            comPort.addEventListener(this);       //给当前串口增加一个监听器
            comPort.notifyOnDataAvailable(true);  //当有数据是通知
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
         
        try {
            //设置串口参数依次为(波特率,数据位,停止位,奇偶检验)
            comPort.setSerialPortParams(this.BAUD, this.DATABITS, this.STOPBITS, this.PARITY);
        } catch (UnsupportedCommOperationException e) {
            System.out.println("端口操作命令不支持");
            e.printStackTrace();
        }
         
        try {
             
            //# testData
            String testData = "1";
            oStream.write(testData.getBytes());
             
             
           // iStream.close();
           // comPort.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
     }
 
    @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:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据
            	try {
    				while(iStream.available() > 0) {
                        System.out.println("接收数据:"+((byte) iStream.read()));
                    }
    			} catch (IOException e) {

    			}
                break;
        }
    }
}
稍微修改了下,是可以发送接收的,我也用虚拟串口测试了,不行再问 COM1 接收数据:112 接收数据:97 接收数据:103 接收数据:101 接收数据:32 接收数据:52 接收数据:-1 接收数据:-1 接收数据:-1
你好,我最近也在写基于rxtx的串口通信程序,这里接收下位机发送的16进制数据为什么就直接显示为10进制了,有没有办法接收16进制的数据?希望可以帮忙解答一下,十分感激
酷酷啦啦xsx 2015-12-28
  • 打赏
  • 举报
回复
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;

import javax.print.attribute.standard.PrinterMessageFromOperator;

import com.sun.glass.ui.TouchInputSupport;
 
public class aaa implements SerialPortEventListener{
     
    protected static CommPortIdentifier portid = null;  //通讯端口标识符
    protected static SerialPort comPort = null;         //串行端口
    protected int BAUD = 9600;  //波特率
    protected int DATABITS = SerialPort.DATABITS_8;;  //数据位
    protected int STOPBITS = SerialPort.STOPBITS_1;  //停止位
    protected int PARITY = SerialPort.PARITY_NONE;  //奇偶检验
    private static OutputStream oStream;    //输出流
    private static InputStream iStream;     //输入流
    StringBuilder buf = new StringBuilder(128);
     
    public static void main(String[] args) {
    	aaa my = new aaa();
    	my.setSerialPortNumber();
    }
     
    /**
     * 读取所有串口名字
     */
     private 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());
             }
         }
     }
      
     /**
      * 设置串口号
      * @param Port
      * @return
      */
     private void setSerialPortNumber() {
       
         String osName = null;
         String osname = System.getProperty("os.name", "").toLowerCase();
         if (osname.startsWith("windows")) {
             // windows
             osName = "COM1";
         } else if (osname.startsWith("linux")) {
             // linux
             osName = "/dev/ttyS1";
         }
          System.out.println(osName);
         try {
             portid = CommPortIdentifier.getPortIdentifier(osName);
             // portid = CommPortIdentifier.getPortIdentifier(Port);
             if(portid.isCurrentlyOwned()){
                 System.out.println("端口在使用");
             }else{
                 comPort = (SerialPort) portid.open(this.getClass().getName(), 1000);
             }
         } catch (PortInUseException e) {
             System.out.println("端口被占用");
             e.printStackTrace();
          
         } catch (NoSuchPortException e) {
             System.out.println("端口不存在");
             e.printStackTrace();
         }
 
         try {
            iStream = comPort.getInputStream(); //从COM1获取数据
            oStream = comPort.getOutputStream();
         } catch (IOException e) {
                e.printStackTrace();
        }
          
          
        try {
            comPort.addEventListener(this);       //给当前串口增加一个监听器
            comPort.notifyOnDataAvailable(true);  //当有数据是通知
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
         
        try {
            //设置串口参数依次为(波特率,数据位,停止位,奇偶检验)
            comPort.setSerialPortParams(this.BAUD, this.DATABITS, this.STOPBITS, this.PARITY);
        } catch (UnsupportedCommOperationException e) {
            System.out.println("端口操作命令不支持");
            e.printStackTrace();
        }
         
        try {
             
            //# testData
            String testData = "1";
            oStream.write(testData.getBytes());
             
             
           // iStream.close();
           // comPort.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
     }
 
    @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:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据
            	try {
    				while(iStream.available() > 0) {
                        System.out.println("接收数据:"+((byte) iStream.read()));
                    }
    			} catch (IOException e) {

    			}
                break;
        }
    }
}
稍微修改了下,是可以发送接收的,我也用虚拟串口测试了,不行再问 COM1 接收数据:112 接收数据:97 接收数据:103 接收数据:101 接收数据:32 接收数据:52 接收数据:-1 接收数据:-1 接收数据:-1
wangwenyao88 2015-12-28
  • 打赏
  • 举报
回复
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN| SerialPort.FLOWCONTROL_RTSCTS_OUT);
fuhongzi2015 2015-09-08
  • 打赏
  • 举报
回复
最近使用RXTX编写串口通信,遇到同样的问题,不知道解决了没
zz_xiazhi 2014-05-30
  • 打赏
  • 举报
回复
同样问题,有人解决了吗?
yinrongg 2014-04-11
  • 打赏
  • 举报
回复
先排除虚拟串口软件的问题,找两个USB转串口调试更保险些。
u014490840 2014-04-11
  • 打赏
  • 举报
回复
我也和你遇到同样的问题哈,没有解决,不知道解决否,
english1255 2014-03-10
  • 打赏
  • 举报
回复
还是没人来。
english1255 2014-03-09
  • 打赏
  • 举报
回复
大神快出来吧。

51,396

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧