help for digitalWrite with millis()

i was trying a simple way to blink a led using the millis()

the code should do:

read an push button and if is pressed:

turn on a led

wait a time

turn off the led

after run the sketch the led is off when i press the button the led turn on but he never turn off even after the chose time is gone

sorry about my english

sketch_mar09c.ino (467 Bytes)

I'd love to be able to help you, but I can't see your code.

sorry about that

#define ledPin   13


bool ledState = LOW;             


unsigned long previousMillis = 0;        


const long interval = 1000;           

void setup() {

  pinMode(2,INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {

  if(!digitalRead(2))
  {
    digitalWrite(ledPin,HIGH);
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    
    previousMillis = currentMillis;


    digitalWrite(ledPin,LOW);
  }
 }
}

This check:

    if (currentMillis - previousMillis >= interval)

Is controlled by the if that looks for a button press. i.e. you only check to see if it's time to turn the LED off when the button is pressed.

read an push button and if is pressed:

This may be tricky as I would guess that you are not a native English speaker

Do you want the LED to turn on and off [u]while[/u] the button is pressed and held down, or do you want it to turn on and off when the button [u]becomes[/u] pressed and for it to continue even when the button is released ?

UKHeliBob: This may be tricky as I would guess that you are not a native English speaker

Do you want the LED to turn on and off [u]while[/u] the button is pressed and held down, or do you want it to turn on and off when the button [u]becomes[/u] pressed and for it to continue even when the button is released ?

yes, after a simple click without hold the button the code should continue even when the button is released,the button is just a trigger.

Take a close look at how your conditional statements are grouped.

after a simple click without hold the button the code should continue even when the button is released,the button is just a trigger.

Have a look at the StateChangeDetection example in the IDE to see how to do it.

i test the code without de button but dont work, it should just blink a led

#define ledPin   13


bool ledState = LOW;             


unsigned long previousMillis = 0;        
unsigned long anterior = 0;

const long intervalo = 1000;
const long interval = 1000;           

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

void loop() {

    
    unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    
    previousMillis = currentMillis;


    digitalWrite(ledPin,LOW);
  }
  if(currentMillis - anterior >= intervalo)
  {
    anterior = millis();
    digitalWrite(ledPin,HIGH);
  }


}

What does it do ? What do you see if you put some Serial.print()s in the code so that you know what is going on ?