Skip to main content
Arduino

Return to Revisions

2 of 2
Removed useless variable, fiwed RTC frequency.
Edgar Bonet
  • 45.1k
  • 4
  • 42
  • 81

As I said in my comment, the idea of using the Arduino's own PWM as a clock source is completely misguided. It will be no more accurate than using millis() or micros(): both these functions and the PWM rely on the same primary clock source, namely the ceramic resonator clocking the chip.

Also, you should avoid using delay() for timekeeping. The time it takes to run around the loop() is the sum of all your delays plus the time needed to execute the actual instructions, which you do not know accurately. It is far better to use either millis() or micros().

Here is a tentative sidereal clock code, not tested:

// Pins driving the clock.
const int a1 = 8;
const int a2 = 9;
// Length of one sidereal second in microseconds.
const unsigned long SIDEREAL_SECOND = 997270;
void setup()
{
 pinMode(a1, OUTPUT);
 pinMode(a2, OUTPUT);
}
void tick()
{
 static int activePin = a1;
 // Pulse the pin.
 digitalWrite(activePin, HIGH);
 delay(50);
 digitalWrite(activePin, LOW);
 // Next time use the other pin.
 if (activePin == a1) activePin = a2;
 else activePin = a1;
}
void loop()
{
 static unsigned long last_tick;
 if (micros() - last_tick >= SIDEREAL_SECOND) {
 tick();
 last_tick += SIDEREAL_SECOND;
 }
}

You can tune the speed of the clock by changing the constant SIDEREAL_SECOND. I set the constant to the actual length of a sidereal second, in microseconds, but you may find that the clock does not run exactly at the correct speed. This is because the ceramic resonator inside the Arduino is not very accurate. You can remove most of the inaccuracy by calibration: measure how fast or slow it runs and change the value of SIDEREAL_SECOND to compensate. You will still face some residual inaccuracy owing to the fact that the resonator's frequency is not very stable, and is highly temperature-dependent.

If you want to build a clock that has decent accuracy, your best bet is to use a 32768 Hz quartz crystal, as suggested by Ignacio Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a "barebones Arduino") to make a 24-hour analog wall clock. You should be able to easily adapt the code I published in that page to fit your project.

Edgar Bonet
  • 45.1k
  • 4
  • 42
  • 81

AltStyle によって変換されたページ (->オリジナル) /