12 Replies - 1308 Views - Last Post: 28 February 2012 - 08:01 PM Rate Topic: -----

#1 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Error with DataReceive serial communication

Posted 28 February 2012 - 12:20 PM

Hey guys, I have put together a small console application that is supposed to read data from the COM port. I have attached my whole program for you guys to see. I am sure the parameters match that of the device that is transmitting the data via rs232 to my pc. However, when I run my program ans set the appropriate parameters, is ends after opening the port. It never listens or reads the data. I've used the SerialDataReceivedEventHandler, but my program seems to ignore that. I did not include a _serialPort.Close() statement because I want my program to listen continuously.I also wonder why all the examples I have looked at call the handler and than open the port. I thought it should be the other way around. Any suggestions?

Is This A Good Question/Topic? 0
  • +

Replies To: Error with DataReceive serial communication

#2 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 12:37 PM

code for my program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace COMportListener
{
    class Program
    {
        static SerialPort _serialPort;


        static void Main(string[] args)
        {
            //create a new serial port object with default settings
            _serialPort = new SerialPort();

            //Allow user to set port parameters.
            Console.WriteLine("Please set the port parameter");
            _serialPort.PortName = SetPortName(_serialPort.PortName);
            _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
            _serialPort.Parity = SetPortParity(_serialPort.Parity);
            _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
            _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);


            Console.WriteLine("Incoming Data from port:" +_serialPort.PortName);
            _serialPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
            try
            {
                if (_serialPort.IsOpen == true)
                {
                    _serialPort.Close();
                }

                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                    Console.WriteLine("Port opened at " + DateTime.Now + "\n");
                    
                }
                    
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }




        }

        public static string SetPortName(string defaultPortName)
        {
            string portName;

            Console.WriteLine("Available Ports:");
            foreach (string s in SerialPort.GetPortNames())
            {
                Console.WriteLine("   {0}", s);
            }
            Console.WriteLine("COM port ({0}):", defaultPortName);
            portName = Console.ReadLine();

            if (portName == "")
            {
                portName = defaultPortName;
            }
            return portName;
        }

        public static int SetPortBaudRate(int defaultPortBaudRate)
        {
            string baudRate;

            Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
            baudRate = Console.ReadLine();

            if (baudRate == "")
            {
                baudRate = defaultPortBaudRate.ToString();
            }

            return int.Parse(baudRate);
        }

        public static Parity SetPortParity(Parity defaultPortParity)
        {
            string parity;

            Console.WriteLine("Available Parity options:");
            foreach (string s in Enum.GetNames(typeof(Parity)))
            {
                Console.WriteLine("   {0}", s);
            }

            Console.Write("Parity({0}):", defaultPortParity.ToString());
            parity = Console.ReadLine();

            if (parity == "")
            {
                parity = defaultPortParity.ToString();
            }

            return (Parity)Enum.Parse(typeof(Parity), parity);
        }

        public static int SetPortDataBits(int defaultPortDataBits)
        {
            string dataBits;

            Console.Write("Data Bits({0}): ", defaultPortDataBits);
            dataBits = Console.ReadLine();

            if (dataBits == "")
            {
                dataBits = defaultPortDataBits.ToString();
            }

            return int.Parse(dataBits);
        }

        public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
        {
            string stopBits;

            Console.WriteLine("Available Stop Bits options:");
            foreach (string s in Enum.GetNames(typeof(StopBits)))
            {
                Console.WriteLine("   {0}", s);
            }

            Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
            stopBits = Console.ReadLine();

            if (stopBits == "")
            {
                stopBits = defaultPortStopBits.ToString();
            }

            return (StopBits)Enum.Parse(typeof(StopBits), stopBits);

        }

        private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //retrieve number of bytes in the buffer
            int bytes = _serialPort.BytesToRead;
            //create a byte array to hold the awaiting data
            byte[] dataBuffer = new byte[bytes];
            //Read the data and store it
            _serialPort.Read(dataBuffer, 0, bytes);
            //display the data 
            string s = System.Text.ASCIIEncoding.ASCII.GetString(dataBuffer);
            Console.WriteLine("Data" +s+" was received at " + DateTime.Now);
            Console.WriteLine(_serialPort.ReadExisting());
            Console.WriteLine("Data Received");
            
        }


    }
}


Was This Post Helpful? 0
  • +
  • -

#3 Curtis Rutland  Icon User is online

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


Reputation: 4436
  • View blog
  • Posts: 7,707
  • Joined: 08-June 10

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 12:43 PM

Please post your code directly, and use [code] tags when doing so.

I've fixed your post.
Was This Post Helpful? 0
  • +
  • -

#4 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 01:15 PM

View PostCurtis Rutland, on 28 February 2012 - 12:43 PM, said:

Please post your code directly, and use [code] tags when doing so.

I've fixed your post.

Thank you.
Was This Post Helpful? 0
  • +
  • -

#5 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

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

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 02:07 PM

So if you put a breakpoint on this line...

int bytes = _serialPort.BytesToRead;



it doesn't get hit?

If not, then no data is coming into the serial port.

Why exactly did you make the event handler static?

private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)


Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is online

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

