-1

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 (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) {
                }
            }
        }
    }
}

}

is this code is correct, or there should be some modification to this code ....

3
  • 1
    Well, does it work? Have you tried it? Aug 4, 2011 at 9:08
  • ya i do ... it works, but i still suspicious about that code ... is it the correct one ???
    – S Gaber
    Aug 4, 2011 at 9:12
  • berry120, the above coding is to send is there anyway to send a specific command such as CRC "cycle redundancy check" to the other PC machine !
    – S Gaber
    Aug 5, 2011 at 6:33

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.