Fade leds with serial communication Arduino

287 Views Asked by At

I am getting serial communication and trying to make an led fade effect , This is my function for leds which is facing latency issues , obviously the for loop . Can anyone suggest a better logic or solution to approach this without getting latency in leds?

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();
}
1

There are 1 best solutions below

1
Kerbolosh On

You need to write non-blocking code as Scheff mentioned. Instead of a global variable, you can use a static variable in a function. It remembers its value for each call of that function.

Here is an example how you could do it, using millis(). My code fades an LED on and off if some serialEvent happens and it does not block the rest of the code:

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;
  }
 
}