imranahmed
Advanced Member level 3
- Joined
- Dec 4, 2011
- Messages
- 817
- Helped
- 3
- Reputation
- 6
- Reaction score
- 3
- Trophy points
- 1,298
- Location
- Karachi,Pakistan
- Activity points
- 6,493
Please let me know I wrote 2 functions for generating delay of 1ms by timer 0 and 1us delay for timer 1 but it is not working properly why please check it and give comments, I calculate using MikroElektronica Timer Calculator.
Code:
/// Timer 1 Code for us delay ///
void initTimer1() {
//set timer 1 into CTC mode by placing 1 into WGM12. all others are zero
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B &= ~(1 << WGM13);
// calculate OCR1A for a 1us delay. OCR1A = (Td * fclk)/ Ps
// prescaler of 8
// OCR1A = (1e-6 * 16e6)/8
// OCR1A = 2
//start the clock with prescaler 8 and OCR1A = 2
TCCR1B &= ~((1 << CS12) | (1 << CS10));
TCCR1B |= (1 << CS11);
OCR1A = 2;
}
void delayUs(unsigned int delay) {
unsigned int count = 0;
// set the counter flag down
TIFR1 |= (1 << OCF1A);
// clear the count register
TCNT1 = 0;
// enter a loop to compare count with delay value needed
while (count < delay) {
if (TIFR1 & (1 << OCF1A)) { //increment every time the timer raises a flag (counting 1 us flags)
count++;
TIFR1 |= (1 << OCF1A); //set timer to start counting again
}
}
}
Code:
/// Timer 0 Code for ms delay///
void initTimer0() {
// set the timer mode to be "CTC"
TCCR0A &= ~(1 << WGM00);
TCCR0A |= (1 << WGM01);
TCCR0B &= ~(1 << WGM02);
OCR0A = 249;
}
/* This delays the program an amount specified by unsigned int delay.
Use timer 0. Keep in mind that you need to choose your prescalar wisely
such that your timer is precise to 1 millisecond and can be used for
100-200 milliseconds
*/
void delayMs(unsigned int delay) {
for (int x = 0 ; x <= delay ; x++) {
OCR0A = 249;
TCCR0A = 0x28;
TCCR0B |= 0x04;
}
}