0

我正在进行串行通信并尝试制作LED淡入淡出效果,这是我的 LED 功能,它面临延迟问题,显然是for 循环。任何人都可以提出更好的逻辑或解决方案来解决这个问题而不会导致 LED延迟吗?

void loop() {
    // serial communication
    while(Serial.available() > 0 ){
        int inByte = Serial.read();
        Serial.print(inByte);
        if (inByte > 0) {
            // if byte is 255, then the next 3 bytes will be new rgb value
            if (inByte == 255) {
                setColors = true;
                colorSetCounter = 0;
            } else if (setColors) {
                switch (colorSetCounter) {
                    case 0:
                        redVal = inByte;
                        break;
                    case 1:
                        greenVal = inByte;
                        break;
                    case 2:
                        blueVal = inByte;
                        setColors = false;
                        receiveNotes = true;
                        fill_solid(leds, NUM_LEDS, CRGB::Black);
                        FastLED.show();
                        break;
                }
                colorSetCounter++;
            } else if (receiveNotes) {
                     

                controlLeds(inByte);
                       

            }
        }
    }
}

void controlLeds (int note) {
    note -= 1;
    if (!leds[note]) {
        leds[note].red = redVal;
        leds[note].green = greenVal;
        leds[note].blue = blueVal;      
    } 

    else {
   for(int i =0; i<=255; i++){       
       leds[note].fadeToBlackBy(i);
       FastLED.show();
       if(!leds[note]){
        break;       
       }
   }       
      }
   FastLED.show();
}
4

1 回答 1

2

您需要编写 Scheff 提到的非阻塞代码。static您可以在函数中使用变量来代替全局变量。它会记住每次调用该函数的值。

这是一个示例,您可以使用millis(). 如果发生某些 serialEvent 并且它不会阻止其余代码,我的代码会打开和关闭 LED:

const int ledPin = 13;
int setValue = 0;
unsigned long lastTime = 0;
const unsigned long refreshTime = 200;
char buffer1[8];

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (millis() - lastTime > refreshTime)
  {
    lastTime = millis();
    fadeLED(setValue);
  }
}

void fadeLED(int fadeValue)
{
  static int currentValue = 0;
  if (fadeValue > currentValue) {
    currentValue++;
  }
  if (fadeValue < currentValue) {
    currentValue--;
  }
  analogWrite(ledPin, currentValue);

}
void serialEvent()
{ Serial.readBytesUntil('\n', buffer1, 8);
  switch (setValue)
  {
    case 0:
      setValue = 255;
      break;
    case 255:
      setValue = 0;
      break;
    default:
      break;
  }
 
}
于 2021-05-04T08:06:26.347 回答