我在我的代码中使用计时器。我正在设置1s定时器,用于从arduino接收串行数据。现在,我想每1分钟写入excel文件。使用计时器。从根本上说它运作良好。每1秒写入excel。但我想每1分钟写一次。 下面我发布了计时器代码。这是设置为1s。当1秒超过增量计数器并在文本框上显示计数值时。
如果计数值达到60意味着1分钟。然后写入excel表,否则继续增加。
这是我的代码部分
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim counter As Integer
Try
SerialPort1.Write("c")
System.Threading.Thread.Sleep(250)
Dim k As Double
Dim value As String = SerialPort1.ReadLine()
k = CDbl(distance)
ListBoxSensor.Text = k
Dim s As New Series
s.Points.AddXY(1000, k)
Chart1.Series.Add(s)
Count_val.Text = counter
If counter = 6 Then
Dim headerText = ""
Dim csvFile As String = IO.Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not IO.File.Exists((csvFile)) Then
headerText = "Date& time ,value, "
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now()
Dim x As String = y + "," + value
outFile.Write(x)
End Using
End If
Catch ex As Exception
End Try
End Sub
答案 0 :(得分:0)
在您的计时器中,将子计数器声明为静态。使用 Dim ,值范围是本地的,返回后将丢失。这意味着在每个tick 计数器始终为零。 静态即使在返回后也会保留该值。
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Static counter As Integer = 0 'Initial value
counter += 1 'increase for every tick
Try
...
...
If counter = 60 Then
...
...
End If
Catch ex As Exception
MsgBox("Error in Timer1_Tick: " & ex.Message)
End Try
End Sub