2014-09-24 16 views
0

我在我的代碼中使用了定時器。我正在爲從arduino接收串行數據設置1s定時器。現在,我想每1分鐘寫入一次excel文件。使用定時器。單獨它工作正常。每1秒寫入excel。但我想每寫1分鐘。 下面我發佈了計時器代碼。這是設置爲1秒。當1秒鐘超過增量計數器並在文本框中顯示計數值時。如何在VB中計數定時器的值

如果計數值達到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

或者有什麼方法可以計算被調用的時間計時器的數量? – 2014-09-24 11:43:46

+1

'計數器'是一個永遠不會獲得價值的變量。另外,不要這樣做:'趕上例外結束嘗試'(空捕獲)。 – 2014-09-24 11:44:19

+0

@TimSchmelter如何做到這一點。我發現計時器我沒有從串行獲取數據例如code.with計時器我可以寫入CSV文件設置間隔時間。 – 2014-09-24 12:20:49

回答

0

在你的計時器滴答部分子聲明計數器靜態。使用Dim值範圍是本地的,返回後將丟失。這意味着在每個計時計數器始終爲零。 靜態即使返回後也​​保留該值。

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 
+0

感謝它爲我工作。 – 2014-09-25 05:47:13