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

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

Phone

044 4213 1795

Mobile

+91 91764 16648
 

How to Work With 32K crystal and AVR Microcontroller

Introduction

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:

Component

Qty

ATmega8

1

LED

1

Resistor

1

Push Button switch

1

32768Hz Crystal

1

33pF Ceramic capacitor

2

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
#include
#include
#include

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
_delay_ms(2000);
initTimr();
sleep_cpu(); // Halts The CPU. Here, you
// can use ‘while(1);’ too
return 0;
}

Block: Program

How to add external crystal to Avr Atmega8