首页 > 解决方案 > 在定义的次数和时间内将引脚设置为高电平的功能

问题描述

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

我打电话hapticFeedback(1000, 2, 1);

变量定义为

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

这是功能。出于某种原因,我只将引脚设置为高电平而不是闪烁和低电平


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;

}

标签: c++arduinonested-loops

解决方案


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

在循环中我有

    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;

当达到重复次数时,我放下 oneshot,强制输出为高,使其通过例程变为低,最后重置我的重复计数器。

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


推荐阅读