与串行端口

时间:2015-09-15 11:21:38

标签: java

我正在尝试与串行端口通信。在下面的程序中,我列出了可用的端口,它给了我正确的输出但是当我尝试与串口建立通信时,它给了我以下异常。

  

java.lang.ClassCastException:gnu.io.LPRPort无法强制转换为gnu.io.SerialPort

程序:

import gnu.io.CommPortIdentifier;
import gnu.io.*;
import java.io.*;
import java.util.Enumeration;

public class PortList {

    private static CommPortIdentifier port;
    private SerialPort serialport;
    private InputStream inputstream;
    private OutputStream outputstream;
    private static Enumeration ports;

    public static void main(String args[]) {
        System.out.println("fdsgfjh");

        ports = CommPortIdentifier.getPortIdentifiers();
        System.out.println(ports.nextElement());
        while (ports.hasMoreElements()) {
            port = (CommPortIdentifier)ports.nextElement();
            String type;
            switch (port.getPortType()) {
                case CommPortIdentifier.PORT_PARALLEL:
                    type = "Parallel"; 
                    break;
                case CommPortIdentifier.PORT_SERIAL:
                    type = "Serial"; 
                    break;
                default: /// Shouldn't happen
                    type = "Unknown"; 
                    break;
            }
            System.out.println(port.getName() + ": " + type);
        }
        PortList objOfClass=new PortList();
        objOfClass.readData();

    }

    public void readData(){
        try{
            if (port.isCurrentlyOwned()) {
                System.out.println("Port Is In Use");
            }
            else {
                serialport=(SerialPort)port.open(this.getClass().getName(), 2000);//Giving Exception on this line.

                System.out.println("Port Is Opened now");

                int baudRate=serialport.getBaudRate();
                System.out.println(Integer.toString(baudRate));

                serialport.setSerialPortParams(1200, 8, 1, serialport.PARITY_NONE);
                System.out.println("Properties are set");

                inputstream=serialport.getInputStream();
                outputstream=serialport.getOutputStream();

                byte[] write={12,45,78};
                outputstream.write(write);//you have to write the data in the byte format for that status is given in the byte.
                outputstream.flush();

                byte[] read=new byte[30];
                inputstream.read(read);

                for(int i =0; i< read.length;i++){
                    System.out.println(i+" "+read);
                }
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

帮助感谢。 感谢。

2 个答案:

答案 0 :(得分:1)

根据您的实施,port将是最后列出的端口。最后列出的端口可能不是串行端口。 在您的情况下,似乎最后列出的端口是并行端口。

答案 1 :(得分:0)

通过这种方式,我选择了可​​用的特定端口。

CommPortIdentifier.getPortIdentifier(&#34;的/ dev / ttyS0来&#34);