long previousMillis = 0;
long interval = 20000;
unsigned long currentMillis = millis();
if
{
previousMillis = currentMillis;
}
else if (currentMillis - previousMillis >= interval)
{
Serial.println(currentMillis);
previousMillis = currentMillis;
}
else
{
}
I need a way to make it only print the first 20 seconds only not every 20 seconds!! the 20 seconds is from when an event happens in the 1st if statement!
stuwilson:
yes but I want the function to happen when the millis hits 20 seconds not every time it finds the millis equal to or more than 20 seconds (>=)
const int ledPin = 13; // the number of the LED pin
int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0; // will store last time LED was updated
const unsigned long interval = 20*1000UL; // interval at which to blink (milliseconds)
boolean flag = true; // if true, continue to run
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
//Run MyBlink 20 seconds from now
previousMillis = millis();
}
void loop()
{
unsigned long currentMillis = millis();
if((currentMillis - previousMillis >= interval) && flag == true) {
//uncommented the next line if you what things to restart
//previousMillis = currentMillis;
//comment the next line if you want this to happen more than once
flag = false;
MyBlink();
}
}
void MyBlink()
{
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
{
ledState = HIGH;
}
else
{
ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
You can set the start time to 0 to indicate that the timer should not be checked:
// Every 10 minutes turn on the LED and turn it off 20 seconds later
// constants won't change. Used here to set a pin number :
const int ledPin = 13; // the number of the LED pin
// Generally, you should use "unsigned long" for variables that hold time
unsigned long repeatStart = 0; // Timer start for repeating
unsigned long delayStart = 0; // Timer start for delay
// constants won't change :
const unsigned long repeatInterval = 600000UL; // ten minutes
const unsigned long delayInterval = 20000UL; // 20 seconds
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - repeatStart >= repeatInterval) {
// Turn LED on
digitalWrite(ledPin, HIGH);
// re-set the repeatStart to make it repeat
repeatStart = currentMillis;
// Start delay interval for delayed turn-off
delayStart = currentMillis;
}
// If the delay timer is running, check for the end of delay
if (delayStart != 0 &&
currentMillis - delayStart >= delayInterval) {
// Turn LED off
digitalWrite(ledPin, LOW);
// Done with delay for now
delayStart = 0;
}
}