LED delay on Serial port issue

Hi. I have a delay() issue.
By this code, I want to have red light only 5 seconds and then change to green light.
But if I try this, the delay of the red light comes out like 10 seconds and 20 seconds long.
If I have delay less than 1 second, then it works well. But over 5 seconds, the light changes so late.
If you help me solve this problem I would sincerely appreciate it.
Thank you.

int RED = 6;
int GREEN = 7;
int BLUE = 8;

void setup(){                 
  Serial.begin(9600);
  pinMode(RED,OUTPUT);
  pinMode(GREEN,OUTPUT);
  pinMode(BLUE,OUTPUT);
  }

void loop(){
  while(Serial.available()>0){ 
    char ser=Serial.read();
     switch(ser){
      case '0':
        setColor(255,0,0);
        delay(5000);
        break;
        case'1':
        setColor(0,255,0);
        delay(5000);
        break;
      }
   }
}

void setColor(int red, int green, int blue)
{
  analogWrite(RED, red);
  analogWrite(GREEN, green);
  analogWrite(BLUE, blue);
}

Your post was MOVED to its current location as it is more suitable.

if you are on a UNO, pin 7 and 8 are not PWM capable (would be fine on a MEGA)

of course while you are stuck in the delay the Serial line is not monitored and could overflow the small buffer if on the other side you are bombarding it with requests. how are you sending the data in?

I'm using google teachable machine and p5js. The webcam sends '0' or '1' value to the arduino in real time.

at what rate ? data sent during the 5s pause is ignored and dealt with only after the delay is finished.
The buffer for incoming data is 64 bytes deep and you can get up to ~1000 '1' or '0' per second at the baud rate you selected.

What does "Real time" mean? How often does the webcam send a 0 or a 1? It is almost always better not to use delay for timing. Check out the following tutorial:

BlinkWithoutDelay

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.