2
votes

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.

2

2 Answers

6
votes

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.

0
votes

You are not reading the port correctly.

Here's an example on how to properly read data input from a comport.

public static void Main()
{
    SerialPort mySerialPort = new SerialPort("COM1");

    mySerialPort.BaudRate = 9600;
    mySerialPort.Parity = Parity.None;
    mySerialPort.StopBits = StopBits.One;
    mySerialPort.DataBits = 8;
    mySerialPort.Handshake = Handshake.None; // Some device needs a different handshake.

    mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

    mySerialPort.Open();

    Console.WriteLine("Press any key to continue...");
    Console.WriteLine();
    Console.ReadKey();
    mySerialPort.Close();
}

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    Debug.Print("Data Received:");
    Debug.Print(indata);
}