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
MySerialPort.setComPortParameters(BaudRate,
DataBits,
StopBits,
Parity);
//Set Read Time outs
MySerialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,
3000,
0);
MySerialPort.openPort(); //open the port
//Reading from COM port using Java
try
{
while (true)
{
byte[] readBuffer = new byte[100];
int numRead = MySerialPort.readBytes(readBuffer,
readBuffer.length);
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)
{
e.printStackTrace();
}
// 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
delay(3000);
}
SerialPort..readBytes(buffer, bufferLength)
. \$\endgroup\$