Tails270 Tails270 - 2 months ago 16
C# Question

C# Serial Commications issues with Arduino

I have been struggling with commincations speeds with some code.

So i want to increase the baud rate for both the code & Arduino. But if i leave the 9600 baud rate, the data stops sending & reciving properly.
So i set up a simple test program.

Arduino Code:

void setup()
{
Serial.begin(9600);
Serial.setTimeout(10);
}

void loop()
{
if (Serial.available())
{
String Data = Serial.readStringUntil('#');
if (Data == "Test")
{
Serial.println("Recived");
}
}
delay(1);
}


c# Code:

SerialPort Port = new SerialPort("COM4", 9600);
Port.Open();
if (Port.IsOpen)
{
Port.Write("Test#");
System.Threading.Thread.Sleep(1000);
String Read = Port.ReadExisting();
Port.Close();
}


So running that String Read comes back with "Recived\r\n".
Change the baud rate to 19200 and it comes back with "".

Any ideas why this is occuring?

Edit: If i use the Arduino IDE's Serial Monitor Program, this works just fine regardless of baudrate used. Its as soon as i use c# that it that this issue occurs. Which rules out hardware issues i believe.

Thanks

Answer

Thankyou for you inputs.

Think i have found a solution, although not to clear about why.

I think it was due to the Serial.Avalible() Command. Appears i needed to send though some data first to make it register the port is open.

So modifying my C# code to this: Works

SerialPort Port = new SerialPort("COM4", 9600);
Port.Open();
if (Port.IsOpen)
{
     Port.Write("#");
     Port.Write("Test#");
     System.Threading.Thread.Sleep(1000);
     String Read = Port.ReadExisting();
     Port.Close();
}

Thanks a lot

Comments