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. 

#include 
Servo servo1; 
int ledPin = 13;

void setup() {
  servo1.attach(14);
  servo1.setMaximumPulse(2500);
  Serial.begin(19200);
  Serial.print("Ready");
}
void loop() {
  static int v = 0;
  if ( Serial.available()) {
    char ch = Serial.read();
    switch(ch) {
      case '0'...'9':
        v = v * 10 + ch - '0';
        break;
      case 's':
        servo1.write(v);
        v = 0;
        break;
        
      case 'w':
      blink();
      v = 0;
      
      
    }
  } 

 Servo::refresh();
}

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
    }
Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: