Search code examples
c#timerserial-portserial-communication

C# How can I get number of byte on serial write buffer?


I want to print number of byte when serial write on label

So I make a timer for real-time updates.

    ...    
    System.Windows.Forms.Timer tmr_Progress = new System.Windows.Forms.Timer;
    tmr_Progress.Interval = 100;
    tmr_Progress.Tick += new EventHandler(tmr_Progress_Tick);   
    ...


    void tmr_Progress_Tick(object sender, EventArgs e)
    {
        lbl_Progress.Text = "Now Send : " + Serial.BytesToWrite;
    }

    ...

    private void serialWrite(byte[] sendByte )
    {
        try
        {
            tmr_Progress.Start();
            Serial.Write(sendByte, 0, sendByte.Length);
            tmr_Progress.Stop();
        }
        catch (Exception ex)
        {
            Trace.WriteLine("Write Error : " + ex.Message + " / " + ex.StackTrace);
        }
    }

But tmer isn't work and lable isn't update.

I check the timer before Serial.Write. Its enable property is turning true after tmr_Progress.Start();

but lable isn't update.. How can I get number of byte on serial write buffer ?


Solution

  • The Write method of the serial port writes data to the buffer of the .NET Framework or device driver and consumes almost no time.

    Since the timer is stopped immediately after Write, no timer event occurs.
    To generate timer event, delete "tmr_Progress.Stop ();" of after Write, and call it when BytesToWrite becomes 0 in the timer event handler.

    However, if there is an interval of 100 milliseconds, most of the data will have been sent. Is there any meaning to the progress indicator?
    Also, is the displayed wording appropriate? The value of BytesToWrite is the number of bytes remaining in the buffer to be sent.

    If you still want to display, you should first display the value of sendByte.Length on the label immediately after Write using invokrequired and invoke as shown in the text display of this article How to use SerialPort in .Net by using DataReceived event? DataReceived event.