问题描述
您好,我已经创建了一个串行端口,以便在获取值时从温度传感器获取值,应根据温度绘制图表.
当我单击button1时,我的表单中有两个按钮,它应该获取数据并绘制图形.当我单击按钮时,它应该停止获取数据.我希望为图形创建一个单独的函数,但是在将通过串口读取的温度值发送给图形函数时遇到困难.
Hello i have created a serial port to get value from a temperature sensor when i get the value , graph should be plotted depending upon the temp .
I have two buttons in my forms when i click button1 it should get data and plot graph . When i click button it should stop getting data . I wish to create a seperate function for graph but find difficulty in sending the temp value which i read through serial port to graph function .
namespace Graphtry1
{
public partial class Form1 : Form
{
SerialPort sprt;
string indata;
GraphPane myPane;
double d;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
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");
}
Thread.Sleep(500);
indata = sprt.ReadExisting();
MessageBox.Show(indata);
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { indata });
zedGraphControl1.Location = new Point(10, 10);
// Leave a small margin around the outside of the control
zedGraphControl1.Size = new Size(ClientRectangle.Width - 20,
ClientRectangle.Height - 20);
ZedGraphControl zgc = zedGraphControl1;
myPane = zgc.GraphPane;
myPane.Title.Text = "My Test Graph\n(For CodeProject Sample)";
myPane.XAxis.Title.Text = "My X Axis";
myPane.YAxis.Title.Text = "My Y Axis";
double x, y1, y2;
PointPairList list1 = new PointPairList();
PointPairList list2 = new PointPairList();
for (int i = 0; i < 36; i++)
{
x = 3.5;
y1 = d;
//MessageBox.Show(d);
//y2 = 3.0 * (1.5 + Math.Sin((double)i * 0.2));
list1.Add(x, y1);
//list2.Add(x, y2);
}
// Generate a red curve with diamond
// symbols, and "Porsche" in the legend
LineItem myCurve = myPane.AddCurve("Porsche",
list1, Color.Red, SymbolType.Diamond);
// Generate a blue curve with circle
// symbols, and "Piper" in the legend
//LineItem myCurve2 = myPane.AddCurve("Piper",
// list2, Color.Blue, SymbolType.Circle);
zgc.AxisChange();
//sprt.DataReceived += new SerialDataReceivedEventHandler(sprt_DataReceived);
}
private delegate void SetTextDeleg(string text);
//private void sprt_DataReceived(
// object sender,
// SerialDataReceivedEventArgs e)
//{
//Thread.Sleep(500);
//try
//{
// indata = sprt.ReadExisting();
//}
//catch (Exception)
//{
// MessageBox.Show("Port Not closed . Try again");
//}
//this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { indata });
//}
private void si_DataReceived(string indata)
{
String[] datashort=indata.Split('':'');
string chop=datashort[2];
string finaldata=chop.Remove(5);
d = Convert.ToDouble(finaldata);
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
sprt.Close();
}
}
}
我想将最终数据发送到其中的图形函数查找问题.需要帮助
I want to send the final data to graph function finding problem in that . Help needed
推荐答案
BackgroundWorker worker;
List<float> measures;
public Form1()
{
InitializeComponent();
measures = new List<float>();
worker = new BackgroundWorker();
worker.DoWork += (sender, e) =>
{
//put all your serial port code here
...
//when you want to update the measures list
lock (measures)
{
measures.Add(...);
}
//sometimes update the graph
BeginInvoke((Action)(() =>
{
lock (measures)
{
//fill your PointPairList from the measures
...
}
zedGraphControl1.AxisChange();
zedGraphControl1.Invalidate();
}));
};
}
private void button1_Click(object sender, EventArgs e)
{
//starts the worker
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 of double: do not forget the <double>!!
/// This is a the list of the new measures since the last update
List<double> measures;
/// The ZedGraph curve
LineItem myCurve;
BackgroundWorker worker;
public Form1()
{
InitializeComponent();
//create an empty list
measures = new List<double>();
//init your zegGraphControl here
...
//create an empty curve: it will be filled later
myCurve = myPane.AddCurve("Porsche", null, Color.Red, SymbolType.Diamond);
//create the worker
worker = new BackgroundWorker();
// set this to true so that you can cancel the worker
worker.SupportsCancellation = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}
private void button1_Click(object sender, EventArgs e)
{
//start the worker
worker.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
//stop the worker
worker.CancelAsync();
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//the worker has completed
//do whatever you want here
...
}
private worker_DoWork(object sender, DoWorkEventArgs e)
{
//put all your serial port code here
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;
}
//worker.CancellationPending will change to true when CancelAsync is called
//(so when the user clicks button2).
//while the worker should still continue, read incoming data
while (!worker.CancellationPending)
{
//wait for data to come...
System.Threading.Thread.Sleep(100);
string indata = sprt.ReadExisting();
//extract the values from the read data
//be careful here: make sure the read data is complete...
string[] splt = indata.Split(':');
string chop = splt[2];
string final = chop.Remove(5);
float d = Convert.ToSingle(final);
//update the measures
//measures is shared by several threads: you must lock it to access it safely
lock (measures)
{
measures.Add(d);
}
//update the graph
BeginInvoke((Action)(() => UpdateGraph()));
}
//user wants to stop the worker
sprt.Close();
}
/// This function is called when the graph should be updated
private void UpdateGraph()
{
//messures is shared by several threads: you must lock it to access it safely
lock (measures)
{
//add each measure into the curve
for (int i = 0; i < measures.Count; i++)
{
//fill each with what ever you want
double x = myCurve.Points.Count;
double y = measures[i];
//add a new point to the curve
myCurve.AddPoint(x, y);
}
//all measures have been added
//we can empty the list
measures.Clear();
}
//the curve has been updated so refresh the graph
zedGraphControl1.AxisChange();
zedGraphControl1.Invalidate();
}
}
</double>
我建议您阅读有关使用BackgroundWorker
的教程:Internet上有很多.
我给您的代码至少应该用于更新图形(例如,尝试不使用串行端口代码,在ReadExisting
之后提供一些假值).
如果仍然无法获取数据,请检查是否已使用调试器从串行端口读取了正确的数据.
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.
这篇关于使用串行端口数据绘制zedgraph的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!