using same serial port on three different forms in c#

Topics: Help
Sep 27, 2012 at 9:46 AM
Edited Sep 27, 2012 at 9:50 AM

I am quite new to C# and I am trying to use one common serial port for 3 different forms:

 -Form2.cs

-Form3.cs

-Form4.cs

 Form1.cs isn't needed for this because it's just needed to launch the programs of the other forms. Basically, all 3 forms must receive data from the same serial port at the same time. The problem I am facing is that only one form can receive data from the serial port, but the other two forms can't.

 I found a question similar to this:

http://stackoverflow.com/questions/9358216/using-same-serial-port-data-received-event-on-two-different-forms?answertab=active#tab-top

 Is that problem similar to mine? If yes, can I know where should I place the sample code in the aforementioned link in my code?

 Can someone please help with this? Thanks in advance!

 Codes:

-Form1.cs

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 UAV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.Show();
            Form3 f3 = new Form3();
            f3.Show();
            Form4 f4 = new Form4();
            f4.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}


-Form2.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Globalization;
using GMap.NET;             //Required
using GMap.NET.WindowsForms; //Required
using GMap.NET.WindowsForms.Markers;
using GMap.NET.MapProviders;//Required
using System.Threading;
using System.Windows.Forms;

namespace UAV
{
    public partial class Form2 : Form
    {
        GMapControl MainMap = new GMapControl();
        //Initialise data type for latituide and longitude
        double lat, lng;
        //Initialise customise marker (plane maker). Declared as m.
        GMapMarkerImage m = new GMapMarkerImage(new PointLatLng());
        GMapOverlay overlayOne;

        public Form2()
        {
            InitializeComponent();

            SuspendLayout();

            overlayOne = new GMapOverlay(MainMap, "OverlayOne");
            MainMap.MapProvider = GMapProviders.YahooMap;

            MainMap.SetCurrentPositionByKeywords("Singapore");
            MainMap.MinZoom = 1;
            MainMap.MaxZoom = 24;
            MainMap.Zoom = 13;
            MainMap.CanDragMap = true;
            MainMap.DragButton = MouseButtons.Left;
            MainMap.Dock = DockStyle.Fill;
            MainMap.Manager.Mode = AccessMode.ServerAndCache;

            Controls.Add(MainMap);
            ResumeLayout(true);


        }

        public void button1_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)    //if serial port is not open
                try
                {
                    serialPort1.Open(); //Open Serial Port
                    if (lat != 0 && lng != 0)  //Display marker only when GPS has receive data
                    {
                        overlayOne.Markers.Add(m);          //Add marker on the position given to the overlayOne layer
                        MainMap.Overlays.Add(overlayOne);   //Add overlayOne layer to the MainMap layer
                    }
                }
                catch
                {
                    //A message box will display this message, informing user either a wrong port has been chosen, or have not been plugged in.
                    MessageBox.Show("There was an error. Please make sure that the correct port was selected, and the device, plugged in.");
                }

        }

        public void button2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)                // if Serial Port is open
            {
                serialPort1.Close();               //Close Serial
                overlayOne.Markers.Remove(m);
            }
        }

        //When microsoft visual studio receive data
        public void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            this.Invoke(new EventHandler(DoUpdate));    //for function DoUpdate

            //Pause Microsoft Visual Studio for 100 milliseconds from receiving data, 
            //to ensure serialPort can be close successfully
            Thread.Sleep(100);
        }

        //Function for updating data. Declared as DoUpdate.
        public void DoUpdate(object sender, EventArgs e)
        {
            string[] c = serialPort1.ReadLine().Split(',');  //Stored data seperately by using array & using the Split() function

            lat = Convert.ToDouble(c[9]);               //Convert Latitude string data to double data
            lng = Convert.ToDouble(c[10]);              //Convert Longitude string data to double data

            //Input lat and lng data in m.
            //Updating the position of the marker
            m.Position = new PointLatLng(lat, lng);
          
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }
    }
}


-Form3.cs

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

