how to send command to embedded pc connected by serial port
i want to send commands to to an embadded pc whihch connected to my pc through serial port ... here is the code that i use ...
public class Write {
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 (PortInUseExcep开发者_开发百科tion 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) {
}
}
}
}
}
}
is this code is correct, or there should be some modification to this code ....
If it works then there's nothing obviously wrong that I can see! The only thing I'd point out is that it's good practice to put close statements (such as when you're closing the serial port at the end) in finally blocks so they're always executed (VM termination aside.) At present if there's an exception thrown by outputStream.write(messageString.getBytes());
the close()
method wouldn't be executed.
You also shouldn't ignore exceptions, at least do a printStackTrace()
to make sure there's nothing happening.
精彩评论