kami kami - 2 months ago 40
C# Question

SerialPort.ReadLine() does not read data from USB COM port sent by Arduino

I'm sending textual data to COM15 (via micro USB) using Arduino. On my desktop, I'm trying to read the data from my C# application. However, when I run it, the console simply shows nothing and the program stucks at the line "string s = myPort.ReadLine()".

The following is my C# program:

static void Main(string[] args)
{
var myPort = new SerialPort("COM15", 115200);
myPort.Open();
while (true)
{
var s = myPort.ReadLine(); // execution stucks here waiting forever!
Console.WriteLine(s);
}
}


The following is the Arduino code (sends data to COM15):

int counter = 1;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}

void loop() {
// put your main code here, to run repeatedly:
Serial.println(" Data Loop = " + String(counter));
counter++;
delay(500);
}


The arduino serial monitor does show the data being received at COM15. I also tried other software that read COM ports and verified that the data is available at the port.

Answer

By adding the following line before myPort.Open() command, I managed to fix my issue and read from the COM successfully:

myPort.DtrEnable = true;

You may ask what is Dtr flag. Dtr stands for "Data Terminal Ready" and according to Wikipedia:

Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

Comments