简体   繁体   English

Arduino中的中断功能

[英]Interrupt function in Arduino

I'm currently working on project which takes the button as input and when we click the button starting from the first LED it shifts and after each 0.5 seconds LEDs follow each other.我目前正在研究将按钮作为输入的项目,当我们从第一个 LED 开始单击按钮时,它会移动,每 0.5 秒后 LED 会相互跟随。 Interrupt function works perfectly, but the problem is that interrupt works when the loop is finished.中断功能完美运行,但问题是当循环结束时中断才起作用。 I want to turn of the LEDs when I click the button.我想在单击按钮时关闭 LED。 How to solve this issue?如何解决这个问题?

int button;
void setup() {

 DDRD = B11110000;

 attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
}
void loop() {

  if(button) {

    PORTD = B00010000;
    delay(500);
    PORTD = PORTD <<1;
    delay(500);
    PORTD = PORTD <<1;
    delay(500);
    PORTD = PORTD <<1;
    delay(500);

  }
  else {

    PORTD = B00000000;

  }
}

void buttonPressed() {


  if(button == 0) {
    button = 1;
  }else {
    button = 0;
  }


}

Instead of doing the whole loop you can rewrite the code to check the button state for each LED.您可以重写代码来检查每个 LED 的按钮状态,而不是执行整个循环。 This means that the LED will still always stay lit the full .5 second period.这意味着 LED 仍将在整个 0.5 秒期间始终保持点亮状态。

int button;
void setup() {    
 DDRD = B11110000;    
 attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
}

void loop() {    
  if(button) {
    PORTD = PORTD <<1;
    if (PORTD == 0) {
        PORTD = B00010000;
    }
    delay(500);
  } else {    
    PORTD = B00000000;
  }
}

void buttonPressed() {    
  button = !button;
}

To make the LEDs dark immediately you should not use delay, but rather loop for up to .5 seconds and check the button state;要使 LED 立即变暗,您不应该使用延迟,而是循环最多 0.5 秒并检查按钮状态;

unsigned long timeout = millis() + 500;
while (button && millis() < timeout);

Or a bit more in context或者在上下文中多一点

void loop() {    
  if(button) {
    next_light();
    sleep(500);
  } else {    
    PORTD = B00000000;
  }
}

void next_light() {
  PORTD = PORTD <<1;
  if (PORTD == 0) {
    PORTD = B00010000;
  }
}

void sleep(unsigned long timeout) {
  unsigned long end = millis() + timeout;
  while (button && millis() < end);
}

void buttonPressed() {    
  button = !button;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM