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:When 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 }
Leave a Reply