图形动态更新

本文关键字:更新 动态 图形 | 更新日期: 2023-09-27 18:10:21

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

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

我认为我需要通过用变量替换值来更新"点"answers"值"(0,20),但如果我这样做,我在图中只有一个点,我不能显示以前的值。

图形动态更新

另一种方法(每秒刷新)是使用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);
  }

获取新数据后,只需添加另一个数据点:只是给你一个想法(因为你还没有发布你的数据接收方法):

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

是的,一旦您将真实数据放入您的图表中,您就会想要删除您的假数据。假数据容易混淆。