Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# serialPort: Application hangs if there is no recipient on Write() (virtual null modem)

Tags:

c#

serial-port

I am developing a PC WinForms application in C# that needs to connect to a microcontroller later. For now, for testing purposes, I have created a virtual null modem on my computer and linked it with a terminal program.

The virtual null modem I'm using is "com0com": http://sourceforge.net/projects/com0com/

Here is a screenshot of the COM port pair settings: enter image description here

In my application I use the component serialPort. This is how the serialPort is set up:

public bool SerialPortSetup(String cp)
{
    String port = cp;
    int baud = 19200;
    Parity parity = Parity.None;
    int databit = 8;
    StopBits stopbit = StopBits.One;

    try
    {
        // Initialize serial port
        serialPort1 = new SerialPort(port, baud, parity, databit, stopbit);
        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPortDataReceived);
        serialPort1.Open();
        return true;
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
        return false;
    }
}

Other properties of the serialPort: enter image description here

The terminal program that I've connected to COM2 is set up with the same baudrate, parity, databit, stopbit, etc. When I have connected my own app to COM1, and the terminal to COM2, it all works just fine. Both writing and reading in both directions.

However, when I don't use the COM2 port (that is, the terminal program is not opened), my app hangs just the second I start to use serialPort1.Write(str), where str is just a random string. When running my app from Visual Studio, I can only close it by stopping the debugging. It's not like Windows marks it as "not responding". Btw, I always check for an opened serialPort before I write to it.

I need this problem to go away. Ideas?

like image 966
gosr Avatar asked Dec 17 '22 07:12

gosr


1 Answers

I know that this question is a bit on the old side, but I came across it when looking for a solution to the same problem.

You need to change a couple of settings in com0com, which are described here http://www.magsys.co.uk/comcap/onlinehelp/null_modem_emulator_com0com.htm.

In brief, you need to enable buffer overrun for the receiving port, and baud rate emulation on the sending port. This is simple to do using the dialog in the OP image.

like image 197
Matt Avatar answered Jan 30 '23 06:01

Matt