Question

I have a C# application wherein serial (COM1) data appears to sometimes not get transmitted. Following is a simplified snippet of my code (calls to textBox writes have been removed):

    InitializeComponent()
    {
       // 
       // serialPort1
       // 
       this.serialPort1.BaudRate = 115200;
       this.serialPort1.DiscardNull = true;
       this.serialPort1.ReadTimeout = 500;
       this.serialPort1.ReceivedBytesThreshold = 2;
       this.serialPort1.WriteTimeout = 500;
       this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
    }

        if (radioButtonUart9600.Checked)
        {
           serialPort1.BaudRate = 9600;

           try
           {
              serialPort1.Open();
           }
           catch (SystemException ex)
           {
              /* ... */
           }
        }

        try
        {
           serialPort1.Write("D");
           serialPort1.Write(msg, 0, 512);
           serialPort1.Write("d");
           serialPort1.Write(pCsum, 0, 2);
        }
        catch (SystemException ex)
        {
           /* ... */
        }

What is odd is that this same code works just fine when the port is configured for 115.2Kbps. However, when running at 9600bps data that should be transmitted by this code seems to not get transmitted. I have verified this by monitoring the receive flag on the remote device. No exceptions are thrown from within the try statement. Is there something else (Flush, etc.) that I should be doing to make sure the data is transmitted? Any thoughts or suggestions you may have would be appreciated. I'm using Microsoft Visual C# 2008 Express Edition. Thanks.

Was it helpful?

Solution

Remove these try/catch blocks. That ought to give you a chance to see the TimeoutException you get because you set the WriteTimeout value too low. Sending 516 bytes at 9600 baud takes 538 milliseconds.

Your other settings are recipes for trouble too. Get rid of ReceivedBytesThreshold and DiscardNull.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top