packageinit;importgnu.io.CommPort;importgnu.io.CommPortIdentifier;importgnu.io.SerialPort;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;public classeee

{static String defaultPort = "/dev/ttyS1"; //linux

public static voidmain ( String[] args )

{

listPorts();try{

(newtest()).connect(defaultPort);

}catch( Exception e )

{

e.printStackTrace();

}

}publiceee()

{super();

}void connect ( String portName ) throwsException

{

CommPortIdentifier portIdentifier=CommPortIdentifier.getPortIdentifier(portName);if( portIdentifier.isCurrentlyOwned() )

{

System.out.println("Error: Port is currently in use");

}else{

CommPort commPort= portIdentifier.open(this.getClass().getName(),2000);if ( commPort instanceofSerialPort )

{

SerialPort serialPort=(SerialPort) commPort;

serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

InputStream in=serialPort.getInputStream();

InputStreamReader reader= newInputStreamReader(in);

BufferedReader r= newBufferedReader(reader);

(new Thread(newSerialReader(r))).start();

}else{

System.out.println("Error: Only serial ports are handled by this example.");

}

}

}/** */

public static class SerialReader implementsRunnable

{

BufferedReader in;publicSerialReader ( BufferedReader in )

{this.in =in;

}public voidrun ()

{try{

String line;while ((line = in.readLine()) != null){

System.out.println(line);

}

}catch( IOException e )

{

e.printStackTrace();

}

}

}/** */

public static class SerialWriter implementsRunnable

{

OutputStream out;publicSerialWriter ( OutputStream out )

{this.out =out;

}public voidrun ()

{try{int c = 0;while ( ( c = System.in.read()) > -1)

{this.out.write(c);

}

}catch( IOException e )

{

e.printStackTrace();

}

}

}static voidlistPorts()

{

System.out.println("all ports!!!");

@SuppressWarnings("unchecked")

java.util.Enumeration portEnum =CommPortIdentifier.getPortIdentifiers();while( portEnum.hasMoreElements() )

{

CommPortIdentifier portIdentifier=portEnum.nextElement();

System.out.println(portIdentifier.getName()+ " - " +getPortTypeName(portIdentifier.getPortType()) );

}

}static String getPortTypeName ( intportType )

{switch( portType )

{caseCommPortIdentifier.PORT_I2C:return "I2C";caseCommPortIdentifier.PORT_PARALLEL:return "Parallel";caseCommPortIdentifier.PORT_RAW:return "Raw";caseCommPortIdentifier.PORT_RS485:return "RS485";caseCommPortIdentifier.PORT_SERIAL:return "Serial";default:return "unknown type";

}

}

}

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