doubt regarding Millis

int value = 0;
long previousMillis = 0;

long interval = 3000; //delay

void setup()
{
Serial.begin(9600);

}

void loop()
{

unsigned long currentMillis = millis();

if( currentMillis - previousMillis > interval)
{
if(Serial.available())
{
value = Serial.read();
}
Serial.flush();
previousMillis = currentMillis;
}
}

I'm trying to receive a character only after 3 seconds, if any character comes before 3 seconds it should be discarded.

Is this program correct for what I intend??

Try reading the documentation for the serial.flush() method. AND make sure it's the version on the site.

Mark

I think your code will do what you want. But you don't need Serial.flush(). It is badly named and it is only relevant (and then not much) when the Arduino is sending data.

...R

@robin2 - I think the op wants to throw away all input before the 3 seconds, hence the flush. The old spec (only on the arduino) was to clear the input buffer.

Mark

holmes4:
@robin2 - I think the op wants to throw away all input before the 3 seconds, hence the flush. The old spec (only on the arduino) was to clear the input buffer.

Mark

Looking at his code, the flush statement is inside the if (3 seconds elapsed) loop. How will it flush anything before 3 seconds has elapsed?

holmes4:
@robin2 - I think the op wants to throw away all input before the 3 seconds, hence the flush.

That's as may be. But the reality is that Serial.flush() does not do that nowadays. And there is no new equivalent for what it used to do.

...R

Untested but uses less variables.

unsigned long interval = 3000; //delay

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  unsigned long currentMillis = millis(); // Get current time
  
  while ((millis() - currentMillis) < interval) // Has interval expired?
  {
    while (Serial.available() > 0)  // Any serial data arrived?
    {
      byte value = Serial.read(); // read and discard it
    }
  }
  // Interval is up so next serial read is wanted
}

This:
Serial.read();

uses even less variables than this:
byte value = Serial.read();

You could try this:

char value = 0;

void setup()
{
  Serial.begin(9600);

}

boolean ready = false;
void loop()
{
  if (!ready){
    //first 3 seconds  
    if( millis() > 3000)
    {
      ready = true; //3 seconds has passed.
    } 
    else if(Serial.available())
    {
      Serial.read(); //clear any characters arriving early.
    }
  } 
  else {
    //After 3 seconds:
    if(Serial.available())
    {
      value = Serial.read();
    }


  }
}