Author Options:

How to get an ATtiny to run an accurate clock? Answered

I'm making a clock with an ATtiny and I would like to know how to make it tell accurate time. I'm already pretty sure it would require an external crystal or resonator, but I just don't know the frequency or if there are any code requirements. I'll be programming the chip with an Arduino, if that helps with code.



The forums are retiring in 2021 and are now closed for new topics and comments.

Best Answer 8 years ago

Put an 8Mhz crystal on the chip (the circuit's in the datasheets for the arduino) The code requirements for a hardware RTC means that you need to use interrupt triggered timers to implement the control, or you will probably find the clock gains or loses a little. The BEST way to do it is to add an RTC, crystal, and battery backup to the thing.


6 years ago

The ATtiny is an excellent time generator. The chip will run on an internal oscillator and does not need an external crystal. The internal oscillator with run at up to 8 Megahertz. It will also generate an 64 Megahertz internal clock with an internal phase locked loop (PLL) that can be used by the internal timers. The 8 Mhz system clock can be adjusted for accuracy by an oscillator calibration register (OSCCAL). Adjusting the frequency of the of the internal oscillator with OSCCAL will also adjust the PLL 64 Mhz frequency. OSCCAL settings can change the internal clock frequency by + or - more than 1 Mhz. Read Atmel's data sheet on the ATtiny for the details. The timers and registers to control the clock can all be programmed directly with the Arduino IDE.

Below is a sample sketch for an ATtiny85 as a baud rate generator to give an idea of programming the clock and timer settings.

// Attiny85 , running @ 8MHZ

// output of 153600 Khz = 9600 baud * 16

// Square wave output on pin 5 (PB0)


void setup()


// OSCCAL calibrates 8 mhz internal timer speed

// value of 96 was used to get output of 153600 Khz at

// pin 5 on an osciilscope for this particular project

OSCCAL = 96; // higher value = faster (see Figure 22-42 in data sheet)

CLKPR = 0x80; // set system clock to 8mhz with no prescale

CLKPR = 0x00; // these 2 CLKPR instructions have to be run together in order

// to set clock to 8 Mhz

DDRB |= (1<<PB0); //Set pin PB0 as output (pinMode(0, OUTPUT)

TCNT0 = 0; // initialize timer counter value to 0

TCCR0A = 0; // write 0 to timer 0 control registers

TCCR0B = 0;

TCCR0A |= (1 << COM0A0); //Timer0 in toggle mode (Table 11-2 of datasheet)

TCCR0A |= (1 << WGM01); //Start timer 1 in CTC mode (Table 11-5 )

TCCR0B |= (1 << CS00); // Prescaler table 11.6

OCR0A=27; //CTC Compare value (27 gives 153 khz)


void loop(){



8 years ago

Some of the Atmel microcontrollers have a built in RTC (real time counter) and all you need is an external crystal to make a clock. Many of the ATmega's have this feature. Few, or none, of the ATtiny's have this feature.