c# reading data from Serial port - How?

Greetings experts,

I need your help. I usually would prefer to be led in the right direction to find the answer for myself, but in this case, my brain is completely toast from a long, very hard week at work, and I would just LOVE a pre-written solution. If you would be so kind. Then I will learn from the solution how it works. Thanks!

What I need is:

I have a device (a GPS type of device) that constantly pushes communication through a standard serial connection (COM1).

What I need to be able to do is:

Programatically:
1) Open the serial port
2) Listen for a given period of time (say 2 seconds) to the data that is being received via the serial port.
3) populate a multi-line text box with the data that was received from the serial port.
4) close teh serial port

Then I will build additional code surrounding handling the data in the textbox.

Thank you for your help. I truly appreciate it.
MiShepsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jandromedaCommented:
Well here is a place you can look into this. I know that I'm not helping you that much giving you a link but at the moment I cannot try this. Sorry man!

http://www.dreamincode.net/forums/showtopic35775.htm

Hope this will help you. Happy coding man!
0
MiShepsAuthor Commented:
Yes, I've already looked at that page. Thank you for doing a google though.

I've actually looked through about 2 dozen pages. And they made my head hurt, trying to get it to work... which is why I'm hoping to get some complete code that I can just stick in.

Thank you for trying to help though :-)
0
MiShepsAuthor Commented:
plus, I tried the example on that site, and it didn't function....

Here is what I get on it, and in hyperterm.

Basically, what I need, is the kind of info that you get in hyperterm, but need it populated to a multiline textbox.


example-App.bmp
hyperterm.JPG
0
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

mac-willCommented:
That look like hyperterminal is just printing the bytes from the serial stream.

To do that you can do something like this:


SerialPort mComPort = new SerialPort();
 
while (mComPort.BytesToRead != 0)
{
     byte currByte = mComPort.ReadByte();
     myTextBox.Text += Convert.ToChar(currByte).ToString();
}

Open in new window

0
MiShepsAuthor Commented:
Mac,

Thank you for helping.

I just tried your code, but I get nothing.

I also tried removing the "while" and adding the following line:

messagebox.show(mComPort.ReadByte().toString());

to see if ReadByte is getting any data, and I got an error because the ReadByte value is null

Any more ideas?
0
MiShepsAuthor Commented:
I figured out my problem.

First, for whatever reason, I needed to set RtsEnable to "True" (By default it was False)

Once I set that to "true" I was able to use the following to get the data:


    public partial class Troubleshooter_Main : Form
    {
        delegate void SetTextCallback(string text);
 
            #region GPS Test
                private void btnGPS_Click(object sender, EventArgs e)
                {
                    Thread GPS_Thread = new Thread(new ThreadStart(GPS_One));
                    GPS_Thread.Start();
 
                    MyGlobalVariables.ProcessingGPSPart1 = true;
                    timer7.Enabled = true;
                }
 
                    private void GPS_One()
                    {
                        //configuring the serial port
                        serialPort1.Close();
                        serialPort1.PortName = "COM1";
                        serialPort1.BaudRate = 115200;
                        serialPort1.DataBits = 8;
                        serialPort1.Parity = Parity.None;
                        serialPort1.StopBits = StopBits.One;
                        serialPort1.RtsEnable = true;
 
                        serialPort1.Open();
                        {
                            int GPSTicker = 1;
                        RestartTick:
                            if (GPSTicker <= 25)
                            {
                                GPSTicker = GPSTicker + 1;
 
                                string text = serialPort1.ReadLine().ToString();
 
                                if (this.textBox1.InvokeRequired)
                                {
                                    SetTextCallback d = new SetTextCallback(SetGPSText);
                                    this.Invoke(d, new object[] { text }); //+ " (Invoke)" });
                                }
 
                                goto RestartTick;
                            }
                        }
                        MyGlobalVariables.ProcessingGPSPart1 = false;
                    }
                    private void SetGPSText(string text)
                    {
                        this.txtGPSTest.Text += "\n" + text;
                    }
                    private void timer7_Tick(object sender, EventArgs e)
                    {
                        if (MyGlobalVariables.ProcessingGPSPart1 == false)
                        {
                            this.timer2.Enabled = false;
                            this.pnlWMTruckGreen.Visible = false;
 
                            this.btnRunIndividualTests3.Visible = true;
                            this.btnRunIndividualTests3.BringToFront();
                        }
                    }
            #endregion

Open in new window

0
mac-willCommented:
Glad you figured it out.  Usually GPS units have the serial connection described somewhere but I am surprised the unit needs RTS enabled. (What type of unit is it?)

May I suggest not using "goto"?  This is an old VB carry over that in my opinion should not have been included in C#.

Try something like:


serialPort1.Open();
 
if(serialPort1.IsOpen)
{
    for(int GPSTicker = 1; GPSTicker <= 25; GPSTicker++)
    {
        string text = serialPort1.ReadLine().ToString();
 
        if (this.textBox1.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetGPSText);
            this.Invoke(d, new object[] { text }); //+ " (Invoke)" });
        }
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MiShepsAuthor Commented:
Great suggestion, I will replace the GoTo's straight away. My background is programming in VB, so it has been a bit of a learning curve to get into C#, (about 2 weeks into it now)... but so far, I'm loving C#. VB allowed for very soft code, and I love the more strict, cleaner code of C# so far.

I'm going to award you the points, because I appreciate your help, very much actually.

The GPS is a combination device. It is an "Airlink" actually, which has built in GPS, and Cellular connectivity. So, to test that I am getting data from the device, I'm checking for ANY data received over the com port. To test if the data that I'm receiving includes GPS data, I'm checking for the string ",W," within the text box that was populated by the data received over the com port. The only way that the "W" shows up in the communication strings, is if it is getting GPS data (W=West co-ords).

By doing this, I can actually run 3 tests:

1) Is the unit on the right com port? (In my case, should always be on Com 1)
2) Am I receiving Data from the unit? Y/N
3) Is the Data received GPS data? Y/N

They are pretty nice devices (the Airlinks). We are utilizing them in my company for a very large scale mobile computing project that we are working on for our mobil fleet of vehicles. - Lots of fun :-)




0
MiShepsAuthor Commented:
Thanks for all your help!
0
proteam4Commented:
how to send image file to serial port using c#.net ?
how to receive image file from serial port using c#.net ?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.