Making Things Interactive

February 5, 2008

Arduino Event Timer

Filed under: 4: Counting Sensor Input,Joshua Smith — jssmith44 @ 1:41 pm

I wanted to write a program that would allow the Arduino to calculate the duration of an event. For instance, to be able to display how long a window has been open, or how long your dog has been lying on her pillow bed when you come home, etc. The following code is based on a simple switch with the following circuit diagram:Switch Circuit DiagramWhen the switch is put in the closed position, the Arduino begins counting seconds until the switch is opened. The seconds are then converted to “hours:minutes:seconds” format and passed back and displayed on the terminal using my displayDuration() function. Once the switch is opened, the timer is reset and can begin all over again.For the code to work correctly, I had to calibrate the program to my computer. To do this I had to calculate how many milliseconds it took my computer to process each iteration of the main loop and then set the “offSet” variable equal to that. This was mainly a trial and error process, initiating the switch at the same time as a real stopwatch and making adjustments so they matched up. 

Servo servo1; 
int ledPin = 13;

void setup() {
void loop() {
  static int v = 0;
  if ( Serial.available()) {
    char ch =;
    switch(ch) {
      case '0'...'9':
        v = v * 10 + ch - '0';
      case 's':
        v = 0;
      case 'w':
      v = 0;


void blink(){
  digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(100);                  // waits for .1 second
      digitalWrite(ledPin, LOW);    // sets the LED off
      delay(100);                  // waits for .1 second

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: