I am trying to blink an led without using delay function for 1 second on, 2 seconds off periodically. Instead, to use millis () function. However, I could not code using the millis () function successfully. Can someone kindly help me to code using the millis () function, please? Thanks for your time.
You need to do something like this. (untested, typed on the fly)
You have two states.
waitingOff // ItsOff and I'm waiting 'till its time to turn it on.
waitingOn. // ItsOn and I'm waiting 'till its time to turn it off.
changeTime. // The value in miliseconds when I need to change the LED.
So, come into the loop function and..
Look at the clock. millis();
if(millis()>changeTime) { //Then its time to change the LED ain't it. so..
if(state==waitingOff) {. // See above..
turnOnLED();
recalculate changetime
state = waitingOn; // its on now, so were going to wait to turn it off.
} else {
turnOffLED();
recalculate changetime
state = waitingOff;
}
}
// then do other things..
The demo Several Things at a Time is an extended example of BWoD and illustrates the use of millis() to manage timing. It may help with understanding the technique.
I tried using the Arduino example "BlinkWithoutDelay" to create pulses. I was able to produce correct pulses for millis () function but with the similar method, I was unable to create correct pulses for micros () function. Did I code correctly. Please help me. Thanks.
Below is the code for millis () function:
const int ledPin = 13;
int ledState = 1;
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis1 >= 1000) //Pulse width
{
previousMillis1 = currentMillis;
if (ledState == 0)
{
ledState = 1;
digitalWrite(ledPin, HIGH);
}
else
{
ledState = 0;
}
}
if(currentMillis - previousMillis2 >= 3000) //Period
{
previousMillis2 = currentMillis;
if (ledState == 0)
{
ledState = 1;
digitalWrite(ledPin, LOW);
}
else
{
ledState = 0;
}
}
}
//led blinks on for 1 second, off for 2 second, continously
I think you need to check a flag in your elapsed time check to see which length is running, something ljke this.
You had a similar method, but not correct.
void loop()
{
currentMicros = micros(); // declare as unsigned long before setup()
if((currentMicros - previousMicros1 >= 1400) && (pulseLength == shorter)) //Pulse width
{
previousMicros2 = currentMicros; // capture start time of long pulse
pulseLength = longer; // change "mode"
digitalWrite (ledPin, LOW); // turn off
}
if((currentMicros - previousMicros2 >= 13600)) && (pulseLength == longer)) //Period
{
previousMicros1 = currentMicros; // capture start time of short pulse
pulseLength = shorter; // change "mode"
digitalWrite (ledPin, HIGH); // turn on
}
}