11 Replies - 1279 Views - Last Post: 23 May 2012 - 12:30 PM Rate Topic: -----

#1 insanepenguin  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 238
  • Joined: 08-July 10

Reading serial port to console

Posted 21 May 2012 - 12:08 AM

Hi guys,

I've followed a brief tutorial Here to read serial port data (I have an Arduino that intercepts a data feed from a home weather station) and whoever wrote it doesn't seem to provide a way to start the program, how would I start the process from the main method? Would it be easier in a Windows form text block or something?

Many thanks
Mike

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

namespace SerialPortReader
{
    class Program
    {
         SerialPort serialP = new SerialPort("COM4", 38400);
        
            
        static void Main(string[] args)
        {
            Console.Read();
           
            
        }
        private Program()
        {
            serialP.DataReceived +=new SerialDataReceivedEventHandler(serialP_DataReceived);
            serialP.Open();
            Console.Read();
        }

        void serialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Console.WriteLine(serialP.ReadExisting());
        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Reading serial port to console

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3666
  • View blog
  • Posts: 11,497
  • Joined: 05-May 12

Re: Reading serial port to console

Posted 21 May 2012 - 01:37 AM

That is just bad programming style... he has the constructor for the class do all the work. And he assumes that the instance constructor will be called when the static Main() in invoked. *sigh*

This will get you going, but be warned that it is demo code. It is not even close to production code. The documentation in MSDN for SerialPort() has a much better structure by having a separate thread running to poll for data.

using System;
using System.IO.Ports;

namespace SerialPortReader
{
    class Program
    {
        static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort) sender;
            Console.WriteLine(serialPort.ReadExisting());
        }

        static void Main(string[] args)
        {
            using(SerialPort serialPort = new SerialPort("COM4", 38400))
            {
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                serialPort.Open();
                Console.Read();
            }
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#3 insanepenguin  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 238
  • Joined: 08-July 10

Re: Reading serial port to console

Posted 21 May 2012 - 04:51 AM

Thanks a lot Skydiver,

Can you clarify something for someone new to events? :D

The using statement in the main method (SerialPort serialPort) is this being sent to the serialPort_DataReceived method? specifically via the 'object sender'? So the serialPort_DataReceived is an event handler for the SerialPort in the Main method? I've included an image with arrows in case I'm making no sense!

Thanks again

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6111
  • View blog
  • Posts: 23,671
  • Joined: 23-August 08

Re: Reading serial port to console

Posted 21 May 2012 - 05:18 AM

Yes, the SerialPort object is the sender, which is why you see

SerialPort serialPort = (SerialPort) sender


inside the event handler. It must be cast to its type because event handlers mus be generic to handle whatever is sending the event.
Was This Post Helpful? 1
  • +
  • -

#5 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1526
  • View blog
  • Posts: 5,961
  • Joined: 21-March 08

Re: Reading serial port to console

Posted 21 May 2012 - 05:22 AM

Here is a quick run-through of the events. In .Net, objects can have events. Specifically, the SerialPort class has the DataReceived event(and more). When the event is fired by the SerialPort class(under the covers), it uses an instance of iteself as the object sender. This is how most events in .Net work. In just about any .Net event, the object sender is the instance of the object that executed the event.

So in the event handler, you can cast the object sender to the type(like Skydiver did). This gives you access to the instance of the SerialPort class that executed the event.
Was This Post Helpful? 1
  • +
  • -

#6 insanepenguin  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 238
  • Joined: 08-July 10

Re: Reading serial port to console

Posted 21 May 2012 - 07:24 AM

It makes more sense to me now - So, the DataReceived event when triggered generates an instance of itself (and any data to output) which can be accessed by the handler via 'object sender' and then displayed (serialPort.ReadExisting())

Thanks guys!
Was This Post Helpful? 0
  • +
  • -

#7 Curtis Rutland  Icon User is offline

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


Reputation: 4577
  • View blog
  • Posts: 8,019
  • Joined: 08-June 10

Re: Reading serial port to console

Posted 21 May 2012 - 07:42 AM

Quote

generates an instance of itself


Not quite. The DataRecieved event is a special type of Delegate, an event. You don't normally think of them like this, but methods can be stored in variables just like data can. Delegates can hold references to methods. Events are a special kind of delegate, to make it easier to use.

So, what actually happens is that when you do this:

serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);


You're storing a reference to the serialPort_DataReceived) method in the DataReceived event. Then, when the SerialPort triggers the event, it reads the method (or methods, Events can store more than one reference) out of its event, and calls it (or each) with the correct parameters. It uses a reference to itself as the first parameter, and creates a SerialDataReceivedEventArgs variable for the second.

Hope that clears things up. There's no creating instances, it's all done by reference.
Was This Post Helpful? 2
  • +
  • -

#8 insanepenguin  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 238
  • Joined: 08-July 10

Re: Reading serial port to console

Posted 21 May 2012 - 08:31 AM

Ah, that helps a lot. I have briefly looked at delegates in the past - they're kinda like pointers to a method so that when the DataReceived event is triggered it sends a reference to itself to the event handler which can then access it and do whatever?

Have I got it now?

I was making good ground in C# until the most boring University semester ever: Professional Issues, Systems Development Tools & Techniques and Network management!

Thanks for your time
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3666
  • View blog
  • Posts: 11,497
  • Joined: 05-May 12

Re: Reading serial port to console

Posted 21 May 2012 - 08:49 AM

Yup, that is a good way to think of delegates.
Was This Post Helpful? 1
  • +
  • -

#10 insanepenguin  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 238
  • Joined: 08-July 10

Re: Reading serial port to console

Posted 23 May 2012 - 09:00 AM

I have one last question on this subject; how do I keep reading the serial port using a windows forms application? In the console version Console.Read(); in the Main method keeps reading the data but I'm not sure what the equivalent is for Win forms, maybe a timer or something?

Many thanks
Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland  Icon User is offline

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


Reputation: 4577
  • View blog
  • Posts: 8,019
  • Joined: 08-June 10

Re: Reading serial port to console

Posted 23 May 2012 - 09:12 AM

I haven't worked w/ Serial Ports, but the event should trigger every time the SerialPort object receives data.
Was This Post Helpful? 0
  • +
  • -

#12 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1526
  • View blog
  • Posts: 5,961
  • Joined: 21-March 08

Re: Reading serial port to console

Posted 23 May 2012 - 12:30 PM

You don't necessarily "keep reading" from the serial port. When the serial port sends data to PC, the event will fire. You just sit around waiting for it to fire. Once the event fires, you need to make sure you get all of the data though.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1