?? 串口驅動.txt
字號:
原來一直以為只有趙學慶一個高手,代碼貼出來嚇我一跳,原來CSDN有這么多扎實人,天天來CSDN值得啊...
[code=Java]
//初始化串口驅動
private boolean initCommDriver_win32() {
try {
System.loadLibrary( "win32com ");
String driverName = "com.sun.comm.Win32Driver ";
CommDriver driver = (CommDriver) Class.forName(driverName).newInstance();
driver.initialize();
return true;
}catch (Throwable e) {
MessageDialog.openInformation(null, "initDriver ", "initDriver_Err_Win32Com ");
e.printStackTrace();
return false;
}
}
//打開串口
private boolean OpenComm(String PortName)
{
//獲取指定的COM端口
try {
portIdentifier = CommPortIdentifier.getPortIdentifier(PortName);
} catch (NoSuchPortException e) {
e.printStackTrace();
return false;
}
//打開端口(3秒打不開則失敗)
try {
serialPort = (SerialPort)portIdentifier.open(this.getTitle(),3000);
} catch (PortInUseException e) {
MessageDialog.openInformation(null, "OpenComm ", "Open_Err ");
e.printStackTrace();
return false;
}
//設置端口通訊參數 (波特率 = 9600,數據位 = 8,停止位 = 1 ,校驗位 =奇校驗)
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_ODD);
} catch (UnsupportedCommOperationException e)
{
MessageDialog.openInformation(null, "OpenComm ", "Set_Port ");
e.printStackTrace();
return false;
}
//設置輸入流
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
MessageDialog.openInformation(null, "OpenComm ", "Set_InputStream ");
e.printStackTrace();
return false;
}
//設置輸出流
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
MessageDialog.openInformation(null, "OpenComm ", "Set_OutputStream ");
e.printStackTrace();
return false;
}
//當串口有數據時通知
serialPort.notifyOnDataAvailable(true);
//當串口通訊中斷時通知
serialPort.notifyOnBreakInterrupt(true);
//接收數據超時設置
try {
serialPort.enableReceiveTimeout(30);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
return false;
}
//設置一個串口數據暫存區
strBuffer=new StringBuffer();
//給當前串口添加一個監聽器 DisposeSerialportMessage
try {
serialPort.addEventListener(
new SerialPortEventListener()
{
public void serialEvent(SerialPortEvent e)
{
disposeSerialportMessage(e);
}
}
);
} catch (TooManyListenersException e) {
e.printStackTrace();
return false;
}
return true;
}
[/code]
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -