In: Computer Science
Timer 0 in normal mode (AVR) MSYS LAB8
I'm lost on how to write this..
#include <avr/io.h>
#include "led.h"
// Prototype
void T0Delay();
int main()
{
unsigned char x = 0;
//Ready the LED-port
initLEDport();
DDRA = 0x00; //port A as
input
DDRB = 0xFF; //port B as output
while(1)
{
// Wait 1/125 seconds
T0Delay();
// Increment and show the variable
x
x++;
writeAllLEDs(x);
}
}
void T0Delay()
{
//<----- Write this function so that T0Delay() uses
timer 0 in normal mode,
// in order to wait exactly 1/125 seconds.
// Use a clock prescaler value of 1024.
}
ASSUMPTIONS:
Since, You have not provided Micro controlle's Frequency and AVR's chip name and number.
Assuming ATmega32 with 8Mhz crystal frequency.
Methods discussed below could be implemented in any AVR chip , So you just need to change few values as per the discussed formulas.
TIMER0 :
(You need to find same registers if you are not working on assumed Micro controller unit,i.e, Atmega32. Prefer to read Datasheet of your chip to do so.)
From Atmega32 Data sheet , in Timer0 section we need to look on the following Data registers:
1) TCCR0(Timer/Counter Control Register 0) :
Now, We need to set following things
a) Operate Timer0 in Normal Mode : WGM00->0 , WGM01->0
b)Set Pre-scaler of 1024 : CS02->1, CS01->0 , CS00->1
So, Overall TCCR0 becomes
So, TCCR0 = 0b00000101 = 0x05
2)TCNT0 : It's a 8 bit register. The value of the counter is stored here and it increases and decreases automatically.
3) TIFR0( TIMER/COUNTER INTERRUPT FLAG REGISTER ):
We are only interested in TOV0 flag , it raises when Counter Overflows and to clear it we need to write 1 to it.
So, Bitwise and with TOV0 flag bit and TIFR register will give 0 until , TOV0 becomes 1;
So, (1<<TOV0) ==> will give bit value of TOV0
So, BItwise and with TIFR will always give 0 , until TOV0 becomes 1.
(TIFR&(1<<TOV0)) == 0 till TOV0 becomes 1.
METHODOLOGY:
In order to produce delay of
. We need to calculate value that should
be written in TCNT0.
Now,
Since we need delay of
Value of TCNT0 = 1 + 0xFF - 63
Here , 0xFF = 255 in decimal.
So,
TCNT0 = 1+255-63 = 193
PROGRAM :
void T0Delay()
{
//Load TCNT0 with calculated value
TCNT0 = 193;
//Set TCCR0 =0x05 ,for Normal Mode with Pre-scalar of 1024
TCCR0 = 0x05;
//Start a while loop until TOV0 raises to 1
while((TIFR&(1<<TOV0))==0);
//Stop Timer 0
TCCR0 =0;
//Clearing TOV0 flag , by setting it to 1
TIFR = 0x1;
}