Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9133041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:25:08+00:00 2026-06-17T08:25:08+00:00

I am working on a project which requires precise time(ms) for each data entry

  • 0

I am working on a project which requires precise time(ms) for each data entry I read from a serial port connected to an encoder (US digital S5 Optical Shaft Encoder with a QSB).

I installed the encoder on a small cart where I use it to count the speed of the cart.

Here is what I did so far:

  1. connect to the serial port and write command to QSB to tell the encoder to stream data. commands available here:

    http://www.usdigital.com/assets/general/QSB%20Commands%20List_1.pdf
    http://www.usdigital.com/assets/general/QSB%20Applications%20Examples.pdf

  2. Use readline() to read received data.

  3. put all lines of data into one StringBuilder and output it to a file.

I am able to get data entries in between 1ms when I set the output value threshold and interval rate to as fast as possible.
Here is what I got:

----time stamp(h/m/s/ms)-------value

data with correct time stamp: https://www.dropbox.com/s/pvo1dz56my4o99y/Capture1.JPG

However, there are abrupt “jumps”, roughly 200ms when data is continuous (I am rolling the cart in a constant speed)

data with incorrect time stamp: https://www.dropbox.com/s/sz3sxwv4qwsb2cn/Capture2.JPG

Here is my code:

private void buttonOpenEncoderPort_Click(object sender, EventArgs e)
    {
        serialPortEncoder.Write("S0E\r\n");//start streaming data
        System.Threading.Thread.Sleep(500);
        serialPortEncoder.Write("W0B0\r\n");//set threshold to 0 so the encoder will stream data a the interval I set.
        System.Threading.Thread.Sleep(500);
        serialPortEncoder.Write("W0C0000\r\n");//set output interval to 0 so it will stream as fast as possible
        System.Threading.Thread.Sleep(1500);
        backgroundWorkerEncoder.RunWorkerAsync();}
        //I am using a background worker to pull data out.


 private void backgroundWorkerEncoder_DoWork(object sender, DoWorkEventArgs e)
    {
        while (serialPortEncoder.IsOpen)
        {
            if (serialPortEncoder.BytesToRead != 0)
            {
                try
                {
                    String s = serialPortEncoder.ReadLine();//read from encoder
                    LazerBucket.Add(getCurrentTimeWithMS(timeEncoder) + "-----" + s + "\r\n");//put one line of data with time stamp in a List<String>
                    richTextBoxEncoderData.BeginInvoke(new MethodInvoker(delegate()
                    {
                        richTextBoxEncoderData.Text = s; })); //update UI

                }
                catch (Exception ex) { MessageBox.Show(ex.ToString()); }                   
            }

        }
    }

private String getCurrentTimeWithMS(DateTime d)//to get time
    {
        StringBuilder s = new StringBuilder();
        d = DateTime.Now;
        int hour = d.Hour;
        int minute = d.Minute;
        int second = d.Second;
        int ms = d.Millisecond;
        s.Append("  ----" + hour.ToString() + ":" + minute.ToString() + ":" + second.ToString() + ":" + ms.ToString());
        return s.ToString();
    }

I would appericiate it if someone could find the cause of the time jump. 200ms is too much to be ignored.

EDIT: 

As suggested, I tried Stopwatch but still there are 200ms delay. But when I print out time stamps and BytesToRead together, I found that data in the buffer is decreasing as readLine() is being executed. Eventually BytesToRead will drop to single digit and that’s where the delay happens. I am looking for better solutions on how to implement threads. And also explanations for the delay. Maybe I am reading to fast so the buffer can’t keep up with me?

EDIT:

problem solved. see my answer below. Thanks for replying though. Stopwatch really helps. Now I am trying to work out whether event driven or polling is better.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:25:09+00:00Added an answer on June 17, 2026 at 8:25 am

    Are you using C# 4.5? If so, I highly recommend using async/await over BackgroundWorker.

    Also, DateTime isn’t really accurate for real-time applications. I would recommend DateTime strictly as a start time and then using Stopwatch in System.Diagnostics to get the elapsed time since the start time.

    private void backgroundWorkerEncoder_DoWork(object sender, DoWorkEventArgs e)
    {
      var startTime = DateTime.Now;
      var stopwatch = Stopwatch.StartNew();
    
      while (serialPort.IsOpen && !backgroundWorker.CancellationPending)
      {
        if (serialPort.BytesToRead > 0)
        {
          try
          {
            var line = serialPort.ReadLine();
            var timestamp = (startTime + stopwatch.Elapsed);
    
            var lineString = string.Format("{0}  ----{1}", 
                                           line,
                                           timestamp.ToString("HH:mm:ss:fff"));
    
            // Handle formatted line string here.
          }
          catch (Exception ex)
          {
            // Handle exception here.
          }
        }
      }
    

    As for the 200 ms discrepancy, it could be a variety of things. Perhaps the BackgroundWorker is on a lower priority and doesn’t get as much CPU time as you hoped. Could also be something on the I/O side of either SerialPort or the actual serial device itself.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I was working on a project which requires to download content from a database.
I am working on a project report which requires some tricky output from a
I'm working on a project which requires me to calculate the heading from a
I am working on a project which requires jquery scrollTo plugins from Ariel Flesler:
I am working on a project, which requires me to select a item from
I am currently working on a project which requires migration of content from different
I am working on a project which requires creating a number of JButtons. Each
Hello everyone i am working on a project which requires me to export some
I have started working on a project which requires Natural Language Processing. We have
I'm working on a project for my companies intranet which requires that multiple attached

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.