ATmega32 timer0 strange behaviour

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

Hi, I'm making a project for my microcontroller classes based on ATmega32, 8 diodes and a 4x4 keyboard I made. Unfortunately, it's not going as good as I expected.I came upon a problem with timer0.
I declared a variable, which I decrement inside the timer0 interrupt. The variable was supposed to inform me when to toggle the diodes. Inside the main loop I made a while loop and checked whether the variable was equal to zero or not. When It was equal I toggled the diodes and set the variable to some value to make a visible delay again.Unfortunately, this way of doing that doesn't work properly.It works only one time. I made a modification and instead of toggling the diodes inside the main loop, I did it inside the interrupt handling procedure. This time, to my amazement, it works perfectly well. I don't remember the exact code to it, but it's something like this:

#include 
#include 

unsigned char delay;

ISR (SIG_OUTPUT_COMPARE0) {
if (delay > 0) delay--;
};

int main (void) {
DDRC = 0xff;
PORTC = 0xff;
/*
the timer0 settings I don't remember exactly
CTC mode,no output to pin,prescaler 1024,OCR0 = 255
*/

while (1) {
if (delay == 0) {
PORTC = ~PORTC;
delay = 100;
};
};
};

Can anybody tell me why isn't that working, the way I want? Thanks in advance for any help.

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

Did you try volatile for your delay variable?

Real men don't use backups, they post their stuff on a public ftp server and let the rest of the world make copies.

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

I just tried it, and there's no improvement unfortunately.

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

1) Did you set OCIE0 in TIMSK?
2) Did you do an sei()?

If you can post your Entire code (the program doesn't look very big)
that saves a lot of guesswork.

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

Sorry guys, looks like you both were right. I tested the volatile keyword without the sei () expression. So, volatile is necessary in this case after all. Big thanks to you both.