Initialization of Timer/Counter

Go To Last Post
9 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm currently working on a project where I am writing to an LCD display using the ATmega128 micro. I have been unsuccessful at getting the LCD display to work, and I am suspecting that it is my delay functinos that are causing hte problem. Is there anything wrong with my initialization of the timer/counter or delay function?

//Initialization of timer/counter
void counter_init()
{
TCCR1A = 0X00;
TCCR1B = 0x04;
}

//Delay function
void delay(double cycle)
{
TCNT1 = 0;
while(cycle >= TCNT1);
{
}
}

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The delay function taking a double can be a serious problem. Especially if you're passing an integer to the function.

Since TCNT1 will only go up to 65535 and is an integer, rather than double I'd suggest you pass a unsigned short instead.

Further, if you have interrupts enabled, the TCNT1=0 statement may get interrupted (having two instructions to write 8-bits of the timer at a time) and the value may become invalid. You probably want to disable interrupts during reading and writing of TCNT1.

I'll take a look at your init function later.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

BTW, here are library functions I use for TCNT1 when I have interrupts enabled:

void WriteTimer1 (u16 val) {
  u08 sreg = SREG;
  cli();
  TCNT1 = val;
  SREG = sreg;
}

u16 ReadTimer1 (void) {
  u08 sreg = SREG;
  cli();
  u16 val = TCNT1;
  SREG = sreg;
  return val;
}
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks so much for the help. I'll try your suggestion and see how it works.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

One other thought, if you're using WinAVR, perhaps you'd like to avoid tying up timer1 and use the function _delay_ms defined in the file util\delay.h
You can incorporate that function by using:

#include 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I am currently using ImageCraft 7. As well I am trying to use my timer/counter with a prescale of 256.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Your TCCR1A and TCCR1B initialization looks fine for that.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Oh, this topic is also in the wrong forum (if any moderator wants to move it).

For non-GCC C discussions, the proper forum is the "AVR forum"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for the help Kevin. I'm probably donig something wrong in the rest of my code to access the LCD.