0

我有一个应用程序,每次温度变化时都会从串口获取温度数据。该值存储在变量中并显示在文本框中。我想在图表中显示温度与时间的关系。我已将图表设置如下,但我不知道从哪里开始更新温度线与每秒的时间。

 InitializeComponent();
        //Chart
        chart1.ChartAreas.Add("areas");
        chart1.ChartAreas["areas"].AxisX.Minimum = 0;
        chart1.ChartAreas["areas"].AxisX.Interval = 1;
        chart1.ChartAreas["areas"].AxisY.Minimum = 0;
        chart1.ChartAreas["areas"].AxisY.Maximum = 250;
        chart1.ChartAreas["areas"].AxisY.Interval = 10;
        chart1.ChartAreas["areas"].AxisX.Title = "Time [s]";
        chart1.ChartAreas["areas"].AxisY.Title = "Temperature [°C]";
        chart1.Series.Add("Temperature");
        chart1.Series["Temperature"].Color = Color.Red;
        chart1.Series["Temperature"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
        chart1.Titles.Add("Extruder Temperature");

       //this two lines are only to see something in the graph
        chart1.Series["Temperature"].Points.AddXY(0, 20);
        chart1.Series["Temperature"].Points.AddXY(1, 50);
    }

我认为我需要通过用变量替换值来更新“点”和“值”(0、20),但如果这样做,我在图中只有一个点,我无法显示以前的值。作为初学者,我将不胜感激。

4

2 回答 2

2

另一种方法(每秒刷新)是使用 BackgroundWorker。这个问题举个例子。本质上,您启动了一个后台线程,该线程每隔设定的时间更新视图。

private BackgroundWorker _bw;

....
    InitializeComponent();
    _bw = new BackgroundWorker
    {
      WorkerReportsProgress = true,
      WorkerSupportsCancellation = true
    };
    _bw.DoWork += bw_DoWork;
    _bw.ProgressChanged += bw_ProgressChanged;
    _bw.RunWorkerCompleted += bw_RunWorkerCompleted;

    _bw.RunWorkerAsync ("Hello to worker");
     if (_bw.IsBusy) _bw.CancelAsync();
  }

  private void bw_DoWork (object sender, DoWorkEventArgs e)
  {

      if (_bw.CancellationPending) { e.Cancel = true; return; }
      var dataPoints = YourConnectToSerialPortAndGetDataFunction();
      _bw.ReportProgress (dataPoints);
      Thread.Sleep (1000); 

    e.Result = dataPoints;    // This gets passed to RunWorkerCompleted
  }

  private void bw_RunWorkerCompleted (object sender,
                                     RunWorkerCompletedEventArgs e)
  {

}

  private void bw_ProgressChanged (object sender,
                                  ProgressChangedEventArgs e)
  {
//UPDATE YOUR LABEL
chart1.Series["Temperature"].Points.AddXY(0, 20);
        chart1.Series["Temperature"].Points.AddXY(1, 50);
  }
于 2013-04-22T07:56:26.337 回答
1

获取新数据后,只需添加另一个数据点:只是给您一个想法(因为您尚未发布数据接收方法):

OnSerialReceive()
{
    var temp = serialport.read();
    var time = (int)stopwatch.Elapsed.TotalSeconds;
    chart1.Series["Temperature"].Points.AddXY(time, temp);
}

是的,一旦您将真实数据放入图表中,您就会想要删除虚假数据。虚假数据令人困惑。

于 2013-04-22T07:52:57.167 回答