I suggest you use a
BackgroundWorker
to get the data from serial port, and update your graph regularly.
Try something like that:
BackgroundWorker worker;
List<float> measures;
public Form1()
{
InitializeComponent();
measures = new List<float>();
worker = new BackgroundWorker();
worker.DoWork += (sender, e) =>
{
...
lock (measures)
{
measures.Add(...);
}
BeginInvoke((Action)(() =>
{
lock (measures)
{
...
}
zedGraphControl1.AxisChange();
zedGraphControl1.Invalidate();
}));
};
}
private void button1_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
-----------------------------------------------------------------
You didn't follow what I said... Let's write it another way, maybe it will be simpler like that:
public partial class Form1 : Form
{
List<double> measures;
LineItem myCurve;
BackgroundWorker worker;
public Form1()
{
InitializeComponent();
measures = new List<double>();
...
myCurve = myPane.AddCurve("Porsche", null, Color.Red, SymbolType.Diamond);
worker = new BackgroundWorker();
worker.SupportsCancellation = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}
private void button1_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
worker.CancelAsync();
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
...
}
private worker_DoWork(object sender, DoWorkEventArgs e)
{
SerialPort sprt = new SerialPort("COM3");
sprt.BaudRate = 9600;
sprt.Parity = Parity.None;
sprt.StopBits = StopBits.One;
sprt.DataBits = 8;
sprt.Handshake = Handshake.None;
try
{
sprt.Open();
}
catch (Exception)
{
MessageBox.Show("Check port");
return;
}
while (!worker.CancellationPending)
{
System.Threading.Thread.Sleep(100);
string indata = sprt.ReadExisting();
string[] splt = indata.Split(':');
string chop = splt[2];
string final = chop.Remove(5);
float d = Convert.ToSingle(final);
lock (measures)
{
measures.Add(d);
}
BeginInvoke((Action)(() => UpdateGraph()));
}
sprt.Close();
}
private void UpdateGraph()
{
lock (measures)
{
for (int i = 0; i < measures.Count; i++)
{
double x = myCurve.Points.Count;
double y = measures[i];
myCurve.AddPoint(x, y);
}
measures.Clear();
}
zedGraphControl1.AxisChange();
zedGraphControl1.Invalidate();
}
}
</double>
I suggest that your read tutorials about using
BackgroundWorker
: there is a lot on internet.
The code I gave you should work at least for updating the graph (for example, try it without the serial port code, give some fake values after
ReadExisting
).
If you still can't get your data, check that you read proper data from the serial port with the debugger.