fiftyplus
fiftyplus

Reputation: 561

Adding event handler in main() for SerialPort

I try to subscribe a event handler to the data received event. Seems like I cant specify the event handler function name. I dont understand why

myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); 

is giving me error message.

Here is the problem, hope anyone can answer it.

namespace serialport
{
    public class Program
    {

        internal List<Byte> portBuffer = new List<Byte>(1024);

        static void Main()
        {


            //1. find available COM port
            string[] nameArray = null;
            string myComPortName = null;
            nameArray = SerialPort.GetPortNames();
            if (nameArray.GetUpperBound(0) >= 0)
            {
                myComPortName = nameArray[0];
            }
            else
            {
                Console.WriteLine("Error");
                return;
            }


            //2. create a serialport object
            // the port object is closed automatically by use using()
            SerialPort myComPort = new SerialPort();
            myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
            myComPort.PortName = myComPortName;
            //the default paramit are 9600,no parity,one stop bit, and no flow control



            //3.open the port
            try
            {
                myComPort.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show(ex.Message);
            }
            //Add timeout, p161

            //reading Bytes
            byte[] byteBuffer = new byte[10];
            Int32 count;
            Int32 numberOfReceivedBytes;
            myComPort.Read(byteBuffer, 0, 9);
            for (count = 0; count <= 3; count++)
            {
                Console.WriteLine(byteBuffer[count].ToString());
            }


        }
        //The event handler should be static??
        void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int numberOfBytesToRead;
            numberOfBytesToRead = myComPort.BytesToRead;
            byte[] newReceivedData = new byte[numberOfBytesToRead];
            myComPort.Read(newReceivedData, 0, numberOfBytesToRead);
            portBuffer.AddRange(newReceivedData);
            ProcessData();
        }
        private void ProcessData()
        {
            //when 8 bytes have arrived, display then and remove them from the buffer
            int count;
            int numberOfBytesToRead = 8;

            if (portBuffer.Count >= numberOfBytesToRead)
            {
                for (count = 0; count < numberOfBytesToRead; count++)
                {
                    Console.WriteLine((char)(portBuffer[count]));
                }
                portBuffer.RemoveRange(0, numberOfBytesToRead);
            }
        }

    }

    }

Upvotes: 5

Views: 1750

Answers (3)

Brian Driscoll
Brian Driscoll

Reputation: 19635

Tetsujin no Oni's answer is the ideal way to handle your issue with scope. Another approach that also works is to declare myComPort as a static member of your Program, e.g.:

internal List<Byte> portBuffer = new List<Byte>(1024);
private SerialPort myComPort = new SerialPort();

Then simply remove the myComPort declaration from your main method.

Upvotes: 0

madd0
madd0

Reputation: 9303

First, since method Main is static, you can only call other static methods in the same class. As it is, comPort_DataReceived is declared as an instance method, the following code should fix the assignment of the event handler:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   // ...
}

Second, since myComPort is defined in Main, it will not be visible in comPort_DataReceived. You have two choices: either declare myComPort as a static member of your class, or use the sender argument of the event handler:

static void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    // ...
}

Upvotes: 6

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7367

In your event handler, myComPort isn't in scope - it's declared locally in your main() method. I would suggest that you extract the com port handling into a class and make myComPort a member variable of that class.

Also, your comments note that the SerialPort class has a managed resource that it needs to dispose of using the IDisposable / Using pattern, but you don't have a using block wrapping the access to the comm port.

Last, the method you are adding as the event handler exists as an instance member rather than as a static member; to access it from the main() method's static scope, you need to either grab it from an instance of the class or make the method static.

Upvotes: 4

Related Questions