在定义的次数和时间内将引脚设置为高电平的功能

function that set pin high for defined number of times and time

我遇到这个问题,我尝试将输出引脚设置为高电平一段时间。

我用 hapticFeedback(1000, 2, 1);

打电话

变量定义为

unsigned long hapticPreviousMillis = 0;
int hapticState = LOW;
int oneshotHaptic = 0;

这是函数。出于某种原因,我只将引脚设置为 HIGH 而不是闪烁和 LOW


void hapticFeedback(int activeLength, int repeats, int oneshotHaptic) {  

    if (oneshotHaptic == 1) {

        for (int x = 0; x <= repeats; x++) {

           unsigned long currentMillis = millis();

           if (currentMillis - hapticPreviousMillis >= (unsigned long)activeLength) {

                hapticPreviousMillis = currentMillis;


                if (hapticState == LOW) {
                    hapticState = HIGH;
                }
                else {
                    hapticState = LOW;
                }

                digitalWrite(haptic, hapticState);
            }
        }

    }

    oneshotHaptic = 0;

}

所以我弄明白了,如果其他人正在寻找这个,这就是我想出的。它可能不是最流畅的代码,但它完成了我想要它做的事情

在我的循环中

    if (setOneshotHaptic == 1) {

    hapticFeedback(activeLength);
}

触觉功能看起来像这样

void hapticFeedback(int activeLength) {  

    unsigned long currentMillis = millis();

     if (currentMillis - hapticPreviousMillis >= (unsigned long)activeLength) {

         hapticPreviousMillis = currentMillis;

         if (x == repeats) {
                         setOneshotHaptic = false;
                         hapticState = HIGH;
                         x = 0;
         }

         if (hapticState == LOW) {
             hapticState = HIGH;
             x++;
         }
         else {
             hapticState = LOW;

         }

         digitalWrite(haptic, hapticState);

     }

}

每当我想获得触觉反馈时,我都可以定义以下变量

    setOneshotHaptic = true;
    repeats = 3;
    activeLength = 1000;

当达到重复次数时,我放下单发,按例程强制输出为高电平,最后重置我的重复计数器。

可能有更好的方法来做到这一点。但是我找不到它们,这对我有用....