Timer

Hello…I was creating a ultrasonic hand washing timer with a servo which works. However I need to implement an LCD…and I want it to start the timer and count to 20 when the servo starts moving. Basically, I don’t know how to create a timer that goes: 1,2,3 that lasts exactly 20 seconds. Here is my code so far:

 /*
This is code for LCD1602 Display with I2C module
 * watch the video for this code https://youtu.be/q9YC_GVHy5A
 
 * Permission granted to share this code given that this
 * note is kept with the code.
 * Disclaimer: this code is "AS IS" and for educational purpose only.
 * This library is based on work done by DFROBOT (www.dfrobot.com).
 */
/*
 *  This code has been modefied from the Arduino library
 *  Updated by Ahmad Nejrabi on Jan 20, 2018 at 11:09
 *  in Ajax, Ontario, Canada
 *  for Robojax.com
 *  
 *  This is code for LCD1602 Display with I2C module
 *  which can display text on the screen.
 */
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
  // Robojax code for LCD with I2C
  // initialize the LCD, 
  lcd.begin();
 
  // Turn on the blacklight and print a message.
  lcd.backlight();
  // Robojax code for LCD with I2C


}

void loop()
{
  
  //start of loop Robojax code for LCD with I2C
  lcd.clear();
  lcd.print("");
  lcd.setCursor (0,1); // go to start of 2nd line


//I would like the timer to go here: 

lcd.print("Hello World!");
  
  delay(500);
 //end of loopcode Robojax code for LCD with I2C
}

Example code for a 20 second timer. I don't have an LCD handy but this should be easy enough to modify for an LCD. One thing. Do not use the clear function in loop(). Clear is slow nd can cause flickering. Use the setCursor to position the cursor and overwrite old data with new data and/or spaces.

void setup()
{
   Serial.begin(115200);
}

void loop()
{
  static unsigned long timer = 0;
  unsigned long interval = 1000;
  static int seconds = 0;
  if(millis() - timer >= interval)
  {
    timer = millis();
    seconds++;
    Serial.print("seconds elapsed = ");
    Serial.println(seconds);
    if(seconds == 20)
    {
      Serial.println("activate servo");    
    }
    if(seconds == 30)
    {
      Serial.println("retract servo");
      seconds = 0; 
    }
  }
}

Thank you this worked :slight_smile: