Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to pass data back from a serial port class to the Main Form. I have tried to use example code from other questions on this topic(eg c# - Accessing WinForms Controls from a serial port in a class - Stack Overflow[^] ) . I have tried to follow the example code as closely as possible and made a very simple project to get it working before expanding the project. When I compile I get errors.
The Serial class is a .cs file in the same project as the Main Form .cs file.

Main Form code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SendReceiveData
{
    public partial class Form1 : Form
    {
        SerialClass myComms;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            myComms = new SerialClass();
            myComms.DataReceived += new myComms.DataReceivedDelegate(myCommsDataReceived);    // ERROR 1 at compile          
            // Open COMM3 at 19200 baud
            myComms.OpenSerialPort(3, 19200);               
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            myComms.commsPortWriteMsg("Hello");
        }

        private delegate void DataReceivedDelegate(string data);

        void myCommsDataReceived(string data)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new DataReceivedDelegate(myCommsDataReceived), new Object[] { data });
            }
            else
            {
                textBox1.Text = data;
            }
        }

    }
}

The Serial class

<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace SendReceiveData
{
    class SerialClass
    {
        public delegate void DataReceivedDelegate(string data);
        public event DataReceivedDelegate DataReceived;

        static SerialPort commsPort;

        public SerialClass()
        {
            commsPort = new SerialPort();
            // Attach a method to be called when data waiting in the port's buffer
            commsPort.DataReceived += new SerialDataReceivedEventHandler(commsPortDataReceived);
        }

        public Boolean OpenSerialPort(byte comPort, int baudRate)
        {
            Boolean boolResult;
            try
            {
                // Initialise COM port
                commsPort.PortName = "COM" + comPort.ToString();
                commsPort.Parity = Parity.None;
                commsPort.DataBits = 8;
                commsPort.StopBits = StopBits.One;
                commsPort.ReadTimeout = 500;
                commsPort.WriteTimeout = 500;
                commsPort.BaudRate = baudRate;

                if (!commsPort.IsOpen)
                {
                    commsPort.Open();
                }
                boolResult = true;
            }
            catch (Exception ex)
            {
                boolResult = false;
                SerialPortClose();
            }
            return boolResult;
        }

        private static void commsPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // ... grab the data and place into a string called "data" ...
            string data = "";

            // raise our custom event:
            if (DataReceived != null)    <// ERROR 2 AT COMPILE
            {
                DataReceived(data);      // ERROR 3 AT COMPILE
            }
        }

        public Boolean commsPortWriteMsg(byte[] bOutbuffer)
        {
            Boolean boolResult = false;
            try
            {
                // Write data
                int msgLen = (int)(bOutbuffer[4]) * 256;
                msgLen += (int)bOutbuffer[5];

                commsPort.Write(bOutbuffer, 0, msgLen + 7);
            }
            catch (Exception ex)
            {
                boolResult = false;
            }
        }

        ....
        // Other functions 
    }
}


What I have tried:

When I compile the code I get errors. I have shown the lines where the errors occur as bold and underlined :

Error1 Form1.cs 23 'SendReceiveData.Form1.myComms' is a 'field' but is used like a 'type'

Error3 SerialClass.cs 61 An object reference is required for the non-static field, method, or property 'SendReceiveData.SerialClass.DataReceived'

Error4 SerialClass.cs 63 An object reference is required for the non-static field, method, or property 'SendReceiveData.SerialClass.DataReceived'

Help solving this would be appreciated!
Posted
Comments
RickZeeland 30-Mar-17 14:43pm    
One error I see is in commsPortDataReceived(), you need:
commsPort.DataReceived
RickZeeland 30-Mar-17 14:59pm    
myComms.DataReceived += new myComms.DataReceivedDelegate(myCommsDataReceived);

Can be written as:
myComms.DataReceived += myCommsDataReceived;

Don't forget to remove it when no longer needed like this:
myComms.DataReceived -= myCommsDataReceived;

This is to prevent memory leaks.
Marco Bertschi 30-Mar-17 17:56pm    
Have a look at https://www.codeproject.com/Articles/678025/Serial-Comms-in-Csharp-for-Beginners for further reference.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900