Serial data not being passed in C # application

I have a C # application where serial (COM1) data is sometimes not transmitted. Below is a simplified snippet of my code (removed entries in text notes):

    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's odd is that this same code works fine when the port is set to 115.2 Kbps. However, when working at 9600 bps, the data to be transmitted by this code does not appear to be transmitted. I verified this by checking the receive flag on the remote device. Exceptions are not excluded from the try statement. Is there something else (Flush, etc.) that I should be doing to ensure data transfer? Any thoughts or suggestions that you may be appreciated. I am using Microsoft Visual C # 2008 Express Edition. Thanks.

+2


a source to share


1 answer


Remove try / catch blocks. This should give you a chance to see the TimeoutException that you get because you set the WriteTimeout value too much. Sending 516 bytes at 9600 baud takes 538 milliseconds.



Your other settings are recipes for problems as well. Get rid of ReceivedBytesThreshold and DiscardNull.

+4


a source







All Articles