Search Code

Arduino millis() Function Explained with 3 Examples

Arduino millis() Function Explained with 3 Examples

This code example has been explained in a video. Please watch the video and use this code.
216-Example 1 of using millis() in Arduino programming
Language: C++
/*
 * Example 1 of using millis() with Arduino
 * Written by Ahmad Shamshiri on July 27, 2019
 * in Ajax, Ontario, Canada
 * Watch video instructions for millis():
 */

unsigned long event = 5000;// 5 seconds
void setup() {
  Serial.begin(9600);//initialize serial monitor
  Serial.println("Introduction to millis");
  pinMode(2,INPUT_PULLUP);
 
}

void loop() {
  // Robojax.com millis() example 1
  Serial.println(millis());
  int pb = digitalRead(2);// read pin 2
  if(pb ==LOW)
  {
      if(millis() >= event)
      {
        Serial.println("Take action");
      }// if end
  }// if end
  
}// loop end
217-Example 2 of using millis() in Arduino programming
Language: C++
/*
 * Example 2 of using millis() with Arduino
 * Written by Ahmad Shamshiri on July 27, 2019
 * in Ajax, Ontario, Canada
 * Watch video instructions for millis():
 */

unsigned long event = 5000;// 5 seconds
unsigned long buttonPushed =0;

void setup() {
  Serial.begin(9600);//initialize serial monitor
  Serial.println("Introduction to millis");
  pinMode(2,INPUT_PULLUP);
  


}

void loop() {
  // Robojax.com example 2 millis()
  Serial.println(millis());
  int pb = digitalRead(2);// read pin 2
  if(pb ==LOW && buttonPushed ==0)
  {
    buttonPushed =millis();
    Serial.print("First push at:");
    Serial.println(buttonPushed);
  }
  if( pb ==LOW &&  buttonPushed >0 )
  {
   unsigned long difference = millis()- buttonPushed;
      if( difference >= event)
      {
        Serial.println("Action after 5 seconds of first push");
      }
  }
  
}

Resources & references

Files📁

No files available.