About using of millis()

Hi, i have a question for millis(). I need to blink a light few time with milils, but i am not sure aout the code.

const int ledPin = LED_BUILTIN;  // the number of the LED pin


int ledState = LOW; 


const long interval = 500;  

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  

  /
  unsigned long currentMillis = millis();
 for(p=0;p>3;p++){
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }}
    digitalWrite(ledPin, ledState);
  }
}

consider

const int ledPin = LED_BUILTIN;  // the number of the LED pin

int ledState = LOW;

const long interval = 500;
unsigned long previousMillis;

void setup() {
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        ledState = ! ledState;
        digitalWrite(ledPin, ledState);
    }
}

Don't use a for loop, let loop() do the looping for you

const int ledPin = LED_BUILTIN;  // the number of the LED pin

int ledState = LOW;
const long interval = 500;
byte counter = 0;
unsigned long previousMillis;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (counter < 6)
  {
    if (currentMillis - previousMillis >= interval)
    {
      digitalWrite(ledPin, !digitalRead(ledPin));
      previousMillis = currentMillis;
      counter++;
    }
  }
}
1 Like

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