c#按下buttonA按钮开始接收从单片机发来的8个传感器的数据,并在chart图中绘制这8个传感器数据曲线图,按下buttonB停止接收数据,停止绘图,按下buttonC保存8个传感器的数据值至Excel文件中
时间: 2024-02-13 07:02:55 浏览: 70
单片机采集数据
4星 · 用户满意度95%
您好,要实现这个功能,需要借助串口通信来接收单片机发送的数据,并使用Windows Forms Chart控件绘制数据曲线图,还需要使用EPPlus库来保存数据至Excel文件中。以下是一个简单的示例代码:
```csharp
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;
using OfficeOpenXml;
// 创建Chart对象和SerialPort对象
Chart chart1 = new Chart();
SerialPort serialPort1 = new SerialPort();
// 添加Chart控件到窗口
this.Controls.Add(chart1);
// 设置Chart控件属性
chart1.Location = new Point(10, 10);
chart1.Width = 600;
chart1.Height = 400;
// 添加八个Series对象
Series[] series = new Series[8];
for (int i = 0; i < 8; i++)
{
series[i] = chart1.Series.Add("Sensor " + (i+1));
series[i].ChartType = SeriesChartType.FastLine;
}
// 创建Excel文件和工作表对象
ExcelPackage excel = new ExcelPackage();
ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Sensor Data");
// 添加列头
worksheet.Cells[1, 1].Value = "Time";
for (int i = 0; i < 8; i++)
{
worksheet.Cells[1, i+2].Value = "Sensor " + (i+1);
}
// 定义变量
bool isReceivingData = false;
DateTime startTime = DateTime.MinValue;
int dataCount = 0;
// 按下buttonA按钮开始接收数据
private void buttonA_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
serialPort1.PortName = "COM3"; // 设置串口号
serialPort1.BaudRate = 9600; // 设置波特率
serialPort1.Open();
}
isReceivingData = true;
startTime = DateTime.Now;
dataCount = 0;
}
// 按下buttonB按钮停止接收数据
private void buttonB_Click(object sender, EventArgs e)
{
isReceivingData = false;
}
// 按下buttonC按钮保存数据至Excel文件中
private void buttonC_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel files (*.xlsx)|*.xlsx";
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog1.FileName;
excel.SaveAs(new FileInfo(filePath));
}
}
// 串口数据接收事件处理函数
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (isReceivingData)
{
string data = serialPort1.ReadLine();
string[] values = data.Split(',');
if (values.Length == 8)
{
// 解析数据并绘制曲线图
double[] sensorData = new double[8];
for (int i = 0; i < 8; i++)
{
sensorData[i] = double.Parse(values[i]);
series[i].Points.AddXY(DateTime.Now.Subtract(startTime).TotalSeconds, sensorData[i]);
}
// 在Excel文件中保存数据
dataCount++;
worksheet.Cells[dataCount+1, 1].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < 8; i++)
{
worksheet.Cells[dataCount+1, i+2].Value = sensorData[i];
}
}
}
}
```
上述代码实现了按下buttonA按钮开始接收数据,按下buttonB按钮停止接收数据,并在Chart控件中绘制八个传感器数据曲线图。同时,按下buttonC按钮可以将数据保存至Excel文件中。您可以根据自己的需求,对代码进行修改和优化。
阅读全文