Read Data From Serial and Display in a Textbox

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

39 Replies - 6526 Views - Last Post: 26 August 2011 - 08:36 AM Rate Topic: -----

#1 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Read Data From Serial and Display in a Textbox

Posted 21 August 2011 - 09:28 PM

Hello everyone, so what I'm trying to do is just read the data that is coming in from the Serial port and display it into a textbox. So far I have worked up the code below but I can't seem to get it to display in the textbox. Also the way I currently have it set up it should begin reading from the port at start up. I would like to set it up where it runs on a button click event. Any suggestion would be greatly appreciated.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace BalloonSat
{
    public partial class Form1 : Form
    {
        public SerialPort sp;
        string dataReceived = string.Empty;
        private delegate void SetTextDeleg(string text);

        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            // Instantiates a new Serial port and declares the speed at 57,600 bits per second
            sp = new SerialPort("COM1", 57600, Parity.None, 8, StopBits.One);
            this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

            // Open the Serial Port
            sp.Open();
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(100);

                // Read data from serial until it finds a carriage return
                string x = sp.ReadLine();
                this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { x });
            }
            catch
            {
            
            }
        }

        private void si_DataReceived(string data)
        {
            dataReceived = data.Trim();
            serialDataTextBox.Text = dataReceived;
        }
   }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Read Data From Serial and Display in a Textbox

#2 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 05:09 AM

Code looks fine to me. If you set a breakpoint in the sp_DataReceived SerialPort event, does the breakpoint get hit?
Was This Post Helpful? 0
  • +
  • -

#3 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 08:38 AM

Yes, when I run the program it stops at that breakpoint. The value of this.sp.DataReceived is null.
Was This Post Helpful? 0
  • +
  • -

#4 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 08:46 AM

Events don't really have values, so that's normal. Continue debugging and see if x has a value after string x = sp.ReadLine();.
Was This Post Helpful? 0
  • +
  • -

#5 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 08:53 AM

Maybe I'm doing something wrong, but I run the program and it stops at the breakpoint. So I press F11 to step into the program and I go through it line by line and every time I hit F11 after it highlights sp.Open() it will then open the program window and nothing else happens. If I continue to step through the program it starts completely over where I first began stepping into the program.
Was This Post Helpful? 0
  • +
  • -

#6 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 09:01 AM

Set a breakpoint at Thread.Sleep(100);. Set another breakpoint at dataReceived = data.Trim();. When the first breakpoint is hit, use F10 to step over the code. Once you get past string x = sp.ReadLine();, make sure x has a value. If it does, then hit F5. This will move it down to the next breakpoint. From there, make sure you still have the value.
Was This Post Helpful? 0
  • +
  • -

#7 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 09:09 AM

It's doing the same thing it was before. It's like it just skips over the sp_DataReceived function.
Was This Post Helpful? 0
  • +
  • -

#8 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 09:43 AM

What line of code are you putting your breakpoint on?
Was This Post Helpful? 0
  • +
  • -

#9 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 10:10 AM

I have breakpoints on these lines:

this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);



Thread.Sleep(100);



this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { x });



dataReceived = data.Trim();


Was This Post Helpful? 0
  • +
  • -

#10 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 10:17 AM

That first line isn't actually going to do anything that you can see. It WILL just go on. That line is subscribing to the DataReceived event. It DOES NOT fire the event. The SerialPort class will fire the event when some data comes through the serial port.

So with the third breakpoint at the BeginInvoke line, does x have a value?
Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland  Icon User is online

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


Reputation: 4531
  • View blog
  • Posts: 7,903
  • Joined: 08-June 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 10:32 AM

So far, everything I've read is as it should be. I think you're confused to what events actually are. You're not calling the sp_DataRecieved method at all. You're assigning it to sp's DataReceived event. When that event is triggered (by receiving data), the method will be called.

Here's an actual example of its use:

http://msdn.microsof...tareceived.aspx

Note that he's using ReadExisting, and he's not sleeping the thread or anything like that. You don't need to sleep the thread here, the method wouldn't be called if there wasn't already data waiting for you.

Also, are you sure you even need to Invoke to update the text box? You're not spawning new threads, so unless the SerialPort class does that behind the scenes, it's unnecessary. And even if it is necessary, you're over-complicating it significantly.You could replace your delegate, your method, and your BeginInvoke call with something like this:

Invoke(new Action(() => serialDataTextBox.Text = x.Trim()));

Was This Post Helpful? 0
  • +
  • -

#12 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 10:43 AM

@Curtis Rutland,

Did you mean like this?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace BalloonSat
{
    public partial class Form1 : Form
    {
        public SerialPort sp;
        string dataReceived = string.Empty;
        private delegate void SetTextDeleg(string text);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Instantiates a new Serial port and declares the speed at 57,600 bits per second
            sp = new SerialPort("COM1", 57600, Parity.None, 8, StopBits.One);
            this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

            // Open the Serial Port
            sp.Open();
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                // Read data from serial
                string data = sp.ReadExisting();
                Invoke(new Action(() => serialDataTextBox.Text = data.Trim()));
            }
            catch
            {

            }
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#13 Curtis Rutland  Icon User is online

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


Reputation: 4531
  • View blog
  • Posts: 7,903
  • Joined: 08-June 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 10:56 AM

Pretty much. You can drop the delegate too. Action is a premade delegate that fits what you need here. Before you make your own delegates, see if you can't use an Action or a Func delegate, since they're already made, and they're generic.

Other than that, I'd suggest you not suppress exceptions. You'd never know if something went wrong in your reading code, because you've got an empty catch clause. For debugging purposes, either remove the try/catch completely, or do something like this:

catch (Exception ex){
    //production error handling goes here
#if DEBUG
    //throw the exception so the debugger can catch it for you,
    //but only if we're in debug mode.
    throw ex;
#endif
}


But better if you implement some kind of handling.
Was This Post Helpful? 1
  • +
  • -

#14 RandomlyKnighted  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,370
  • Joined: 14-January 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 11:19 AM

I get an error on Action. It says this:

Using the generic type 'System.Action<T>' requires 1 type arguments

I looked it up and it says it takes the parameter of the method that it encapsulates. So what does that mean?
Was This Post Helpful? 0
  • +
  • -

#15 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: Read Data From Serial and Display in a Textbox

Posted 22 August 2011 - 11:57 AM

What framework version are you targeting? In order to use the non generic Action delegate, you need to be targeting framework 3.5, or higher :)

Instead, I would use the MethodInvoker delegate (which has been around since .NET 1.1, and is faster to invoke than Action):

this.Invoke(new MethodInvoker(() => serialDataTextBox.Text = data.Trim());

This post has been edited by CodingSup3rnatur@l-360: 22 August 2011 - 11:59 AM

Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3