views:

74

answers:

1

Hello. 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.

+3  A: 

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.

Hans Passant
+1, much better than my answer
Shiraz Bhaiji
Thanks, Hans. Increasing the WriteTimeout did the trick. Setting the ReceivedBytesThreshold and DiscardNull were intentional for this specific application. The remote device should always send two-byte responses, and sometimes it may send NULLs, which should be discarded anyways.
Jim Fell