2017-10-18 84 views
2

我很抱歉提前标题可能非常混乱,但我不确定由于我的英文问题该如何解释。接受一段时间内改变的值保持改变

我有一个使用VS2008编写的C#表单应用程序,它不断从外部设备读取数据。读取的数据为0(OFF)或1(ON)。大多数情况下,它保持为0,但是当系统中发生某些事情时,它变为1并保持1 5秒钟并返回到0.
我的程序需要做的是始终观察值从0变化为1,并计数捕获事件的次数1.

问题是,有时外部设备有一个错误,并将事故中的值从0更改为1秒或更少。

我的程序需要忽略和不计数的发生如果将值从0变化到1持续小于1秒,和接受并计数出现如果从0到1的值的变化在5秒的生命中持续2秒。

我在想,基本上我只能增加计数只有当它保持1超过2秒,否则什么也不做。 我试图使用Thread.Sleep(2000),但它不起作用,我不认为这是正确的方式,但我还没有找到解决方案来实现这一点。

private int data; //will contain the data read from the ext. device 
private int occurrence = 0; 
//Tick runs every 100 seconds 
private void MyTick(object sender, EventArgs e) 
{ 
    //if data becomes 1 
    if(data == 1)  
    { 
      Thread.Sleep(2000); //wait 2 seconds??? does not work 
      //if the data stays 1 for 2 seconds, it is a valid value 
      if(?????) 
      { 
       occurrence++; //count up the occurrence 
      } 
    } 
} 

有人可以请给我一些建议,我可以做些什么来实现这一目标吗?

+0

您可能正在寻找'StopWatch'来精确测量已用时间。 – Equalsk

回答

1

您可以跟踪从0到1的开关被检测到的时间点,然后检查该时间段的长度。

事情是这样的:

private int occurrence; 
private int data; 
private int previousData; 
private DateTime? switchToOne; 

private void MyTick(object sender, EventArgs e) 
{ 
    if (data == 1 && previousData == 0) // switch detected 
    { 
     switchToOne = DateTime.Now; // notice the time point when this happened 
    } 

    // if the current value is still 1 
    // and a switch time has been noticed 
    // and the "1" state lasts for more than 2 seconds 
    if (data == 1 && switchToOne != null && (DateTime.Now - switchToOne.Value) >= TimeSpan.FromSeconds(2)) 
    { 
     // then count that occurrence 
     occurrence++; 

     // and reset the noticed time in order to count this occurrence 
     // only one time 
     switchToOne = null; 
    } 

    previousData = data; 
} 

注意DateTime不是很准确。 如果您需要执行非常准确的时间测量,则需要使用Stopwatch。但由于您使用Timer(我从您的事件处理程序中推断出这一点),所以我认为DateTime分辨率可以满足您的需求。

+0

感谢您的回答。我想知道如何在不使用Timer控件的情况下完成这项工作,因为它可以持续读取数据。在这种情况下,ValueChange事件是否使用'Stopwatch'控件? –

+1

我假设你使用'MyTick'事件处理程序和'Timer'。你是否使用了一些'ValueChanged'事件? (我不知道这个事件来自哪里。)如果是这样,那么我的解决方案无论如何将工作。 – dymanoid

+0

是的,你的猜测是正确的,而MyTick是一个'定时器'控制(我不好意思首先不提)。我只是想知道为什么'Timer'不是一个好主意来实现我想要实现的目标。 –