设计思路
- 数据采集:通过串口通信与Arduino进行连接,获取温度传感器发送的数据。
- 异常数据过滤:设定温度合理范围,对采集到的数据进行判断,过滤掉超出范围的数据。
- 数据图形化展示:使用图表控件,将经过处理后的温度数据实时绘制在图表上。
关键代码片段
- 串口通信(初始化串口)
Imports System.IO.Ports
Public Class Form1
Private WithEvents serialPort As New SerialPort("COMX", 9600) '需根据实际COM口修改
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If serialPort.IsOpen = False Then
Try
serialPort.Open()
Catch ex As Exception
MessageBox.Show("串口打开失败: " & ex.Message)
End Try
End If
End Sub
- 接收数据并处理
Private Sub serialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles serialPort.DataReceived
Dim temperature As Double
Dim receivedData As String = serialPort.ReadLine()
If Double.TryParse(receivedData, temperature) Then
If temperature >= 0 And temperature <= 100 Then '假设合理范围0 - 100度
Invoke(New MethodInvoker(Sub() AddDataToChart(temperature)))
End If
End If
End Sub
- 数据图形化展示(假设使用Chart控件)
Private Sub AddDataToChart(ByVal value As Double)
Chart1.Series(0).Points.AddY(value)
If Chart1.Series(0).Points.Count > 100 Then '假设图表只显示最近100个数据
Chart1.Series(0).Points.RemoveAt(0)
End If
End Sub
- 关闭串口
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If serialPort.IsOpen Then
serialPort.Close()
End If
End Sub