我正在尝试在 Arduino 中创建一个倒数计时器,该计时器将在按下按钮时启动,并且也会在按下相同按钮时中止。该值介于 0 - 60 之间,由电位器设置。到目前为止,我遇到的问题是循环开始后我无法退出循环。我知道它可以使用'break'来完成,但我不知道把它放在哪里才能达到预期的效果。这是我到目前为止所拥有的:
const int buttonPin = 2; // The pin that the pushbutton is attached to
int buttonState = 0; // Current state of the button
int lastButtonState = 0; // Previous state of the button
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void timer(){
int pot_value = analogRead(A0); //read potentiometer value
if (pot_value > 17) { //i set it so, that it doesn't start before the value
//isn't greater than the 60th part of 1023
int timer_value = map(pot_value, 0, 1023, 0, 60); //Mapping pot values to timer
for (int i = timer_value; i >= 0; i--){ //Begin the loop
Serial.println(i);
delay(1000);
}
}
}
void loop() {
// Read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// Compare the buttonState to its previous state
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
// If the current state is HIGH then the button
// went from off to on:
timer(); //run timer
}
else {
// If the current state is LOW then the button
// went from on to off:
Serial.println("off");
}
}
// Save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
例如,如果我将电位器设置为 5 并按下按钮,我会看到 5、4、3、2、1、0,关闭,但如果我再次按下按钮直到完成,我无法摆脱它。如何通过按一下按钮来逃避这个循环?