namespace UAV
{

    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();

        }
 
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)    //if serial port is not open
                try
                {
                    serialPort1.Open(); //Open Serial Port

                    //Enable blocks to have colour
                    rectangleShape1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape3.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape4.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape5.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape6.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape7.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape8.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                    rectangleShape9.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
                }
                catch
                {
                    //A message box will display this message, informing user either a wrong port has been chosen, or have not been plugged in.
                    MessageBox.Show("There was an error. Please make sure that the correct port was selected, and the device, plugged in.");
                }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)                // if serial port is open
            {
                serialPort1.Close();                   // Close serial Port 

                //Clear data in textboxes
                FrontSonar.Text = "    ";
                LeftSonar.Text = "   ";
                RightSonar.Text = "    ";

                //Clear colours in the boxes
                rectangleShape1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape3.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape4.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape5.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape6.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape7.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape8.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
                rectangleShape9.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) //When microsoft visual studio receive data
        {
            this.Invoke(new EventHandler(DoUpdate1)); //To update and ensure sonar data infront of UAV can be displayed without error
            this.Invoke(new EventHandler(DoUpdate2)); //To update and ensure sonar data left side of UAV can be displayed without error
            this.Invoke(new EventHandler(DoUpdate3)); //To update and ensure sonar data on the right side of UAV can be displayed without error

            Thread.Sleep(100);
        }

        private void DoUpdate1(object s, EventArgs e) //Display for Sonar infront of UAV
        {
            string[] c = serialPort1.ReadLine().Split(',');  //Stored data seperately by using array & using the Split() function
            FrontSonar.Text = c[1] + "\n";
            double d = Convert.ToDouble(c[1]);

            if (d > 500)
            {
                //Fill blocks with green
                this.rectangleShape1.FillColor = System.Drawing.Color.Green;
                this.rectangleShape2.FillColor = System.Drawing.Color.Green;
                this.rectangleShape3.FillColor = System.Drawing.Color.Green;
            }
            else
                if (d > 400 && d <= 500)
                {
                    //Fill block with Orange colour
                    this.rectangleShape1.FillColor = System.Drawing.Color.Orange;
                    this.rectangleShape2.FillColor = System.Drawing.Color.Orange;

                    //Fill block with Lavender colour
                    this.rectangleShape3.FillColor = System.Drawing.Color.Lavender;
                }
                else
                    if (d <= 400)
                    {
                        //Fill block with red colour
                        this.rectangleShape1.FillColor = System.Drawing.Color.Red;

                        //Fill block with Lavender colour
                        this.rectangleShape2.FillColor = System.Drawing.Color.Lavender;
                        this.rectangleShape3.FillColor = System.Drawing.Color.Lavender;
                    }

        }


        private void DoUpdate2(object s, EventArgs e) //Display for Sonar on the left side of UAV
        {
            string[] c = serialPort1.ReadLine().Split(',');  //Stored data seperately by using array & using the Split() function
            LeftSonar.Text = c[2] + "\n";
            double d = Convert.ToDouble(c[2]);

            if (d > 500)
            {
                //Fill blocks with green
                this.rectangleShape9.FillColor = System.Drawing.Color.Green;
                this.rectangleShape8.FillColor = System.Drawing.Color.Green;
                this.rectangleShape7.FillColor = System.Drawing.Color.Green;
            }
            else
                if (d > 400 && d <= 500)
                {
                    //Fill blocks with orange
                    this.rectangleShape9.FillColor = System.Drawing.Color.Orange;
                    this.rectangleShape8.FillColor = System.Drawing.Color.Orange;

                    //Fill block with Lavender colour
                    this.rectangleShape7.FillColor = System.Drawing.Color.Lavender;
                }
                else
                    if (d <= 400)
                    {
                        //Fill block with red colour
                        this.rectangleShape9.FillColor = System.Drawing.Color.Red;

                        //Fill block with Lavender colour
                        this.rectangleShape8.FillColor = System.Drawing.Color.Lavender;
                        this.rectangleShape7.FillColor = System.Drawing.Color.Lavender;
                    }

        }

        private void DoUpdate3(object s, EventArgs e) //Display for Sonar on the right side of UAV
        {
            string[] c = serialPort1.ReadLine().Split(',');  //Stored data seperately by using array & using the Split() function
            RightSonar.Text = c[3] + "\n";
            double d = Convert.ToDouble(c[3]);

            if (d > 500)
            {
                //Fill blocks with green
                this.rectangleShape4.FillColor = System.Drawing.Color.Green;
                this.rectangleShape5.FillColor = System.Drawing.Color.Green;
                this.rectangleShape6.FillColor = System.Drawing.Color.Green;
            }
            else
                if (d > 400 && d <= 500)
                {
                    //Fill blocks with orange
                    this.rectangleShape4.FillColor = System.Drawing.Color.Orange;
                    this.rectangleShape5.FillColor = System.Drawing.Color.Orange;

                    //Fill block with Lavender colour
                    this.rectangleShape6.FillColor = System.Drawing.Color.Lavender;
                }
                else
                    if (d <= 400)
                    {
                        //Fill block with red colour
                        this.rectangleShape4.FillColor = System.Drawing.Color.Red;

                        //Fill block with Lavender colour
                        this.rectangleShape5.FillColor = System.Drawing.Color.Lavender;
                        this.rectangleShape6.FillColor = System.Drawing.Color.Lavender;
                    }
        }

        private void Form3_Load(object sender, EventArgs e)
        {

        }
    }
}

 


-Form4.cs (Still in progress)

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 UAV
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }
    }
}

 

 

 

 

 

Oct 1, 2012 at 1:13 PM

..it's not really project related, but try experiment on simpler code..