在VB.Net中使用多个计时器

时间:2015-08-29 13:02:55

标签: .net vb.net visual-studio visual-studio-2012

我想在Visual Studio 2012中使用多个计时器从PLC(可编程逻辑控制器,电子设备)中的多个寄存器读取数据。当我只使用一个定时器读取一个寄存器时,我得到了正确的数据但是当我想要读取另一个寄存器时,没有一个接收的数据正确显示(它从0到实际值波动)。我用我朋友的图书馆来实现这个目标。所以我不知道图书馆.. 这是代码:

Imports Communication

Public Class Form1
    Dim plc As PLCEthernetReadWrite

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        plc = New PLCEthernetReadWrite("192.168.1.5")
        Timer1.Start()
        Timer2.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Label1.Text = plc.ReadWord("404507") 'Where 404507 is register no.
        Label4.Text = Val(Label1.Text) / 100
    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        Label1.Text = plc.ReadWord("002071") 'Where 002071 is register no.
        Label4.Text = Val(Label1.Text) / 100
    End Sub
End Class

如果我只使用一个计时器(timer1或timer2),那么我得到适当的值。但我想从多个寄存器中显示多个值。

2 个答案:

答案 0 :(得分:0)

我怀疑存在线程问题。尽量避免同时调用plc.ReadWord。

    Private plcLock As New Object

    Private Function GetPlcValue(plc As PLCEthernetReadWrite, word As String) As String
        SyncLock plcLock
            Return plc.ReadWord(word)
        End SyncLock
    End Function

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Label1.Text = GetPlcValue(plc, "404507") 'Where 404507 is register no.
        Label4.Text = Val(Label1.Text) / 100
    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        Label1.Text = GetPlcValue(plc, "002071") 'Where 002071 is register no.
        Label4.Text = Val(Label1.Text) / 100
    End Sub

答案 1 :(得分:0)

感谢您的帮助。我想通了,问题在于时间问题。我将计时器间隔从100毫秒增加到200毫秒,一切正常。然后我添加了第三个plc.ReadWord,程序又开始行为不端。然后我再次将计时器间隔增加到300毫秒,并且一切都运行良好。感谢。