I have a MCU (Arduino) that is connected through USB serial to PC. I am trying to get a reliable and accurate data when it is transmitted from MCU. I only need 1 line of data. More often than not I got shuffled or broken data. I have been trying to change my codes on both side PC and MUC like timing, set amount of time to read and write. However, I couldn't get it to work. The below are Java code on PC and C code on MCU that I got from https://www.xanthium.in/. I just edited it little bit.

package serialportsavail;

import com.fazecast.jSerialComm.*;
public class SerialPortsAvail
   public static void main (String[] Args)
     SerialPort [] AvailablePorts = SerialPort.getCommPorts();
     int i = 0;
       // use the for loop to print the available serial ports
         for(SerialPort S : AvailablePorts)
              System.out.println(i++ + "  " + S.getDescriptivePortName());
    //Open the first Available port
        SerialPort MySerialPort = AvailablePorts[0];
        int BaudRate = 9600;
        int DataBits = 8;
        int StopBits = SerialPort.ONE_STOP_BIT;
        int Parity   = SerialPort.NO_PARITY;

        //Sets all serial port parameters at one time

        //Set Read Time outs

        MySerialPort.openPort(); //open the port

                //Reading from COM port using Java

            while (true)
              byte[] readBuffer = new byte[100];

              int numRead = MySerialPort.readBytes(readBuffer,

              System.out.print("Read " + numRead + " bytes -");

              //Convert bytes to String
              String S = new String(readBuffer, "UTF-8"); 

              System.out.println("Received -> "+ S);

        catch (Exception e) 

       // MySerialPort.closePort(); //Close the port

========= C code========

void setup()
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps 8N1

void loop()
  char TextToSend[] = "Hello to Java from Arduino UNO";

  char NumToSend[] = "120489";

  Serial.print(TextToSend); // sends a \n with text
  Serial.println(NumToSend); // sends a \n with text

========== output from my PC
output from my pc

New contributor
Henry is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • \$\begingroup\$ I see neither shuffled nor broken: Please provide (access to) a specification of SerialPort..readBytes(buffer, bufferLength). \$\endgroup\$
    – greybeard
  • \$\begingroup\$ I recommend not to use blocking mode with timeout on the receiver side. Collect all coming data in a string until it contains the end of line symbol \n and then print it to System.out. \$\endgroup\$
    – Jens
    19 hours ago


Your Answer

Henry is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.