c#在windows窗体应用程序中的实时绘图
本文关键字:实时 绘图 应用程序 windows 窗体 | 更新日期: 2023-09-27 18:15:53
我正在尝试使用Modbus命令读取实时温度。目前,我能够读取温度并绘制图表。然而,一旦它绘制了第一个点,它就不会持续更新图形和GUI。
我应该在Form1_Load
以外的方法中运行这个吗?
private void Form1_Load(object sender, EventArgs e)
{
chart1.ChartAreas.Add("Area");
chart1.ChartAreas["Area"].AxisX.Minimum = -100;
chart1.ChartAreas["Area"].AxisX.Maximum = 100;
chart1.ChartAreas["Area"].AxisX.Interval = 1;
chart1.ChartAreas["Area"].AxisY.Minimum = -100;
chart1.ChartAreas["Area"].AxisY.Maximum = 100;
chart1.ChartAreas["Area"].AxisY.Interval = 1;
//create a Data object array
val[] data = new val[5];
string[] ports = SerialPort.GetPortNames();
this.comboBox1.DataSource = ports;
serialPort1.PortName = "COM5";
using (SerialPort port = new SerialPort("COM5"))
{
//start time object
DateTime start = DateTime.Now;
int startSec = start.Second;
port.Open();
byte slaveID = 1;
ushort startAddress = 360;
ushort numOfPoints = 2;
ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
for (int j = 0; j < 5; j++)
{
ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress,
numOfPoints);
ushort val1 = holding_register[0];
ushort val2 = holding_register[1];
uint t1 = (uint)(holding_register[0]);
uint t2 = (uint)(holding_register[1] << 16);
uint temp = (uint)(t1) | (t2);
byte[] floatVals = BitConverter.GetBytes(temp);
float f = BitConverter.ToSingle(floatVals, 0);
c = 5.0 / 9.0 * (f - 32);
textBox1.Text = c.ToString();
DateTime current = DateTime.Now;
int currentSec = current.Second;
int time = currentSec - startSec;
chart1.Refresh();
data[j].time = time;
data[j].temperature = c;
chart1.Series[j].Points.Add(new DataPoint(data[j].time, data[j].temperature));
chart1.Refresh();
port.Close();
}
}
}
将串行端口设置为成员变量,然后在表单中添加计时器。然后,您可以解析串行数据并将数据点附加到计时器回调中的图形中。