Search code examples
c++arduinomicrocontrollerarduino-unoarduino-ide

I want to get an LED to blink using the millis() function but my LED stays constantly on, what's wrong with my code?


I know there are other ways but I'd like to know what's wrong with my code and why it doesn't work. Pin 2 seems to constantly stay 'HIGH' despite the 'else if' statement.

const int led = 2;

int ledState = digitalRead(led);

const unsigned long interval = 1000;
unsigned long previousTime = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(led,OUTPUT);
}

void loop()
{
  unsigned long current = millis();

  if((current - previousTime >= interval) && (ledState == LOW))
  {
    digitalWrite(led,HIGH);
    previousTime = current;
  }
  else if((current - previousTime >= interval) && (ledState == HIGH))
  {
    digitalWrite(led,LOW);
    previousTime = current;
  }
}


Solution

  • The first comment said you did not update ledState. This is the problem. I believe a better solution to that is the following:

    const int led = 2;
    
    const unsigned long interval = 1000;
    unsigned long previousTime = 0;
    
    void setup()
    {
      Serial.begin(9600);
      pinMode(led,OUTPUT);
    }
    
    void loop()
    {
      unsigned long current = millis();
    
      if(current - previousTime >= interval)
      {
        digitalWrite(led,!digitalRead(led));
        previousTime = current;
      }
    }
    

    This reads the current led state and inverts it with !digitalRead(led) without the need of an if () else {}