0

I'm trying to plot the data read from a serial port using zedgraph. I'm still learing to code so I couldn't deduce why the plot does not work. Please have a look at the code and advice;

namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        string t;
        SerialPort sp;

Thread m_thread;
bool m_running = false;
ManualResetEvent m_event = new ManualResetEvent(true);
bool m_pause = false;
private GraphPane myPane;

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();

    CreateZedGraph(); //error : Severity    Code    Description Project File    Line    Suppression State
                      //Error CS7036  There is no argument given that corresponds to the required formal parameter 
                      //'w' of 'Form1.DrawPoint(ZedGraphControl, int, PointPair)'
}
// start button
private void btnStart_Click(object sender, EventArgs e)
{
    if (m_thread == null || m_thread.IsAlive == false)
    {
        ClearGraph();
        m_thread = new Thread(Process);
        m_thread.Start();
    }
}
void Process()
{       
    PointPair point = new PointPair();
    btnStart.Enabled = false;
    btnStop.Enabled = true;
    m_running = true;
    while (m_running == true)
    {
        m_event.WaitOne();

        point.Y = Convert.ToDouble(serialPort1);
        point.X++;  //time instance of measurement??
        DrawPoint(zed1, point);
        ssData.Value = point.Y.ToString();
        RefresheZedGraphs(zed1);
        Thread.Sleep(700);
    }
    btnStart.Enabled = true;
}

private void CreateZedGraph(object sender, SerialDataReceivedEventArgs e, ZedGraphControl zgc)
{
    myPane = zgc.GraphPane;
    // axes stuff
    myPane.Title.Text = "FRDM-KW40z serial Test";
    myPane.XAxis.Title.Text = "Time";
    myPane.YAxis.Title.Text = "Voltage";
    myPane.XAxis.MajorGrid.IsVisible = true;
    myPane.YAxis.MajorGrid.IsVisible = true;
    myPane.XAxis.MinorGrid.IsVisible = true;
    myPane.YAxis.MinorGrid.IsVisible = true;

    // data from serial port

    PointPairList list = new PointPairList();
    zed1.GraphPane.AddCurve("Test", list, Color.Red);

}

To open and read from a serial port, I use a combox and a couple of buttons (and then later I try to save it to a text file);

    private void button2_Click(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 button3_Click(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);
                button3.Text = "Close Serial port"; // button text
            }
            else
            {
                sp.Close();
                button3.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));
        }
    }
private  void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
    {

        // This below line is not need , sp is global (belongs to the class!!)
        //SerialPort sp = (SerialPort)sender;
        if (e.EventType == SerialData.Chars)
        {
            if (sp.IsOpen)
            {
                string w = sp.ReadExisting();
                if (w != String.Empty)
                {
                    Invoke(new Action(() => Control.Update(w)));
                }
            }
        }
    }

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

The plot does not update! I can't quite guess why. Please tell me if there's mistakes in my approach or the code. I get an error at : Invoke(new Action(() => Control.Update(w))); when trying to update the graph so that I can save after that.

I again have an error at: DrawPoint(zed1, point); Thank you all for your time. Good day.

Cheers, Ram.

Ram.V
  • 3
  • 7

1 Answers1

0

To update the chart, you need to call the Invalidate method.

When you receive data from serial port, you need to convert it to double[] and add those points to your PointPairList.

PointPairList list = new PointPairList();
zed1.GraphPane.AddCurve("Test", list, Color.Red);

//Convert the received data to double array
double[] serialPortData = ....

//You may want to clear list first, by list.Clear();
list.Add(serialPortData);

//Invalidate the ZedGraphControl to update
zed1.Invalidate();
HebeleHododo
  • 3,620
  • 1
  • 29
  • 38
  • thank you for the reply. I can't understand completely, could you please explain? Or do you have an example that might help me? Good day. – Ram.V Mar 09 '17 at 14:42
  • @Ram.V Which part could you not understand? Were you able to get `serialPortData`? – HebeleHododo Mar 09 '17 at 14:45
  • I couldn't now. Earlier I had a richtextbox instead of the zedgraph and I was able to read data from the com port. But now that I started trying to replace the richtextbox with the zedgraph it is complicated. I'm trying to understand better and get this done, but after a couple of days I'll probably turn to charts. Let me know your advice again. Good day. – Ram.V Mar 10 '17 at 10:51
  • @Ram.V Can't you revert to the previous version with textbox? You are reading a string with `ReadExisting`. You either need to use some other serial port method to read bytes or convert your string to bytes or doubles. I don't think you want to plot a string, right? – HebeleHododo Mar 10 '17 at 11:07
  • @Ram.V I would suggest you to start small without any UI elements and get the data you want to plot. Then it will be easier to build up on it. – HebeleHododo Mar 10 '17 at 11:12
  • yup that's right, i don't want to plot a string :) Good call. I'm going to try reading like you have said and then decorate the gui. thanks a lot :) – Ram.V Mar 12 '17 at 11:46