我试图绘制使用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();
}
}
}
答案 0 :(得分:0)
使您的串口成为成员变量,然后在表单中添加一个计时器。然后,您可以解析串行数据并将数据点附加到计时器回调中的图形中。