6 Replies - 1477 Views - Last Post: 21 December 2011 - 08:05 AM Rate Topic: -----

#1 fb69  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 08-December 11

use threading to read the data from com ports every 3 seconds

Posted 20 December 2011 - 08:00 PM

I'm reading com ports data, Currently, all the data is being read continuously from the com ports. And I would like to use threading such that it will read the data every 3 seconds and update the data on the listbox. Please take a look at my codes attached. If I were to input the thread and sleep for 3s, the data displayed on the listbox will be delayed, I would like the data displayed on the listbox tally with the device on the com ports. How do I do that?

        private delegate void setTextDeleg(string text);
        public delegate void myDelegate();

        
        SerialPort serialPortN = new SerialPort();
        List<byte> bBuffer = new List<byte>(125);


        private void btnConnect_Click(object sender, EventArgs e)
        {
        
            if (this.cboCom.SelectedIndex == -1)
            {
                MessageBox.Show("Please select COM Port first!");
            }

            else
                if (serialPortN.IsOpen)
                    serialPortN.Close();

            try
            {
                {
                    serialPortN.PortName = cboCom.Text;
                    serialPortN.BaudRate = 9600;
                    serialPortN.Parity = Parity.None;
                    serialPortN.DataBits = 8;
                    serialPortN.StopBits = StopBits.One;
                    serialPortN.Encoding = System.Text.Encoding.ASCII;
                }

                serialPortN.Open();

                label1.Text = cboCom.Text + " is opened";

serialPortN.DataReceived += new SerialDataReceivedEventHandler(datareceived);

//Thread
                Thread thread1 = new Thread(new ThreadStart(update));
                thread1.Start();  

              
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        void datareceived(object sender, SerialDataReceivedEventArgs e)
        {            
            myDelegate d = new myDelegate(update);
            listBox1.Invoke(d, new object[] { });
           
        }

        
        public void update()
        {          
            while (serialPortN.BytesToRead > 0)
                bBuffer.Add((byte)serialPortN.ReadByte());
            ProcessBuffer(bBuffer);
   }

        private void ProcessBuffer(List<byte> bBuffer)
        {
            int numberOfBytesToRead = 125;

            if (bBuffer.Count >= numberOfBytesToRead)
            {
                 this.Invoke(new Action(() =>
                    listBox1.Items.Add("SP: " + (bBuffer[43].ToString()) + "  " + " HR: " + (bBuffer[103].ToString()) + " Time: ")
                  ));

  			//Sleep thread for 3s
Thread.Sleep(3000);
                // Remove the bytes read from the list
                bBuffer.RemoveRange(0, numberOfBytesToRead);
              
            }
       
        }        





Thanks all.

Is This A Good Question/Topic? 0
  • +

Replies To: use threading to read the data from com ports every 3 seconds

#2 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4577
  • View blog
  • Posts: 8,019
  • Joined: 08-June 10

Re: use threading to read the data from com ports every 3 seconds

Posted 20 December 2011 - 08:10 PM

Why exactly do you need threads to achieve this goal? Why not use a Timer set to tick every three seconds, and perform your read operation when the timer fires?
Was This Post Helpful? 0
  • +
  • -

#3 fb69  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 08-December 11

Re: use threading to read the data from com ports every 3 seconds

Posted 20 December 2011 - 08:27 PM

View PostCurtis Rutland, on 20 December 2011 - 08:10 PM, said:

Why exactly do you need threads to achieve this goal? Why not use a Timer set to tick every three seconds, and perform your read operation when the timer fires?


If I were to input timer tick, I'm unsure where to place the codes. I've tried inserting the timer on the processbuffer method but the data is read continuously still.
Was This Post Helpful? 0
  • +
  • -

#4 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4577
  • View blog
  • Posts: 8,019
  • Joined: 08-June 10

Re: use threading to read the data from com ports every 3 seconds

Posted 21 December 2011 - 02:02 AM

Timers use events, so you'd have to subscribe to it's Tick or Elapsed event, and perform your operation there. There's more than one type of timer, each with different resolutions and uses, so to suggest one I'd have to know what type of project this is, Forms, Console/Service, or WPF?
Was This Post Helpful? 0
  • +
  • -

#5 fb69  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 08-December 11

Re: use threading to read the data from com ports every 3 seconds

Posted 21 December 2011 - 02:19 AM

View PostCurtis Rutland, on 21 December 2011 - 02:02 AM, said:

Timers use events, so you'd have to subscribe to it's Tick or Elapsed event, and perform your operation there. There's more than one type of timer, each with different resolutions and uses, so to suggest one I'd have to know what type of project this is, Forms, Console/Service, or WPF?


Hi Curtis, I'm using windows forms. I'm not sure which code should i insert on the Tick event. Should it be the processbuffer method that I have?

Thanks!
Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,661
  • Joined: 23-August 08

Re: use threading to read the data from com ports every 3 seconds

Posted 21 December 2011 - 04:41 AM

If the Tick event is fired every time the timer goes off, and you want to do something every time the timer goes off, what do you THINK would go in the Tick event handler?

Programming is just as much -- if not MORE -- about THINKING as it is writing actual code.
Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5675
  • View blog
  • Posts: 12,192
  • Joined: 02-June 10

Re: use threading to read the data from com ports every 3 seconds

Posted 21 December 2011 - 08:05 AM

Why do you want to poll every three seconds - AT ALL?

We got away from this type of processor consuming crap years ago. That's why we have events. THe COM port will raise an event when there is new data to report.

Let's assume this is for some type of sensor (like temperature) so you don't want continual reading.

Make a new UserControl. That UserControl can then poll every 1 or 100 seconds as you set it to. Then the control should raise an event such as "NewTemperature(72)"

Your program would then receive the NewTeperature event with the arguments of what the temperature is.

Now you can keep all of your COM port, delay, sensing and so on in a single control that you can drag-n-drop on any form of any project without having to re-create it every time.


The tutorials below walk through making an application including inheritance, custom events and custom controls, object serialization and more.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1