开发者

Serial Data Not Transmitted in C# Application

开发者 https://www.devze.com 2022-12-31 14:42 出处:网络
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):

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 tran开发者_如何学Pythonsmitted? Any thoughts or suggestions you may have would be appreciated. I'm using Microsoft Visual C# 2008 Express Edition. Thanks.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号