0

我正在尝试通过不使用 delay() 函数而不是使用 millis() 函数来创建计数器来调整此版本的 Adafruit NeoPixel 剧院追逐示例以实现非阻塞,但是,我没有运气NeoPixels 只是不断点亮。我错过了什么吗?我决定将 if 语句放置在嵌套 for 循环关闭链中每个第 3 个像素的位置,认为这将是放置它的位置,因为在旧代码中,在此步骤之前调用了 delay()。

这是我制作的这个版本,它不起作用:

//Theatre-style crawling lights.
void theaterChase(uint32_t c, const long wait) {
  unsigned long currentMillis = millis();
  for (int j = 0; j < 10; j++) { //do 10 cycles of chasing
    for (int q = 0; q < 3; q++) {
      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
        strip.setPixelColor(i + q, c);  //turn every third pixel on
      }
      strip.show();
      if (currentMillis - previousMillis >= wait) {
        previousMillis = currentMillis;
        for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
          strip.setPixelColor(i + q, 0);      //turn every third pixel off
        }
      }
    }
  }
}

这是旧版本:

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}
4

1 回答 1

0

包裹在延迟周围的 for 循环是阻塞的。

您必须将包裹在 delay() 周围的嵌套 for 循环分解为它们的组成部分。

  1. 你可以把for(j...){}循环变成if( currentMillis -last > wait){}条件循环,依靠外层loop()来频繁调用这个函数。
  2. q使用静态保存状态并自己进行迭代算术

未经测试的代码:

//Theatre-style crawling lights.
void theaterChase(uint32_t c, const long wait) {
  static unsigned long last;
  static int q;
  unsigned long currentMillis = millis();
  if( currentMillis -last > wait){
    last = currentMillis;
    if(q >= 3) q = 0;
    if(q < 3){
      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
        strip.setPixelColor(i + q, c);  //turn every third pixel on
      }
      strip.show();
      // setup to turn them back off during the next iteration
      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
          strip.setPixelColor(i + q, 0);      //turn every third pixel off
      }
      q++;
    }// if(q ...
  } // if( currentMillis... 
}
于 2022-03-03T17:40:37.063 回答