gunjannigam 28 Junior Poster

I am using Java Comm API to send some data on Serial Port and Again Checking it back. The Problem is that I am not able to get the correct data back always. Sometime I see a garbage value there.
Here is my Code
Setup SerialPort For Sending Data

public void setUpSerialPort()
{
    CommPortIdentifier portId = null;
    try
    {
        portId = CommPortIdentifier.getPortIdentifier("COM7");
    } catch (NoSuchPortException ex) {
          JOptionPane.showMessageDialog(null, "Sorry no such port exists.Please check your connections");
          serialflag=false;
    }
    try
    {
        mySerialPort = (SerialPort) portId.open("AutoPilot on COM7",5000);
            //configure the port
    } catch (PortInUseException ex) {
            JOptionPane.showMessageDialog(null, "Sorry port already in use by other device.\nClose all other applications that might be accessing this port");
            serialflag=false;
    }
  	//configure the port
    try
    {
        mySerialPort.setSerialPortParams(115200,mySerialPort.DATABITS_8,mySerialPort.STOPBITS_1,mySerialPort.PARITY_NONE);
        mySerialPort.setFlowControlMode(mySerialPort.FLOWCONTROL_NONE);
        mySerialPort.setInputBufferSize(1);
        mySerialPort.setOutputBufferSize(1);
                    
  	 } catch (Exception e){JOptionPane.showMessageDialog(null, "Sorry could not connect due to Windows error. Please retry");serialflag=false;}
            System.out.println(mySerialPort.getInputBufferSize());
            System.out.println(mySerialPort.getBaudRate()+" "+ mySerialPort.getDataBits()+" "+" "+mySerialPort.getStopBits()+" "+mySerialPort.getParity()+" "+mySerialPort.getFlowControlMode());
    try
    {
        in = new DataInputStream(mySerialPort.getInputStream());
    } catch (IOException ex) {
           ex.printStackTrace();
     }
     try
     {
        mySerialPort.addEventListener(this);
  		mySerialPort.notifyOnDataAvailable(true);
  	 } catch (TooManyListenersException e) {System.out.println("couldn't add listener");}
     
  	}

Code where I send Data

byte[] message = new byte [14];
                int crc=0;
			
				byte[] mesg;
                byte[] arr = new byte [2];
                mesg="#".getBytes();
                message[0] = mesg[0];

                mesg = "UP".getBytes();
                message[1] = mesg[0];
                message[2] = mesg[1];
				arr = shortToByteArray((short)slider1.getValue());
				message[4] = arr[0];
				message[3] = arr[1];
				arr = shortToByteArray((short)slider2.getValue());
				message[6] = arr[0];
				message[5] = arr[1];
				arr = shortToByteArray((short)slider3.getValue());
				message[8] = arr[0];
				message[7] = arr[1];
                mesg = frameId1.getBytes();
                message[9] = mesg[0];
                message[10] = mesg[1];
                for(int i=0;i<11;i++)
                    crc=crc^message[i];
                //mesg =
                mesg = "000".getBytes();
                message[11] = mesg[0];
                message[12] = mesg[1];
                message[13] = mesg[2];


               
                //setUpSerialPort();
                //System.out.println(mySerialPort.getBaudRate()+" "+ mySerialPort.getDataBits()+" "+" "+mySerialPort.getStopBits()+" "+mySerialPort.getParity()+" "+mySerialPort.getFlowControlMode());
                out = new PrintStream(mySerialPort.getOutputStream());
                           out.write(message);
                /*out.write("#".getBytes());
                out.write("UP".getBytes());
                out.write(message, 3,6);
                
                out.write(frameId1.getBytes());
                out.write("000".getBytes*/
public static byte[] shortToByteArray(short s)
	{
        return new byte[] { (byte) ((s & 0xFF00) >> 8), (byte) (s & 0x00FF) };
	}

I had sending the complete package in one go and sending in bytewise also

This is the code where I setUP to Recieve data. The value of WHichPort in now COM4 and whichSpeed is 115200

public PhysCompSerialDemo (String whichPort, int whichSpeed) throws PortInUseException {
  		CommPortIdentifier portId = null;
        try {
            portId = CommPortIdentifier.getPortIdentifier(whichPort);
        } catch (NoSuchPortException ex) {
           ex.printStackTrace();
        }
        
  			//open the port
  			mySerialPort = (SerialPort)portId.open("SerialExample " + whichPort, 2000);
  			//configure the port
           
  			try {
  					mySerialPort.setSerialPortParams(whichSpeed,
  					mySerialPort.DATABITS_8,
  					mySerialPort.STOPBITS_1,
  					mySerialPort.PARITY_NONE);
                    mySerialPort.setFlowControlMode(mySerialPort.FLOWCONTROL_NONE);
                    mySerialPort.setInputBufferSize(1);
                    
  			} catch (Exception e){e.printStackTrace();}
        System.out.println(mySerialPort.getBaudRate()+" "+ mySerialPort.getDataBits()+" "+" "+mySerialPort.getStopBits()+" "+mySerialPort.getParity()+" "+mySerialPort.getFlowControlMode());
 try {
            in = new DataInputStream(mySerialPort.getInputStream());
            out = new PrintStream(mySerialPort.getOutputStream());
           
        } catch (IOException ex) {
           ex.printStackTrace();
        }
  			try {
  				mySerialPort.addEventListener(this);
  				mySerialPort.notifyOnDataAvailable(true);
  			} catch (TooManyListenersException e) {System.out.println("couldn't add listener");}
       
  			
  		

  	}

  	public void serialEvent(SerialPortEvent event) {

  			
  		if (event.getEventType()== SerialPortEvent.DATA_AVAILABLE) {
            

            try {
              
                 while(((check[0]=(char)(in.read()))!='#')||((check[1]=(char)(in.read()))!='U')||((check[2]=(char)(in.read()))!='P'));
                 for(int i=0;i<3;i++)
                {
                read_short[1]=in.readByte();
                read_short[0]=in.readByte();
                DataInputStream data_stream1 = new DataInputStream(new ByteArrayInputStream(read_short));
                short_rec[i]=data_stream1.readShort();
               
                }
                 for(int i=0;i<3;i++)
                    System.out.print(short_rec[i]+" ");
                for(int i=0;i<5;i++)
                    System.out.print((char)in.read()+" ");
                System.out.println();
            } catch (Exception ex) {
               ex.printStackTrace();
            }
  			
            
  		} //it’s a serial port event

  	}

Some time I am getting correct data and some time there is a garbage
Please Explain how to solve this