Reputation: 5436
  • View blog
  • Posts: 11,661
  • Joined: 02-June 10

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 02:09 PM

Serial port tutorial: FAQ 11 below for serial port tutorials (open the Spoiler tag}

Rick372010 What this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2


FAQ (Frequently Asked Questions - Updated Feb 2012
Spoiler



Was This Post Helpful? 0
  • +
  • -

#7 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 02:44 PM

View Posteclipsed4utoo, on 28 February 2012 - 02:07 PM, said:

So if you put a breakpoint on this line...

int bytes = _serialPort.BytesToRead;



it doesn't get hit?

If not, then no data is coming into the serial port.

Why exactly did you make the event handler static?

private static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)


I did set a breakpoint there and that code is never executed. I made the handler static simply because it was the only way to get the call to the handle to work.
Was This Post Helpful? 0
  • +
  • -

#8 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

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

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 02:55 PM

Oh yeah, I forgot you stated you were doing this in a console app.

And now remembering that, does your application start then stop almost immediately? You have no code that stops the console of completing once the code in the Main method is done.
Was This Post Helpful? 0
  • +
  • -

#9 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 02:59 PM

View PosttlhIn`toq, on 28 February 2012 - 02:09 PM, said:

Serial port tutorial: FAQ 11 below for serial port tutorials (open the Spoiler tag}

Rick372010 What this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2


FAQ (Frequently Asked Questions - Updated Feb 2012
Spoiler



Yes, I agree with you, they don't teach enough debugging in college. However, I did set a few breakpoints and step through my code. The event handler is never accessed. I appreciate the tutorial you have recommended. I actually wrote my program based on the serial communication tutorial (FAQ11).
Was This Post Helpful? 1
  • +
  • -

#10 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 03:54 PM

View Posteclipsed4utoo, on 28 February 2012 - 02:55 PM, said:

Oh yeah, I forgot you stated you were doing this in a console app.

And now remembering that, does your application start then stop almost immediately? You have no code that stops the console of completing once the code in the Main method is done.

Yeah you're right about that. I actually pasted that code when I had moved the _serialPort.Close() statement. I've added it at the end of my main function

if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                    _serialPort.DtrEnable = true;
                    _serialPort.RtsEnable = true;

                    Console.WriteLine("Port opened at " + DateTime.Now + "\n");                 
                    
                   _serialPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
                   Console.WriteLine("Incoming Data from port:" + _serialPort.PortName);
                   Console.WriteLine(_serialPort.ReadExisting());
                        
                    

                    _serialPort.Close();
                    
                }

Even with this statement the program just says the port it opened and time stamp. Is the SerialDataReceiveEventHandler doing the actual listening? I havent been able to find a function such as "TcpListener" where I know im listening for incoming traffic. I believe this is where my program fails.

This post has been edited by tlhIn`toq: 28 February 2012 - 04:04 PM
Reason for edit:: [code] your code here [/code] its not THAT tough

Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq  Icon User is online

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

Reputation: 5436
  • View blog
  • Posts: 11,661
  • Joined: 02-June 10

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 04:09 PM

You do realize that that last thing you do in this method is to CLOSE the port, right?
How do you expect to receive data if you close the port?

Also, you have subscribed to the DataREceived event. THAT handler method should display the data when it comes in. You don't need/want the two lines after that here in this method.

if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                    _serialPort.DtrEnable = true;
                    _serialPort.RtsEnable = true;

                    Console.WriteLine("Port opened at " + DateTime.Now + "\n");                 
                    
                   _serialPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);// Do your displaying in the Port_DataReveived() method, not below this line
                   //Console.WriteLine("Incoming Data from port:" + _serialPort.PortName);
                   //Console.WriteLine(_serialPort.ReadExisting());
                        
                    

                    //_serialPort.Close(); // Don't close the port here - duh
                    
                }

Was This Post Helpful? 0
  • +
  • -

#12 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

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

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 07:44 PM

I think both of you are missing the point I am getting at. Once the code in the Main method is executed, the console application ends. It doesn't wait for data to come in. It just quits. You need some type of code at the end to keep the console application from closing while it waits for data from the serial port.

In reality, a console app is not a good way to test getting data from the serial port for the reason stated above. A WinForms/WPF application is better suited as it's designed to sit idle. Console applications are not designed to just sit and do nothing.
Was This Post Helpful? 0
  • +
  • -

#13 Rick372010  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 28-February 12

Re: Error with DataReceive serial communication

Posted 28 February 2012 - 08:01 PM

View Posteclipsed4utoo, on 28 February 2012 - 07:44 PM, said:

I think both of you are missing the point I am getting at. Once the code in the Main method is executed, the console application ends. It doesn't wait for data to come in. It just quits. You need some type of code at the end to keep the console application from closing while it waits for data from the serial port.

In reality, a console app is not a good way to test getting data from the serial port for the reason stated above. A WinForms/WPF application is better suited as it's designed to sit idle. Console applications are not designed to just sit and do nothing.

Thanks for your suggestion eclipsed4utoo. I write a windows app version of this. As you mentioned, its's designed to sit idle and it is exactly what I need.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1