电容式触摸传感器:"触摸100 ms"

时间:2018-03-13 23:57:53

标签: arduino

我正面临一个编程问题,我想在触摸电容式触摸传感器100 ms时触发一些代码(以区分原型中的误报)。我的传感器被此代码触及

if (digitalRead(touchPin))

现在无论何时触摸100ms,我都想要一些其他代码(例如,激活LED)来运行。我似乎无法找到解决方案,因为我的startTime = millis()变量一直在重置。

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

  1. 你需要一个bool变量来存储最后一个状态(触摸时为TRUE,否则为FALSE)
  2. 此外,您需要存储更改为TRUE的时间。时间可以由millis()函数
  3. 来完成
  4. 如果您的bool变量为true,请检查,如果时间超过100毫秒。
  5. 所以:

    // In your global scope:
    ...
    // Last touch state
    bool isTouched = FALSE;
    // time, when last touch happened
    int touched_t = 0;
    
    // In your loop:
    ...
    bool isTouchedNow = (digitalRead(touchPin) == HIGH);
    // Touch state is changed till last measure:
    if (isTouchedNow != isTouched)
    {
       // Set "last isTouched state" to new one
       isTouched = isTouchedNow;
       // If it wasn't touched before, store current time (else zero):
       touched_t = isTouched ? millis() : 0;       
    }
    else //If touch state isn't changed till last time:
    {
       //If state was "touched" and now it "touched", and 100ms has passed:
       if (isTouched && touched_t > 0 && millis() - touched_t > 100)
       {
          // Call your function, that should be called, 
          // whan sensor is touched for 100 ms (activate a LED of something)
          DOTHESTUFF();
       }
    }
    ...