Jacob Jacob - 1 month ago 5
C# Question

Serial.WriteLine("My message!"); Appending?

I am trying to send a message from a C# application to my arduino on the serial port.

However it hangs on the WriteLine. It never ends and when I read whats been stored in my buffer on the arduino it's like ive been sending it over and over 100 times.

Code on c# app

public void testSend()
{
if (mySerialPort.IsOpen)
{
//setup
//mySerialPort.Open();
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
mySerialPort.WriteTimeout = 500;
try
{
mySerialPort.WriteLine("Sent from my c# app!");
}
catch(TimeoutException)
{
//Console.WriteLine("Timeout while sending data");
}

//mySerialPort.Close();
}
else
{
Console.WriteLine("Port already open!");
}

}


Code on arduino(for reference and clearance )

void setup()
{
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial)
{
; // wait for serial port to connect. Needed for native USB
}
}
char* buf = malloc(1024);

int ReciveData()
{

if (Serial.available())
{
// read the incoming bytes:
String temp = Serial.readString();
if (temp.length() > 0)
{
temp.toCharArray(buf, temp.length() + 1);
}
}
}

void loop()
{
Serial.print("Sent from arduino!");
Serial.println(buf);
delay(1000);
ReciveData();
}
}


This is how it looks. Here is 4 messages, every send start with "Sent from arduino!". when i read it. You can see on line 1 and 2 everything is good but when I start the c# application and it goes Hawaii

Sent from arduino!Sent from serial terminal!
Sent from arduino!Sent from serial terminal!
Sent from arduino!Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!

Sent from arduino!Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!
Sent from my c# app!

Answer

Not sure why. But when i tried to add \0 at end of the string it worked.

        try 
        {
            mySerialPort.WriteLine("Sent from my c# app! \0");
        }