2011-08-04 117 views
-1

我想發送命令到whihch通過串口連接到我的電腦的embadded PC連接嵌入式PC ...這裏是我使用的代碼...如何發送命令通過串口

公衆類寫{

static Enumeration portList; 
static CommPortIdentifier portId; 
static String messageString = "Hello, world!\n"; 
static SerialPort serialPort; 
static OutputStream outputStream; 

public static void main(String[] args) { 
    portList = CommPortIdentifier.getPortIdentifiers(); 
    while (portList.hasMoreElements()) { 
     portId = (CommPortIdentifier) portList.nextElement(); 
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
      if (portId.getName().equals("COM1")) { 
       try { 
        serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000); 
        System.out.println("openning the port..."); 
       } catch (PortInUseException e) { 
       } 
       try { 
        outputStream = serialPort.getOutputStream(); 
        System.out.println("sending the command..."); 
       } catch (IOException e) { 
       } 
       try { 
        serialPort.setSerialPortParams(9600, 
          SerialPort.DATABITS_8, 
          SerialPort.STOPBITS_1, 
          SerialPort.PARITY_NONE); 

       } catch (UnsupportedCommOperationException e) { 
       } 
       try { 
        outputStream.write(messageString.getBytes()); 
        serialPort.close(); 
       } catch (IOException e) { 
       } 
      } 
     } 
    } 
} 

}

是這個代碼是正確的,還是應該有一些修改這個代碼....

+1

那麼,它的工作?你試過了嗎? – berry120

+0

雅我做...它的工作,但我仍然懷疑代碼...這是正確的嗎? –

+0

berry120,上面的代碼是發送反正有發送一個特定的命令,如CRC「循環冗餘檢查」到另一臺PC機! –

回答

0

如果成功則沒有什麼顯然w ^榮,我可以看到!我唯一指出的一點是,在finally塊中放置close語句(比如當你關閉串口時)是一個很好的習慣,所以它們總是被執行(拋開VM終止)。目前if outputStream.write(messageString.getBytes());引發的異常將不會執行close()方法。

你也不應該忽略異常,至少要做一個printStackTrace()以確保沒有任何事情發生。