Step 6Programming the Arduino
I am not going to go over how to program an Arduino, there are plenty of example online. I used the motor knob example in the Arduino IDE as the basis for driving the stepper motors. From there I modified the code to drive the stepper motors.
When programming a clock, you obviously want your clock to run and not loose time. My first hack at the code, my clock lost about 15 minutes overnight. That was not acceptable. The algorithm for that code was to count to 60 seconds, tick the minute hand, then count to 5 minutes and tick the hour hand. Not the most elegant of solutions.
So what i did next was to use a date/time library and keep track of the last minute, then I would check the time every 5 seconds or so and if the minute changes then I would tick the clock. Every 5 minutes, I will tick the hour hand. I also set the pin13 led to flash every second. You will have to install the time library to run the pde code. It is downloaded here http://www.arduino.cc/playground/Code/Time
Code (cut and paste) or download the PDE below:
/*
* gearclock.pde
*
* Brian Wagner
* LVL1 - Louisville's Hackerspace
* www.lvl1.org
* 9/10/11
* 9/18/11 reworked to use time_t
*/
#include <Stepper.h>
#include <Time.h>
#define STEPS 20 // The stepper has 20 steps per revolution
int ledPin = 13; // LED connected to digital pin 13
int LastMinute;
int ThisMinute;
int LastSecond;
int ThisSecond;
//for the 21-02485-03 stepper, the colors in order are yellow, red, black/white, blue
Stepper Hours(STEPS, 4, 5, 6, 7);
Stepper Minutes(STEPS, 8, 9, 10, 11);
int MinuteCount;
time_t t;
void setup()
{
pinMode(ledPin, OUTPUT);
setTime(1,1,1,1,1,1); //set the time to Jan 1, 2001
//It really does not matter what the time is set to,
//we are checking to see if a minute has passed.
t = now();
LastMinute = minute(t);
LastSecond = second(t);
//how fast is it gonna step
Minutes.setSpeed(5);
Hours.setSpeed(5);
//test the minutes and hours to make sur it is going in the correct direction
//Minutes.step(100);
//Hours.step(100);
Minutes.step(4);
Hours.step(4);
MinuteCount = 1;
}
void loop()
{
t = now();
ThisMinute = minute(t);
ThisSecond = second(t);
if ( ThisSecond != LastSecond ) {
digitalWrite(ledPin, HIGH); // set the LED on
delay(200); // wait for 500ms
digitalWrite(ledPin, LOW); // set the LED off
LastSecond = ThisSecond;
}
if ( ThisMinute != LastMinute ) {
Minutes.step(2);
MinuteCount++;
LastMinute = ThisMinute;
}
//tick the hour ring every 5 minutes
if (MinuteCount > 5) {
Hours.step(2);
MinuteCount = 1;
}
delay(200);
}
GearClock.pde1 KB| « Previous Step | Download PDFView All Steps | Next Step » |
![]() |
Add Comment
|














































