2

I need to blink a LED for only 100 millisecond and the delay function in the loop make my code very unresponsive.

if (readString.indexOf("?23") >0){
  digitalWrite(23, LOW);
  delay(100);
  digitalWrite(23, HIGH);
}

Is there a simple way to replace delay with millis to blink only once? I have tried this, but doesn't work

unsigned long interval1=1000;    // the time we need to wait
unsigned long previousMillis1=0; // millis() returns an unsigned long.

if (readString.indexOf("?22") >0){
  if ((unsigned long)(millis() - previousMillis1) >= interval1) {
    previousMillis1 = millis();
    digitalWrite(22, LOW);
  }
  digitalWrite(22, HIGH);

Can you guys help me? I cannot figure it out.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
RobCon
  • 75
  • 1
  • 1
  • 7

1 Answers1

1

I assume, that you are trying to turn on the LED for 100ms, when the string variable readString contains the defined literal string, and turning it of after it.

I think you are missing an else in your code, because without it the digitalWrite(22, LOW) to turn off the LED will be directly followed by the digitalWrite(22, HIGH), which will turn the LED on again. And with executing previousMillis1 = millis() you let the LED blink continuously, not only once. Try something like this:

unsigned long interval1=100;    // the time we need to wait
unsigned long previousMillis1=0; // millis() returns an unsigned long.
boolean led_blinking = false;

void loop(){
    if (readString.indexOf("?22") >0 && !led_blinking){
        led_blinking = true;
        previousMillis1 = millis();
    }
    if (led_blinking && millis() - previousMillis1 <= interval1) {
        digitalWrite(22, HIGH);
    } else {
        digitalWrite(22, LOW);
        led_blinking = false;
        readString = ""; /* resetting the string variable to prevent
                            further blinking, until the variable is set
                            by another part of the code */
    }

    // Do other task of the main loop
}

Note that, depending on the time it takes to execute the rest of your main loop, the timing here is not exact. But if you only want to have a visual sign of your condition, this will be sufficient. If you don't want to reset the string variable, you can use another boolean variable, which you can set at the time, when the string variable is set. But don't forget resetting it instead of the string variable.

chrisl
  • 393
  • 3
  • 16