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.