title: Arduino countdown within delay loop
body: <p>What a great learning experience my first Arduino project is turning out to be.. I would now like to add a countdown until a sensor reading is taken and displayed, which will repeat infinitely. I've got the sensor and LCD display working fine but my loop is not quite right.. Should I be using a while() of some sort? How do I keep the timer ticking during the big delay between readings?</p>
  
  <pre><code>/*Code for self-watering plant with LCD readout*/
  // value for LCD params
  char ESC = 0xFE;
  // analog input pin that the soil moisture sensor is attached to
  const int analogInPin = A1;  
  // value read from the soil moisture sensor
  int sensorValue = 0;
  // if the readings from the soil sensor drop below this number, then turn on the pump
  int dryValue;  
  // countdown timer until next soil reading
  int timerValue = 9; 
  
  void setup() {
    pinMode(12, OUTPUT); 
    // initialize serial communications at 9600 bps:
    Serial.begin(9600); 
    // Set the "dry" value of soil on turning on the device
    dryValue = analogRead(analogInPin); 
    // pause before intialize LCD
    delay(2000);
    // Initialize LCD module
    Serial.write(ESC);
    Serial.write(0x41);
    Serial.write(ESC);
    Serial.write(0x51);
    // Set Contrast
    Serial.write(ESC);
    Serial.write(0x52);
    Serial.write(40);
    // Set Backlight
    Serial.write(ESC);
    Serial.write(0x53);
    Serial.write(5);
  
    //print the dry value to serial
    Serial.print("Dry = " ); 
    Serial.print(dryValue);
    Serial.print("   ");
  }
  
  void loop(){
    watering();
    // wait some time (really should be delay(86400000))
    delay(10000);                
  }
  
  void printTimer(){  
    // Set cursor line 1, column 16
    Serial.write(ESC);
    Serial.write(0x45);
    Serial.write(0x0F);
    // print the timer value
    Serial.print(timerValue);
    timerValue = timerValue - 1;
    if(timerValue == 0){
    timerValue = 9;
    }
  }
  
  void printVal(){
    // set cursor line 2, column 1
    Serial.write(ESC);
    Serial.write(0x45); 
    Serial.write(0x40);  
    // print the sensor to the serial monitor:
    Serial.print("Sensor = " );                       
    Serial.print(sensorValue);
    Serial.print("   ");
    printTimer();
    } 
  
  void watering(){
    // read the analog in value:
    sensorValue = analogRead(analogInPin);                   
    //turn on the water pump for some time if the soil is too dry
    if(sensorValue &lt; dryValue){
      digitalWrite(12, HIGH);
      delay(2000);
      digitalWrite(12, LOW);
    }
    else {
    printVal();
    }
  }
  </code></pre>