Skip to Content
Arduino Cookbook, 3rd Edition
book

Arduino Cookbook, 3rd Edition

by Michael Margolis, Brian Jepson, Nicholas Robert Weldin
April 2020
Intermediate to advanced
795 pages
17h 43m
English
O'Reilly Media, Inc.
Book available
Content preview from Arduino Cookbook, 3rd Edition

Using Time and Dates

12.0 Introduction

Managing time is a fundamental element of interactive computing. This chapter covers built-in Arduino functions and introduces many additional techniques for handling time delays, time measurement, and real-world times and dates. You’ll learn about Arduino’s built-in function for introducing delays into your sketch, as well as more advanced techniques for intermittently performing operations. Other recipes in this chapter cover how to measure time as it passes, and even how to use an external real-time clock for tracking time and dates.

12.1 Using millis to Determine Duration

Problem

You want to know how much time has elapsed since an event happened; for example, how long a switch has been held down.

Solution

The following sketch uses the millis() function to print how long a button was pressed (see Recipe 5.2 for details on how to connect the switch):

/*
  millisDuration sketch
  returns the number of milliseconds that a button has been pressed
 */

const int switchPin = 2;  // the number of the input pin

unsigned long startTime; // the value of millis when the switch is pressed
unsigned long duration;  // variable to store the duration

void setup()
{
  pinMode(switchPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop()
{
  if(digitalRead(switchPin) == LOW)
  {
    // here if the switch is pressed
    startTime = millis();
    while(digitalRead(switchPin) == LOW)
      ; // wait while the switch is still pressed
    unsigned long duration = millis() - startTime
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Arduino for Arduinians

Arduino for Arduinians

John Boxall
Getting Started With Arduino, 4th Edition

Getting Started With Arduino, 4th Edition

Massimo Banzi, Michael Shiloh

Publisher Resources

ISBN: 9781491903513Errata PageSupplemental Content