硬件是STM32:
软件开发环境是VS2012
通讯方式:SERIAL
PC界面主要是曲线绘制以及数据库的操作
上传部分多线程代码
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Data.SqlClient; 10 using System.Threading; 11 using System.IO.Ports; 12 using ZedGraph; 13 14 namespace WindowsFormsApplication1 15 { 16 public partial class Form1 : Form 17 { 18 public Form1() 19 { 20 InitializeComponent(); 21 } 22 private static string connectString = "";// = "Data Source=(LocalDB)\\v11.0;Initial Catalog=testdb;Integrated Security=True"; 23 private static SqlConnection sqlCnt = null;// = new SqlConnection(connectString); 24 private static bool Closing_serial = false, start_or_pause = false; 25 private static List<byte> buffer = new List<byte>(4096); 26 private static byte[] binary_data_1 = new byte[9]; 27 private static byte ack0, ack1; 28 private static ushort volt, temperature, soc; 29 private static short current; 30 public static Thread th; 31 public static Thread th_graph; 32 33 /// <summary> 34 /// 曲线绘制的list的一个对象 35 /// </summary> 36 private static PointPairList v1List = new PointPairList(); 37 private static PointPairList v2List = new PointPairList(); 38 private static PointPairList v3List = new PointPairList(); 39 40 private static int sampleCnt = 0; 41 /// <summary> 42 /// 锁的变量,因为在操作数据库的时候发现会弹出invalid操作 43 /// </summary> 44 static object _object = new object(); 45 public delegate void UpdateGridView(); 46 public UpdateGridView updategrdv; 47 48 /// <summary> 49 /// 定义委托,申明一个委托对象去执行th_graph线程的任务 50 /// </summary> 51 /// <param name="commdata"></param> 52 public delegate void UpdateGraph(List<int> commdata); 53 public UpdateGraph updategrph; 54 55 //private void DoWork() 56 //{ 57 // Cinvokes ivk = new Cinvokes(Updata); 58 // BeginInvoke(ivk, null); 59 //} 60 61 //private void Updata(SqlConnection conn) 62 /// <summary> 63 /// 函数说明: 64 /// 65 /// </summary> 66 /// <param name="commdata"></param> 67 public void UpdateGra(List<int> commdata) 68 { 69 double time = sampleCnt; //曲线的横坐标点 70 v1List.Add(time, commdata[0]); // 电流 71 v2List.Add(time, commdata[1]); // 电压 72 v3List.Add(time, commdata[2]); // 温度 73 graph.GraphPane.YAxis.Scale.MajorStepAuto = true; //自动Y轴的step 74 graph.GraphPane.YAxis.Scale.MinorStepAuto = true; 75 graph.AxisChange(); // 更新曲线的x轴 76 graph.Invalidate(); // 更新曲线 77 sampleCnt++; //曲线的X轴添加横坐标点 78 } 79 /// <summary> 80 /// 数据库实时显示数据,支持CSV格式保存 81 /// </summary> 82 private void Updata() 83 { 84 //lock (_object) 85 //{ 86 //string connectString = "Data Source=C:\\Users\\Administrator\\AppData\\Local\\Microsoft\\Microsoft SQL Server Local DB\\Instances\\v11.0;Initial Catalog=C:\\Users\\Administrator\\testdb;Integrated Security=True"; 87 //string connectString = "Data Source=(LocalDB)\\v11.0;Initial Catalog=testdb;Integrated Security=True";//(localdb)\v11.0 C:\\Users\\Administrator\\ 88 //SqlConnection sqlCnt = new SqlConnection(connectString); 89 try 90 { 91 if (sqlCnt.State == ConnectionState.Closed) sqlCnt.Open(); 92 } 93 catch (System.Exception ex) 94 { 95 MessageBox.Show("open fail" + ex.ToString()); 96 return; 97 } 98 string sql = "select * from [dbo].[Table1]"; 99 //SqlCommand cmd = sqlCnt.CreateCommand(); // 创建SqlCommand对象 100 SqlCommand cmd = new SqlCommand(sql, sqlCnt); 101 //cmd.CommandType = CommandType.Text; 102 //cmd.CommandText = "select * from [dbo].[Table1]"; // sql语句 103 104 SqlDataReader reader = cmd.ExecuteReader(); //执行SQL,返回一个“流” 105 int cnt = 0; 106 int colIdx = 0; 107 //BeginInvoke((MethodInvoker)delegate() 108 //{ 109 dataGridView1.Rows.Clear(); 110 while (reader.Read()) 111 { 112 dataGridView1.Rows.Add(1); 113 colIdx = 0; 114 dataGridView1.Rows[cnt].Cells[colIdx++].Value = cnt + 1; 115 dataGridView1.Rows[cnt].Cells[colIdx++].Value = reader["curr"]; 116 dataGridView1.Rows[cnt].Cells[colIdx++].Value = reader["vol"]; 117 dataGridView1.Rows[cnt].Cells[colIdx++].Value = reader["temp"]; 118 cnt++; 119 //MessageBox.Show(reader["curr"] + " " + reader["vol"] + " " + reader["temp"]); 120 } 121 reader.Dispose(); 122 //int tmp = dataGridView1.ColumnHeadersHeight + 123 // (dataGridView1.Rows.Count * dataGridView1.Rows[0].Height); 124 //if (tmp > dataGridView1.Height) 125 //{ 126 // dataGridView1 = 127 // dataGridView1.FirstDisplayedScrollingRowIndex * dataGridView1.Rows[0].Height + 128 // dataGridView1.ColumnHeadersHeight; 129 //} 130 dataGridView1.FirstDisplayedScrollingRowIndex = cnt; 131 //}); 132 //closeConn(); 133 //} 134 } 135 /// <summary> 136 /// 曲线线程要做的事情用委托去执行 137 /// </summary> 138 public void graphwork() 139 { 140 while (true) 141 { 142 List<int> comm = new List<int>(3) { current , volt, temperature}; 143 //comm.Add(current); 144 //comm.Add(volt); 145 //comm.Add(temperature); 146 this.BeginInvoke(updategrph, comm); 147 Thread.Sleep(timer1.Interval); 148 } 149 } 150 /// <summary> 151 /// 数据库实时显示数据 152 /// </summary> 153 public void threadwork() 154 { 155 //this.BeginInvoke(updategrdv); 156 while (true) 157 { 158 this.BeginInvoke(updategrdv); 159 Thread.Sleep(timer1.Interval); 160 } 161 } 162 /// <summary> 163 /// 打开STM32设备的按钮事件 164 /// </summary> 165 public void openconn() 166 { 167 try 168 { 169 sqlCnt.Open(); 170 } 171 catch (System.Data.SqlClient.SqlException ex) 172 { 173 MessageBox.Show("open fail" + ex.ToString()); 174 return; 175 } 176 } 177 /// <summary> 178 /// 关闭数据库连接 179 /// </summary> 180 public void closeConn() 181 { 182 sqlCnt.Close(); 183 sqlCnt.Dispose(); 184 } 185 /// <summary> 186 /// 曲线初始化 设定4个曲线list 187 /// </summary> 188 /// <param name="zgc"></param> 189 public void CreateChart(ZedGraphControl zgc) 190 { 191 GraphPane myPane = zgc.GraphPane; //设置一个曲线对象变量 192 myPane.Chart.Border.IsVisible = false; //是否显示边框 193 194 myPane.Title.Text = "电流 电压 温度曲线"; //曲线标题 195 myPane.XAxis.Title.Text = "采样计数"; //曲线x轴标题 196 myPane.YAxis.Title.Text = "参数值"; //曲线y轴标题 197 198 /************************************************************************/ 199 /* 设置第1条曲线 */ 200 /************************************************************************/ 201 // Generate a red curve with diamond symbols, and "Velocity" in the legend 202 LineItem myCurve = myPane.AddCurve("电压", 203 v1List, Color.Red, SymbolType.None); //添加曲线电压1 204 // Fill the symbols with white 205 myCurve.Symbol.Fill = new Fill(Color.White); //符号的颜色 206 // Make the Y axis scale red 207 myPane.YAxis.Scale.FontSpec.FontColor = Color.Red; //刻度颜色 208 myPane.YAxis.Title.FontSpec.FontColor = Color.Red; //标题颜色 209 myPane.Legend.FontSpec.Size = 20; //图例大小 210 myPane.YAxis.Color = Color.Red; //Y轴颜色 211 myPane.YAxis.MajorTic.Color = Color.Red; //Y轴大跨度颜色 212 myPane.YAxis.MinorTic.Color = Color.Red; //Y轴小跨度颜色 213 myPane.YAxis.MajorTic.Size = 5; // Y轴大跨度 字体大小 214 myPane.YAxis.MajorTic.PenWidth = 2; // Y轴大跨度 字体宽度 215 myPane.YAxis.MinorTic.Size = 2.5f;//Y轴小跨度大小 216 myPane.YAxis.MinorTic.PenWidth = 2;//Y轴小跨度厚度 217 // turn off the opposite tics so the Y tics don't show up on the Y2 axis 218 myPane.YAxis.MajorTic.IsOpposite = false; //大跨度是否双向 219 myPane.YAxis.MinorTic.IsOpposite = false; //小跨度是否双向 220 // Don't display the Y zero line 221 myPane.YAxis.MajorGrid.IsZeroLine = false; //零点线 222 // Align the Y axis labels so they are flush to the axis 223 myPane.YAxis.Scale.Align = AlignP.Inside; //Y轴和Y2轴是否同一方向 224 myPane.YAxis.Scale.MaxAuto = true; //最大值自动 225 myPane.YAxis.Scale.MinAuto = true; //最小值自动 226 myPane.YAxis.Scale.MajorStep = 0.5; //设置大跨度的刻度间隔 227 myPane.YAxis.Scale.MinorStep = 0.1; //设置小跨度的刻度间隔 228 /************************************************************************/ 229 /* 设置第2条曲线 */ 230 /************************************************************************/ 231 // Generate a blue curve with circle symbols, and "Acceleration" in the legend 232 myCurve = myPane.AddCurve("电流", 233 v2List, Color.Blue, SymbolType.None); 234 235 myCurve.Symbol.Fill = new Fill(Color.White); 236 237 myPane.Y2Axis.IsVisible = true; //Y2轴是否显示(右边) 238 myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue; //设定y2轴线的颜色 239 myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue; //设定y2轴标题的颜色 240 myPane.Y2Axis.Color = Color.Blue; //设定Y2对应曲线的颜色 241 myPane.Y2Axis.MajorTic.Color = Color.Blue; //设定Y2轴刻度上大跨度的颜色 242 myPane.Y2Axis.MinorTic.Color = Color.Blue; //设定Y2轴刻度上小跨度的颜色 243 myPane.Y2Axis.MajorTic.Size = 5; //设定Y2轴大跨度字体的厚度 244 myPane.Y2Axis.MajorTic.PenWidth = 2; //设定Y2轴大跨度字体的大小 245 myPane.Y2Axis.MinorTic.Size = 2.5f; //设定Y2轴小跨度字体的厚度 246 myPane.Y2Axis.MinorTic.PenWidth = 2; //设定Y2轴小跨度字体的厚度 247 myPane.Y2Axis.MajorGrid.IsZeroLine = false; //是否显示零点线 248 // turn off the opposite tics so the Y2 tics don't show up on the Y axis 249 myPane.Y2Axis.MajorTic.IsOpposite = false; //Y2轴线大跨度是否双向 250 myPane.Y2Axis.MinorTic.IsOpposite = false; //Y2轴线小跨度是否双向 251 // Display the Y2 axis grid lines 252 myPane.Y2Axis.MajorGrid.IsVisible = true; //Y2轴线是否显示 253 // Align the Y2 axis labels so they are flush to the axis 254 myPane.Y2Axis.Scale.Align = AlignP.Inside; //Y2轴刻度线在内部或外部 255 /************************************************************************/ 256 /* 设置第3条曲线 */ 257 /************************************************************************/ 258 // Generate a green curve with square symbols, and "Distance" in the legend 259 myCurve = myPane.AddCurve("温度", 260 v3List, Color.Green, SymbolType.None); 261 // Fill the symbols with white 262 myCurve.Symbol.Fill = new Fill(Color.White); 263 264 YAxis yAxis3 = new YAxis(""); 265 myPane.YAxisList.Add(yAxis3); 266 yAxis3.Scale.FontSpec.FontColor = Color.Green; 267 yAxis3.Title.FontSpec.FontColor = Color.Green; 268 yAxis3.Color = Color.Green; 269 yAxis3.MajorTic.Color = Color.Green; 270 yAxis3.MinorTic.Color = Color.Green; 271 yAxis3.MajorTic.Size = 5; 272 yAxis3.MajorTic.PenWidth = 2; 273 yAxis3.MinorTic.Size = 2.5f; 274 yAxis3.MinorTic.PenWidth = 2; 275 yAxis3.Scale.FontSpec.IsBold = true; 276 yAxis3.MajorTic.IsInside = true; 277 yAxis3.MinorTic.IsInside = true; 278 yAxis3.MajorTic.IsOpposite = false; 279 yAxis3.MinorTic.IsOpposite = false; 280 yAxis3.Scale.Align = AlignP.Inside; 281 yAxis3.MajorGrid.IsZeroLine = false; 282 /******************************************/ 283 // Show the x axis grid 284 myPane.XAxis.MajorGrid.IsVisible = true; 285 myPane.XAxis.Color = Color.Gray; 286 myPane.XAxis.Scale.FontSpec.FontColor = Color.Gray; 287 myPane.XAxis.MajorTic.Color = Color.Transparent; 288 myPane.XAxis.MinorTic.Color = Color.Transparent; 289 myPane.XAxis.Color = Color.Transparent; 290 // Fill the axis background with a gradient 291 // myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f); 292 myPane.Chart.Fill = new Fill(Color.White, Color.WhiteSmoke, 45.0f); 293 } 294 /// <summary> 295 /// 窗体初始化 296 /// </summary> 297 /// <param name="sender"></param> 298 /// <param name="e"></param> 299 private void Form1_Load(object sender, EventArgs e) 300 { 301 connectString = "Data Source=(LocalDB)\\v11.0;Initial Catalog=testdb;Integrated Security=True"; 302 sqlCnt = new SqlConnection(connectString); 303 //comboBox1.SelectedIndex = 1; 304 //th = new Thread(Updata); 305 //th = new Thread(new ThreadStart(DoWork)); 306 //th = new Thread(new ThreadStart(delegate 307 //{ 308 // threadwork(); 309 //})); 310 //objThread.Start(); 311 CreateChart(graph); 312 313 updategrdv = new UpdateGridView(Updata); 314 updategrph = new UpdateGraph(UpdateGra); 315 } 316 /// <summary> 317 /// 插入数据到数据库当中【测试用的】 318 /// </summary> 319 /// <param name="sender"></param> 320 /// <param name="e"></param> 321 private void button_insert_Click(object sender, EventArgs e) 322 { 323 //string connectString = "Data Source=C:\\Users\\Administrator\\AppData\\Local\\Microsoft\\Microsoft SQL Server Local DB\\Instances\\v11.0;Initial Catalog=C:\\Users\\Administrator\\testdb;Integrated Security=True"; 324 //string connectString = "Data Source=(LocalDB)\\v11.0;Initial Catalog=testdb;Integrated Security=True"; 325 if (sqlCnt.State == ConnectionState.Closed) openconn(); 326 SqlCommand cmd = sqlCnt.CreateCommand(); // 创建SqlCommand对象 327 cmd.CommandType = CommandType.Text; 328 329 330 if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "") cmd.CommandText = "INSERT INTO [dbo].[Table1] ([curr], [vol], [temp]) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ")"; // sql语句 331 else { MessageBox.Show("插入数据为空 请输入后重试~"); return; } 332 //MessageBox.Show(cmd.CommandText); 333 //cmd.Parameters.Add("@curr", label_cur.Text); 334 //cmd.Parameters.Add("@vol", label_vol.Text); 335 //cmd.Parameters.Add("@temp", label_temp.Text); 336 337 try 338 { 339 int isInsertSuccess = cmd.ExecuteNonQuery(); 340 341 if (isInsertSuccess == 1) { } 342 //MessageBox.Show("insert( " + textBox1.Text + ", " + textBox2.Text + ", " + textBox3.Text + " )success!"); 343 } 344 catch (System.Exception ex) 345 { 346 MessageBox.Show(ex.ToString()); 347 } 348 finally 349 { 350 //closeConn(); 351 } 352 } 353 /// <summary> 354 /// 查询数据,主要是将所有数据显示到表格当中 355 /// </summary> 356 /// <param name="sender"></param> 357 /// <param name="e"></param> 358 private void button_query_Click(object sender, EventArgs e) 359 { 360 lock (_object) 361 { 362 //string connectString = "Data Source=C:\\Users\\Administrator\\AppData\\Local\\Microsoft\\Microsoft SQL Server Local DB\\Instances\\v11.0;Initial Catalog=C:\\Users\\Administrator\\testdb;Integrated Security=True"; 363 //string connectString = "Data Source=(LocalDB)\\v11.0;Initial Catalog=testdb;Integrated Security=True";//(localdb)\v11.0 C:\\Users\\Administrator\\ 364 //SqlConnection sqlCnt = new SqlConnection(connectString); 365 try 366 { 367 if (sqlCnt.State == ConnectionState.Closed) sqlCnt.Open(); 368 } 369 catch (System.Exception ex) 370 { 371 MessageBox.Show("open fail" + ex.ToString()); 372 return; 373 } 374 string sql = "select * from [dbo].[Table1]"; 375 //SqlCommand cmd = sqlCnt.CreateCommand(); // 创建SqlCommand对象 376 SqlCommand cmd = new SqlCommand(sql, sqlCnt); 377 //cmd.CommandType = CommandType.Text; 378 //cmd.CommandText = "select * from [dbo].[Table1]"; // sql语句 379 380 SqlDataReader reader = cmd.ExecuteReader(); //执行SQL,返回一个“流” 381 int cnt = 0; 382 int colIdx = 0; 383 dataGridView1.Rows.Clear(); 384 while (reader.Read()) 385 { 386 dataGridView1.Rows.Add(1); 387 colIdx = 0; 388 dataGridView1.Rows[cnt].Cells[colIdx++].Value = cnt + 1; 389 dataGridView1.Rows[cnt].Cells[colIdx++].Value = reader["curr"]; 390 dataGridView1.Rows[cnt].Cells[colIdx++].Value = reader["vol"]; 391 dataGridView1.Rows[cnt].Cells[colIdx++].Value = reader["temp"]; 392 cnt++; 393 //MessageBox.Show(reader["curr"] + " " + reader["vol"] + " " + reader["temp"]); 394 } 395 396 reader.Dispose(); 397 //closeConn(); 398 } 399 } 400 /// <summary> 401 /// 连接STM32 402 /// </summary> 403 /// <param name="sender"></param> 404 /// <param name="e"></param> 405 private void button_connect_Click(object sender, EventArgs e) 406 { 407 try 408 { 409 serialPort1.PortName = "COM7"; 410 serialPort1.BaudRate = 115200; 411 serialPort1.Open(); 412 button_connect.Text=serialPort1.IsOpen?"关闭串口":"打开串口"; 413 timer1.Enabled=serialPort1.IsOpen?true:false; 414 } 415 catch (System.Exception ex) 416 { 417 MessageBox.Show(ex.ToString()); 418 } 419 } 420 /// <summary> 421 /// 发送一个命令给SMT32,让它将实时数据返回给PC 422 /// </summary> 423 /// <param name="sender"></param> 424 /// <param name="e"></param> 425 private void button_sample_Click(object sender, EventArgs e) 426 { 427 start_or_pause = !start_or_pause; 428 if (start_or_pause) 429 { 430 th = new Thread(new ThreadStart(delegate 431 { 432 threadwork(); 433 })); 434 th.Start(); 435 436 th_graph = new Thread(new ThreadStart(delegate 437 { 438 graphwork(); 439 })); 440 th_graph.Start(); 441 442 button_sample.Text = "停止采样"; 443 byte[] package = new byte[9]; 444 package[0] = 0xaa; //帧头 445 package[1] = 6; //lenth 446 package[2] = 0; //ff代表正常,00代表正在处理其他事情 447 package[3] = 0xA2; //命令 448 package[4] = 0x90; //数据 449 package[5] = 0x90; //数据 450 package[6] = 0x90; //数据 451 package[7] = 0x90; //数据 452 package[8] = 0x0d; //帧尾 453 try 454 { 455 serialPort1.Write(package, 0, 9); //发9个字节 456 } 457 catch (System.InvalidOperationException ex) 458 { 459 MessageBox.Show(ex.ToString()); 460 } 461 } 462 else 463 { 464 button_sample.Text = "开始采样"; 465 th.Abort(); 466 467 th_graph.Abort(); 468 } 469 } 470 /// <summary> 471 /// 在串口事件当中根据STM32发送数据 解析数据 472 /// </summary> 473 private void deal_byte() 474 { 475 switch (binary_data_1[3]) //根据命令来解析数据 476 { 477 case 0: 478 ack0 = (byte)(binary_data_1[4] * 256 + binary_data_1[5]); //识别码1 479 ack1 = (byte)(binary_data_1[6] * 256 + binary_data_1[7]); //识别码2 480 break; 481 case 1: 482 volt = (UInt16)(binary_data_1[4] * 256 + binary_data_1[5]); //电压 483 temperature = (UInt16)(binary_data_1[6] * 256 + binary_data_1[7]); //温度 484 break; 485 case 2: 486 soc = (UInt16)(binary_data_1[4] * 256 + binary_data_1[5]); //SOC 487 current = (short)(binary_data_1[6] * 256 + binary_data_1[7]); //电流 488 break; 489 490 } 491 } 492 /// <summary> 493 /// 协议 0xaa 0x44 len(5) cmd(01) data(uint16) data1(unin16) XOR 494 /// </summary> 495 /// <param name="sender"></param> 496 /// <param name="e"></param> 497 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 498 { 499 if (Closing_serial) return; //关闭窗体时做一个标志位 500 try 501 { 502 // Listening = true; //串口事件发生标志位 503 int n = serialPort1.BytesToRead; //读取串口事件发生时的字节数 504 byte[] buf = new byte[n]; //申明数组保存一帧数据 505 serialPort1.Read(buf, 0, n); //读取缓冲数据 506 bool data_1_catched = false; //缓存记录数据是否捕获到 507 buffer.AddRange(buf); //缓存到listbuffer里面去 508 while (buffer.Count >= 4) //这里用while是因为里面有break 和continue 509 { 510 if (buffer[0] == 0xbb && buffer[1] == 0x44) //判断头 511 { 512 int len = buffer[2]; //下位机发送的字节数 513 if (buffer.Count < len + 4) break; //如果接受数据数小于字节数,继续接受 514 byte checksum = 0; //异或效验变量 515 for (int i = 3; i < len + 3; i++) //len=5 516 { checksum ^= buffer[i]; } //得到效验值 517 if (checksum != buffer[len + 3]) //如果效验失败,这个数据不要,继续接受下一个数据 518 { buffer.RemoveRange(0, len + 4); continue; } //这里的continue是说while循环,不是if 519 buffer.CopyTo(0, binary_data_1, 0, len + 4); //复制一条完整数据到具体的数据缓存 520 data_1_catched = true; 521 buffer.RemoveRange(0, len + 4); //正确分析一条数据,从缓存中移除数据。 522 } 523 else 524 { buffer.RemoveAt(0); } //如果包的第一个数据错误,则重新开始 525 } 526 if (data_1_catched) 527 { 528 deal_byte(); //用变量保存想要的数据 529 } 530 } 531 catch(System.InvalidOperationException ex) 532 { 533 MessageBox.Show(ex.ToString()); 534 } 535 } 536 537 private void timer1_Tick(object sender, EventArgs e) 538 { 539 if (sqlCnt.State == ConnectionState.Closed) 540 openconn(); 541 label1.Text = sqlCnt.State.ToString();// +timer1.Interval.ToString(); 542 SqlCommand cmd = sqlCnt.CreateCommand(); // 创建SqlCommand对象 543 cmd.CommandType = CommandType.Text; 544 545 //if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "") cmd.CommandText = "INSERT INTO [dbo].[Table1] ([curr], [vol], [temp]) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ")"; // sql语句 546 if (serialPort1.IsOpen && start_or_pause) 547 { 548 //if (current == 0 && volt == 0 && temperature == 0) 549 //{ MessageBox.Show("未开始采样 请点击开始采样~"); return; } 550 //else 551 cmd.CommandText = "INSERT INTO [dbo].[Table1] ([curr], [vol], [temp]) VALUES (" + current + "," + volt + "," + temperature + ")"; // sql语句 552 try 553 { 554 string tmp = cmd.CommandText; 555 int isInsertSuccess = cmd.ExecuteNonQuery(); 556 557 if (isInsertSuccess == 1) { } 558 //MessageBox.Show("insert" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "success!"); 559 //MessageBox.Show("insert (" + current + ", " + volt + ", " + temperature + " )success!"); 560 } 561 catch (System.Data.SqlClient.SqlException ex) 562 { 563 //MessageBox.Show(ex.ToString()); 564 return; 565 } 566 } 567 //closeConn(); 568 } 569 570 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 571 { 572 switch (comboBox1.SelectedIndex) 573 { 574 case 0: 575 //string tmp = comboBox1.SelectedText; 576 timer1.Interval = Convert.ToInt32(comboBox1.Text); 577 break; 578 case 1: 579 timer1.Interval = Convert.ToInt32(comboBox1.Text); 580 break; 581 case 2: 582 timer1.Interval = Convert.ToInt32(comboBox1.Text); 583 break; 584 default: break; 585 } 586 } 587 588 private void button_clear_db_Click(object sender, EventArgs e) 589 { 590 if (sqlCnt.State == ConnectionState.Closed) openconn(); 591 SqlCommand cmd = sqlCnt.CreateCommand(); // 创建SqlCommand对象 592 cmd.CommandType = CommandType.Text; 593 594 cmd.CommandText = "TRUNCATE TABLE [dbo].[Table1]"; 595 596 try 597 { 598 int isInsertSuccess = cmd.ExecuteNonQuery(); 599 600 if (isInsertSuccess == -1) 601 { 602 //MessageBox.Show("数据库数据已全部清除"); 603 dataGridView1.Rows.Clear(); 604 } 605 } 606 catch (System.Exception ex) 607 { 608 MessageBox.Show(ex.ToString()); 609 } 610 finally 611 { 612 //closeConn(); 613 } 614 } 615 616 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 617 { 618 try 619 { 620 closeConn(); 621 th.Abort(); 622 th_graph.Abort(); 623 } 624 catch (System.Exception ex) 625 { 626 return; 627 } 628 629 } 630 631 } 632 }