8 Replies - 252 Views - Last Post: 07 February 2012 - 06:07 AM Rate Topic: -----

Topic Sponsor:

#1 fb69  Icon User is offline

  • New D.I.C Head

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

Unable to display data on Listbox after disconnect COM Port

Posted 05 February 2012 - 08:00 PM

Hi all,
I've 2 buttons. Button Connect(open com port) & Disconnect(close port). When I click on the connect button, the timer will trigger and display the data on Listbox from the com port every few seconds. When I click disconnect and click connect button again, the data will not be displayed on the Listbox and the timer is not triggered. Why is that so?

Here;s my code: (Using C# Windows Form VS2008)
 System.Timers.Timer timer = new System.Timers.Timer();       
        List<byte> buffer = new List<byte>(125);


        public ReadData()
        {
            InitializeComponent();
            
            timer.Interval = 5000;
            timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
          
        }
 private void btnConnect_Click(object sender, EventArgs e)
    {
 
        if (serialPortN.IsOpen)
            serialPortN.Close();
        try
        {
            {
 
                serialPortN.PortName = "COM8";
                serialPortN.BaudRate = 9600;
                serialPortN.Parity = Parity.None;
                serialPortN.DataBits = 8;
                serialPortN.StopBits = StopBits.One;
                serialPortN.Encoding = System.Text.Encoding.ASCII;
                serialPortN.ReadTimeout = 500;
            }
 
            serialPortN.Open();
            label1.Text = "COM8" + " is opened";
 
            
            timer.Start();
 
            serialPortN.DataReceived += new SerialDataReceivedEventHandler(datareceived);
 

            btnDisconnect.Enabled = true;
            btnConnect.Enabled = false;
 
        }
 
        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)
            buffer.Add((byte)serialPortN.ReadByte());
        // Call a routine to process the data.          
        ProcessBuffer(buffer);
     }
 
  private void ProcessBuffer(List<byte> buffer)
    {
       int numberOfBytesToRead = 125;
        if (buffer.Count >= numberOfBytesToRead)
        {
//To display data on the console output
            this.Invoke(new Action(() =>
             Console.WriteLine(string.Format("SPO = {0}, PulseRate = {1}, Time = {2}",
                                                    buffer[43].ToString(),
                                                    buffer[103].ToString(),
                                                    DateTime.Now.ToString()
            ))));
 
            buffer.RemoveRange(0, numberOfBytesToRead);
        }
 
    }
 
   void TimerElapsed(object sender, ElapsedEventArgs e)
    {
 
        int numberOfBytesToRead = 125;
        if (buffer.Count >= numberOfBytesToRead)
        {
//To display data on the LISTBOX
            this.Invoke(new Action(() =>
            listBox1.Items.Add(string.Format("SPO = {0}, PulseRate = {1}, Time = {2}",
                                                    buffer[43].ToString(),
                                                    buffer[103].ToString(),
                                                    DateTime.Now.ToString()
            ))));
            buffer.RemoveRange(0, numberOfBytesToRead);
 
        }
 
  private void btnDisconnect_Click(object sender, EventArgs e)
        {
           
            listBox1.Items.Clear();
            serialPortN.Close();
            buffer.Clear();
}




Thanks all.

Is This A Good Question/Topic? 0
  • +

Replies To: Unable to display data on Listbox after disconnect COM Port

#2 tlhIn`toq  Icon User is offline

  • WillMyCodeWork = !FailedWhenYouTriedIt;
  • member icon

Reputation: 3290
  • View blog
  • Posts: 6,898
  • Joined: 02-June 10

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 06:21 AM

Why the timer? Just react to when the data comes in. Its a huge waste of CPU cycles to poll like that. Its just plain bad practice.

Personally, instead of trying to fix this so the timer works I'd invest my time in getting rid of the timer and react to the SerialPort.DataReceived.

Tutorial:
http://www.dreaminco...cation-in-c%23/
Was This Post Helpful? 1
  • +
  • -

#3 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1451
  • View blog
  • Posts: 5,763
  • Joined: 21-March 08

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 06:32 AM

Why are you using a timer? Simply use the DataReceived event and work from it. You don't need a timer. When the data comes in, read it from the SerialPort, then write it to the ListBox.

Also, notice that you are subscribing to the DataReceived event in the Connect button click. That's going to cause you weird problems because you never unsubscribe. So the second time you click the Connect button, you will now have two subscriptions to the event, which means it will fire twice. Then the third time you click the Connect button, you will have three subscriptions, which means it will fire three times everytime data is received.
Was This Post Helpful? 1
  • +
  • -

#4 fb69  Icon User is offline

  • New D.I.C Head

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

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 06:44 PM

View PosttlhIn`toq, on 06 February 2012 - 06:21 AM, said:

Why the timer? Just react to when the data comes in. Its a huge waste of CPU cycles to poll like that. Its just plain bad practice.

Personally, instead of trying to fix this so the timer works I'd invest my time in getting rid of the timer and react to the SerialPort.DataReceived.

Tutorial:
http://www.dreaminco...cation-in-c%23/


Hi, I insert the timer coz I would the data to be displayed every 5 seconds.. How can I do it without inserting the timer? Is there any codes? Thanks.
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • WillMyCodeWork = !FailedWhenYouTriedIt;
  • member icon

Reputation: 3290
  • View blog
  • Posts: 6,898
  • Joined: 02-June 10

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 06:47 PM

You want to deliberately slow down the display to every 5 second instead of showing the data immediately when it comes in? Really?
Was This Post Helpful? 0
  • +
  • -

#6 fb69  Icon User is offline

  • New D.I.C Head

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

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 06:54 PM

View Posteclipsed4utoo, on 06 February 2012 - 06:32 AM, said:

Why are you using a timer? Simply use the DataReceived event and work from it. You don't need a timer. When the data comes in, read it from the SerialPort, then write it to the ListBox.

Also, notice that you are subscribing to the DataReceived event in the Connect button click. That's going to cause you weird problems because you never unsubscribe. So the second time you click the Connect button, you will now have two subscriptions to the event, which means it will fire twice. Then the third time you click the Connect button, you will have three subscriptions, which means it will fire three times everytime data is received.


I would like the data to be displayed every 5 seconds on the listbox. How do I unsubscribe the event? Where is the best place to put my event? Sorry, coz i'm unsure Thanks!
Was This Post Helpful? 0
  • +
  • -

#7 fb69  Icon User is offline

  • New D.I.C Head

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

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 08:03 PM

View PosttlhIn`toq, on 06 February 2012 - 06:47 PM, said:

You want to deliberately slow down the display to every 5 second instead of showing the data immediately when it comes in? Really?


Hi, I don't wanna slow down the process.. If I were to slow down the process, the data displayed on the listbox will not be in realtime.. If I didn't insert the timer, it'll read the data continuously every seconds.. which makes it kinda difficult to read on the listbox.. Hmm..
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • WillMyCodeWork = !FailedWhenYouTriedIt;
  • member icon

Reputation: 3290
  • View blog
  • Posts: 6,898
  • Joined: 02-June 10

Re: Unable to display data on Listbox after disconnect COM Port

Posted 06 February 2012 - 09:23 PM

If you wait 5 second to display, its not in real time either.

If you read only when data comes in THAT is real time.

Are you saying you have data CONTINUOUSLY with no break?

If that were the case then you would be lagging behind badly because of the delay.

If you have CONTINUOUS data and display it as it comes in...

or have CONTINUOS data and only show chunks of it ever 5 seconds, how does it make it any better? Either the user can read as fast as the data comes in or they can't.

I honestly think you don't understand the data coming in, or the idea of responding to the datareceived event.
Was This Post Helpful? 0
  • +
  • -

#9 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1451
  • View blog
  • Posts: 5,763
  • Joined: 21-March 08

Re: Unable to display data on Listbox after disconnect COM Port

Posted 07 February 2012 - 06:07 AM

View Postfb69, on 06 February 2012 - 09:54 PM, said:

View Posteclipsed4utoo, on 06 February 2012 - 06:32 AM, said:

Why are you using a timer? Simply use the DataReceived event and work from it. You don't need a timer. When the data comes in, read it from the SerialPort, then write it to the ListBox.

Also, notice that you are subscribing to the DataReceived event in the Connect button click. That's going to cause you weird problems because you never unsubscribe. So the second time you click the Connect button, you will now have two subscriptions to the event, which means it will fire twice. Then the third time you click the Connect button, you will have three subscriptions, which means it will fire three times everytime data is received.


I would like the data to be displayed every 5 seconds on the listbox. How do I unsubscribe the event? Where is the best place to put my event? Sorry, coz i'm unsure Thanks!


To unsubscribe, you use a - instead of a +...

subscribe
serialPortN.DataReceived += new SerialDataReceivedEventHandler(datareceived);



unsubscribe
serialPortN.DataReceived -= new SerialDataReceivedEventHandler(datareceived);



The best place should be where you instantiate the SerialPort object. So whereever you have SerialPort serialPortN = new SerialPort();, then that's where you would subscribe to the DataReceived event.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1