import javax.comm.CommPortIdentifier; import java.util.Enumeration; public class SerialPortExample { public static void main(String[] args) { Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement(); System.out.println("--------------"); } } } import javax.comm.SerialPort; import javax.comm.CommPortIdentifier; import java.io.InputStream; import java.io.OutputStream; public class SerialCommunicationExample { public static void main(String[] args) { String selectedPort = "COM1"; try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(selectedPort); SerialPort serialPort = (SerialPort) portId.open("SerialCommunicationExample", 2000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); InputStream inputStream = serialPort.getInputStream(); OutputStream outputStream = serialPort.getOutputStream(); serialPort.close(); } catch (Exception e) { e.printStackTrace(); } } } import javax.comm.SerialPort; import javax.comm.CommPortIdentifier; import java.io.InputStream; public class SerialTimeoutExample { public static void main(String[] args) { String selectedPort = "COM1"; try { CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(selectedPort); SerialPort serialPort = (SerialPort) portId.open("SerialTimeoutExample", 2000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); InputStream inputStream = serialPort.getInputStream(); serialPort.enableReceiveTimeout(500); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); serialPort.close(); } catch (Exception e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文