C#在Windows窗体应用程序中实时绘图
我试图绘制使用Modbus命令读取的实时温度。目前,我可以读取温度并绘制图表。但是,一旦绘制出第一点,它就不会持续更新图形和GUI。C#在Windows窗体应用程序中实时绘图
我应该在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();
}
}
}
回答:
使您的串口成为一个成员变量,然后添加一个计时器到您的窗体。然后,您可以解析串行数据,并将数据点附加到定时器回调中的图形中。
以上是 C#在Windows窗体应用程序中实时绘图 的全部内容, 来源链接: utcz.com/qa/266877.html