Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: [AVR-Chat] Re: please help me!

2005-07-25 by David Kelly

On Mon, Jul 25, 2005 at 12:19:13PM -0000, koorosh wrote:
> hi again
> 
> but how can i use counter for 1000,you know ,i could get only 1 
> milisecond from 8 bit counter.and how can i make it with 16 bit 
> counter?
> can you write the codes? what would you do if you have to make 1 
> second for a digital clock?

Its very hard to help when you say so little about what you are using
and what you have done to help yourself.

First you need to study the timer section(s) in the manual for your CPU.
Pay particular attention to the time base options (frequency source) and
available division ratios. On CPUs with timers capable of running off a
2nd crystal at 32 kHz independent of the main system clock it is
practical to produce an overflow interupt once per second.

Is also common to put another counter inside the overflow handler that
one may increase the effective count and measure longer times than the
timer is capable of otherwise. This is something I did on an Atmega64
when during the early stages not all hardware I had to play with had the
32 kHz crystal. So I faked an approximation. Compiler is avr-gcc:

//
//	Timer 0 is 8 bits.
//	Used as a 1 second counter and for software RTC.
//
SIGNAL( SIG_OVERFLOW0 )
{
#ifndef USE_32khz
	//  If not the 32 kHZ clock then must use main CPU XTAL.
	//  Can only divide by 1024 in hardware which still
	//  results in ~61 overflows per second for 16 MHz.
	//  Approximate the seconds clock here.
	static uint8_t subsec;
	
	if( subsec ) {
		subsec--; 
		return;
	}
	subsec = XTAL/1024L/256L;
#endif
	seconds++;

	[ some other things too ]

}

//
//	Do the dirty work to initialize hardware for use of Timer0
//	as a Real Time Clock. Want a 32.768 kHz crystal on TOSC1/2.
//
//	Timer 0 is 8 bits. Config for SIG_OVERFLOW0 exactly 1 Hz.
//
void
t0_init( void )
{
	TIMSK &= ~((1<<TOIE0)|(1<<OCIE0));	//  clear OCIE0 and TOIE0
#ifdef USE_32khz
	ASSR = (1<<AS0);			//  crystal on TOSC1/2
	TCNT0 = 0;
	TCCR0 = (1<<CS02)|(1<<CS00);		//  clock/128 
#else
	ASSR = 0;				//  Use I/O clock
	TCNT0 = 0;				//  seems like a good idea
	TCCR0 = (1<<CS02)|(1<<CS01)|(1<<CS00); //  clock/1024 
#endif
	TIFR  = (1<<TOV0);	//  oddly, writing 1 here clears

	//  Apnote "doc1259.pdf" says we should loop here until not busy:
	//  If this loop doesn't resolve quickly the watchdog will bite.
	while( ASSR & ((1<<TCN0UB)|(1<<OCR0UB)|(1<<TCR0UB)) )
		;

	TIMSK |= (1<<TOIE0);	//  set Timer OVerflow 0 enable
	
}

-- 
David Kelly N4HHE, dkelly@HiWAAY.net
========================================================================
Whom computers would destroy, they must first drive mad.

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.