接受在一段时间内保持更改的更改值

Accept changed value that stayed changed for a certain period of time

提前道歉,标题可能很混乱,但由于我的英语问题,我不确定如何解释。

我有一个使用 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切换到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 分辨率将满足您的需要。