Ajantha College and School Students Science Projects materials The Great in project

"In the name of Allah, most
Gracious, most Compassionate"


044 4213 1795


+91 91764 16648   +91 9042 686793

How to Work With 32K crystal and AVR Microcontroller


Timing-is one of the basic function, performed by the micro controllers. Every microcontroller has at least one timer/counter module in its architecture. However if the counter is clocked internally a few issues may arise in some cases. Sometimes the clock frequency may not stable, or sometimes the clock frequency may be too high than necessary. Sometimes external clock is required to have the required quality. To solve these problems, some AVR micro controllers comes up with an inbuilt oscillator supporting 32.768KHz crystal. User just need to attach the tank circuit along with the 32K Crystal.

For a demonstration of this, we would try to blink an LED. We will use the output of the timer. Microcontroller used here is ATmega8. The component list is as below:









Push Button switch


32768Hz Crystal


33pF Ceramic capacitor


Extra: Programmer, Bread board, 5V Power Supply

 Now, we have one Input Capture register, and we can obtain an electrical output in the OC2 Pin (PORTB, Pin 3). And we must keep the following points in mind while programming:

  • Human Eye can sense any periodic activity with at least 100mS of period. TCNT2 Pre-scalar can scale down the clock frequency to ATMOST 1024th PART, Pulse Width Modulation (PWM) modes will divide the frequency to 256th part. This can give a period of AT MOST 8 Second (1024*256/32768). In this demonstration, we are pre-scaling the clock to 1024th Part.
  • We can use a NON Pulse width Modulation mode like CTC mode to blink the LED too. In this demo, we are using CTC mode.
  • The DDRXn bit (Data Direction Register ‘X’, Bit ‘n’) must be ‘1’, to which, the OC2 ( Output Compare of Timer/Counter 2) is connected. In case of ATmega8, it is pin no 17 of the IC. Corresponding Data Direction Register is DDRB, and pin no is 3.

So let us make circuit and Write the program.


Adding external clock source/32K crystal to Avr Atmega8


Fig: Circuit Diagram

// Program written for ATmega8
#define F_CPU 1000000

void initTimr()
{ ASSR =0x08; // ASSR enables clocking
// From 32kCrystal
TCNT2 =0x00;
OCR2 =32; // As this is a CTC mode
// value of OCR2 determines
// the period
TCCR2 =0b10011111; // TCCR2 Configured for CTC mode.
// Frequency pre-scaled to
// 1024th Part.
// OCR2 toggles in compare match
while((ASSR&0x07)); // Wait until updating of the
// Above 3 register completes
TIFR =0x00;

int main()
{ DDRB=0b00001000; // The DDRXn bit must be ‘1’
// corresponding to OCR2
sleep_cpu(); // Halts The CPU. Here, you
// can use ‘while(1);’ too
return 0;

Block: Program

How to add external crystal to Avr Atmega8