?
Solved

c# reading data from Serial port - How?

Posted on 2008-11-06
10
Medium Priority
?
5,949 Views
Last Modified: 2013-12-17
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.
0
Comment
Question by:MiSheps
10 Comments
 
LVL 12

Expert Comment

by:jandromeda
ID: 22898775
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
 

Author Comment

by:MiSheps
ID: 22899547
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
 

Author Comment

by:MiSheps
ID: 22899873
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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 8

Expert Comment

by:mac-will
ID: 22906109
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
 

Author Comment

by:MiSheps
ID: 22913153
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
 

Author Comment

by:MiSheps
ID: 22913672
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
 
LVL 8

Accepted Solution

by:
mac-will earned 1000 total points
ID: 22914610
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
 

Author Comment

by:MiSheps
ID: 22915580
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
 

Author Closing Comment

by:MiSheps
ID: 31514045
Thanks for all your help!
0
 

Expert Comment

by:proteam4
ID: 24438968
how to send image file to serial port using c#.net ?
how to receive image file from serial port using c#.net ?
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question