Arduino旋转编码器计时器



这就是我要实现的目标:用户使用旋转编码器输入时间。当用户继续旋转编码器时,Arduino串行显示器必须显示时间的实时值。然后,用户点击物理开关(推动开关(以启动倒计时。最初,我的代码与delay()功能完美搭配。但是,我的应用程序还要求我运行电动机,只要计时器持续。为此,我需要一个非阻滞延迟。我很难过。请帮忙。这是我的代码:

unsigned long previousMillis = 0;        // will store last time LED was updated
// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)
#define outputA 6
#define outputB 7
int i;
int button=5;
int counter = 0; 
int aState;
int aLastState;  

void setup() {
  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);
  pinMode (button,INPUT);
  Serial.begin (9600);
  // Reads the initial state of the outputA
  aLastState = digitalRead(outputA);   
}
void loop() {
  // here is where you'd put code that needs to be running all the time.
  aState = digitalRead(outputA); // Reads the "current" state of the outputA
  // If the previous and the current state of the outputA are different, that means a Pulse has occured
  if (aState != aLastState) {     
    // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
    if (digitalRead(outputB) != aState) { 
      counter = counter+1;
    } else {
      counter = counter-1;
    }
    Serial.print("Time (secs): ");
    Serial.println(counter);
    i = counter;
    if (digitalRead(button) == HIGH) {
      while (i != 0) {
        unsigned long currentMillis = millis();
        if (currentMillis - previousMillis == interval) {
          // save the last time you blinked the LED
          previousMillis = currentMillis;
          i--;
          Serial.println(i);
        }
      }
    }
    aLastState = aState; 
  }
}

如果我了解很好,则仅在输入if (currentMillis - previousMillis == interval)时降低i。这意味着您的减少非常缓慢,而不是毫秒毫秒……

要纠正我建议:

unsigned long startMillis = millis();
while (millis() - startMillis() < counter){ //check if your time has elapsed
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis == interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
    Serial.println((int) counter - (millis() - startMillis()));
   }

}

希望它有帮助!

最新更新