Reading Serial Port and Plotting with Chart.

You can post your problem related to Microsoft Visual Studio Projects here. We will try our best to help you out.
ramv
Posts:4
Joined:Tue Mar 14, 2017 10:50 am
Reading Serial Port and Plotting with Chart.

Post by ramv » Fri Mar 24, 2017 9:05 am

Hello people :)

So I'm still struggling and any advice is much appreciated.
I'm trying to read a serial port data from a controller and plot it using chart. I could read the data from the controller and see the data in a textbox earlier. Now I'm trying to use a chart along with the textbox. There are complication when I'm trying to use both together. I get an exception because I'm trying "data = sp.ReadLine();" for chart. I'd like to keep the textbox just to verify what I'm plotting, but I understand that I can also do that using putty. There's no response even when I use only the chart to plot. And I cannot pin-point the problem. Because to my understanding I think I have followed the steps to establish it, but then I'm failing anyway! Please do have a look at what I have tried so far and please do let me know if I'm doing something wong.

Chart and Form1

Code: Select all

namespace Serial_receive
{
    public partial class Form1 : Form
    {
        string t;
        SerialPort sp;
        double rt = 0;
        //Boolean i = false;
        private string data;
        private DateTime datetime;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;

            // User can already search for ports when the constructor of the FORM1 is calling 
            // And let the user search ports again with a click
            // Searching for ports function

            SearchPorts();
        }     

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = SerialPort.GetPortNames();
            timer1.Start();
            Text = "Serial Channel to FRDM-KW40Z";
        }
        
        private void TextBox1_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            rt = rt + 0.1;
        }

        private void chart1_Click_1(object sender, EventArgs e)
        {
            ChartArea CA = chart1.ChartAreas[0];  // quick reference
            CA.AxisX.ScaleView.Zoomable = true;   // see small button on the horizontal scroll for reset??
            CA.CursorX.AutoScroll = true;
            CA.CursorX.IsUserSelectionEnabled = true;
            //
            var dataBlocks = data.Split('\n');

            foreach(var block in dataBlocks)
            {
                var numbers = block.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                rt += 100; //some time interval
                for (int i = 0; i<numbers.Length; i++)
                {
                    double n = double.NaN;  //represents a value that is Not a Number. Field is constant
                    bool ok = double.TryParse(numbers[i], out n);
                    if (ok) chart1.Series[i].Points.AddXY(rt, n);
                    else
                    {
                        int p = chart1.Series[i].Points.AddXY(rt, n);
                        chart1.Series[i].Points[p].IsEmpty = true;
                        Console.WriteLine("well shoot! try again..");
                    }

                }

            }

        }
Combox1 for listing available ports and connecting

Code: Select all

private void button1_Click_1(object sender, EventArgs e)
        {
            //comboBox1.Items.Clear();
            SearchPorts();
        }

        void SearchPorts()
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                comboBox1.Items.Add(port);
            }
        }

        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (sp == null || sp.IsOpen == false)
            {
                OpenCloseSerial();
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            // Catch exception if it will be thrown so the user will see it in a message box
            OpenCloseSerial();
        }
        void OpenCloseSerial()
        {
            try
            {
                if (sp == null || sp.IsOpen == false)
                {
                    t = comboBox1.Text.ToString();
                    sErial(t);
                    button2.Text = "Close Serial port"; // button text
                }
                else
                {
                    sp.Close();
                    button2.Text = "Connect and wait for inputs";   // button text
                }
            }
            catch (Exception err)   // catching error message
            {
                MessageBox.Show(err.Message);   // displaying error message
            }
        }

        void sErial(string Port_name)
        {
            try
            {
                sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One);   // serial port parameters
                sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                sp.Open();
            }
            catch (Exception err)
            {
                throw (new SystemException(err.Message));
            }
        }
Textbox and chart data and saving data as text file;

Code: Select all

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            if (e.EventType == SerialData.Chars)
            {
                if (sp.IsOpen)
                {
                    string w = sp.ReadExisting();
                    if (w != String.Empty)
                    {
                        Text += "\r\n";
                        Invoke(new Action(() => TextBox1.AppendText(w)));
                    }
                }
            }
            data = sp.ReadLine();
            chart1.Series["Data1"].Points.AddXY(rt, data);
            Invoke(new EventHandler(displayData_Event));
        }

        private void displayData_Event(object sender, EventArgs e)
        {
            datetime = DateTime.Now;
            string time = datetime.Day + "/" + datetime.Month + "/" + datetime.Year + "\t" + datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
            //data.AppendText(time + "\t" + data + "\n");
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.InitialDirectory = @"C:\Users\varman\Documents\";
            saveFileDialog1.Title = "Save text Files";
            saveFileDialog1.CheckFileExists = true;
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.DefaultExt = "txt";
            saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog1.FileName, TextBox1.Text);
                TextBox1.Text = saveFileDialog1.FileName;
            }
        }
    }
}
Thank you very much for your time. Good day.

Cheers,

Ram.

Post Reply