-1

シリアルポートを介して自分の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) {
                }
            }
        }
    }
}

}

このコードは正しいですか、それともこのコードに何らかの変更を加える必要がありますか...。

4

1 に答える 1

0

それが機能する場合、私が見ることができることは明らかに悪いことではありません!私が指摘する唯一のことは、closeステートメント(最後にシリアルポートを閉じるときなど)をfinallyブロックに入れて、常に実行されるようにすることです(VMの終了は別として)。メソッドによってスローされoutputStream.write(messageString.getBytes());た例外close()が実行されない場合があります。

また、例外を無視するべきではありません。少なくとも、printStackTrace()何も起こらないことを確認するためにaを実行してください。

于 2011-08-04T09:15:21.053 に答える