Here's my code that uses millis() function to generate delay:
const int ledPin = 13; // the pin that the LED is attached to
int serialValue=0; // variable to hold your serial data
long interval = 3000; // time in 3seconds
long previousMillis = 0; // will store last time
// setup is executed once
void setup()
{
// initialize serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
// ledPin13 is off first
digitalWrite(ledPin,LOW);
}
// loop is always running
void loop()
{
// if data is received in serial buffer register
if (Serial.available() > 0)
{
// read the data and save to a variable
serialValue = Serial.read();
// parse the data
// if '1' is read
if(serialValue == '1')
{
// activate led on arduino Pin13
digitalWrite(ledPin,HIGH);
// implement 3s delay using timer module
// save time to a variable
unsigned long currentMillis = millis();
// check the time if greater the 3s
if(currentMillis - previousMillis > interval)
{
// update time
previousMillis = currentMillis;
// clear buffer register and data variable
Serial.flush();
// turn off led
serialValue = '0';
}
}
// if '0' is received
if(serialValue == '0')
{
// turn led off on arduino Pin13
digitalWrite(ledPin,LOW);
}
}
}
Heres another code using delay function:
const int ledPin = 13; // the pin that the LED is attached to
int serialValue=0; // variable to hold your serial data
long interval = 3000; // time in 3seconds
long previousMillis = 0; // will store last time
// setup is executed once
void setup()
{
// initialize serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
// ledPin13 is off first
digitalWrite(ledPin,LOW);
}
// loop is always running
void loop()
{
// if data is received in serial buffer register
if (Serial.available() > 0)
{
// read the data and save to a variable
serialValue = Serial.read();
// parse the data
// if '1' is read
if(serialValue == '1')
{
// activate led on arduino Pin13
digitalWrite(ledPin,HIGH);
// implement 3s delay
delay(3000);
// clear buffer register and data variable
Serial.flush();
// turn off led
serialValue = '0';
}
// if '0' is received
if(serialValue == '0')
{
// turn led off on arduino Pin13
digitalWrite(ledPin,LOW);
}
}
}