这是我要实现的目标:
用户使用旋转编码器输入时间。
随着用户不断旋转编码器,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;
}
}
答案 0 :(得分:0)
如果我很了解,您仅在输入i
时才递减if (currentMillis - previousMillis == interval)
。这意味着您的减量速度非常缓慢,而不是毫秒级的递减…
要纠正这个问题,我建议:
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()));
}
}
希望有帮助!