mercredi 1 juillet 2015

Write string value to the arduino or the serial port using java

I am trying to write string data to my serial port, but now I cannot write the string value to the arduino serial port. Can anyone help me to solve this.

This is my Java code:

portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals("COM9")) {
                try {
                    serialPort = (SerialPort)
                    portId.open("SimpleWriteApp", 2000);
                } catch (PortInUseException e) {
                    System.out.println("Error1 is "+ e);
                }
                try {
                    outputStream = serialPort.getOutputStream();
                } catch (IOException e) {
                    System.out.println("Error2 is "+ e);
                }
                try {
                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    System.out.println("Error3 is "+ e);
                }
                try {
                    String number = "1";
                    byte arduino[] = number.getBytes();
                    for(int i=0; i<arduino.length; i++){
                        outputStream.write(arduino[i]);
                    }
                    outputStream.flush();
                } catch (IOException e) {
                    System.out.println("Error is4 "+ e);
                }

            }
        }
    }

Aucun commentaire:

Enregistrer un commentaire