Friday, May 22, 2020

Creating a precise one millisecond delay using timer 0 of ATMega32

Using a built-in delay function could consume the CPU executing time. It will keep the Program counter at the delay sub-routine. Other task is queue until the delay is finish.

Using a timer, could schedule any task at a specific time without making other task awaiting. In this example we use timer to create a one millisecond tick every time the TOV0 triggered. 

I use this timer tick to schedule the time for an LED turn on and off.

Creating a precise one millisecond delay using timer 0 of ATMega32
Schematic Diagram. CPU clocks at 16 MHz. PB0 toggle an LED.

Let do some calculation:
  • The CPU clock period is T (CPU) = 1/(16000000 MHz) = 62.5 nano seconds.
  • I set the prescaler to 1:256 (TCCR0=0x04). So the timer 0 input period T  = 256 x 62.5 nano seconds = 16 micro seconds.
  • To get one millisecond: (0.000001 second)/(0.000016 second) = 62.5 counts
  • So, when TOV0 is set we assign TCNT0 = (256-62) = 194 counts or -62 counts.
Source code:

#include <avr/io.h>
//A variable to hold one milli second
unsigned int milliSecond=0;
unsigned int oneMilliDelay(void){
   //Check if TIFR is set
  if(TIFR&0x01){
   //Preload TCNT0 to make 1 mS
   TCNT0=-62;
   //Clear flag
   TIFR=0x01;
   milliSecond+=1;
  }   return milliSecond;
}
int main(void)
{
   
 //Set PortC to Output
 DDRB=0xFF;
 //Clear PortC
 PORTB=0x00;
 //Set 1:256 prescaler
 TCCR0=0x04;
 //Clear overflow flag
 TIFR=0x01;
    while (1) 
    {
  if(oneMilliDelay()<1000) PORTB=0x01;
  else PORTB=0x00;
  if(oneMilliDelay()>2000) milliSecond=0;
  /*Do other tasks*/
    }
}
Back to main tutorial page ATMega32 tutorials in C with Atmel Studio 7.

No comments:

Post a Comment

Search This Blog

Labels

25AA010A (1) 8051 (7) 93AA46B (1) ADC (30) Analog Comparator (1) Arduino (15) ARM (6) AT89C52 (7) ATMega32 (54) AVR (57) CCS PICC (28) DAC (1) DHT11 (2) Display (105) Distance Sensor (3) DS18B20 (3) dsPIC (2) dsPIC30F1010 (2) EEPROM (5) Environment Sensor (4) esp8266 (1) I2C (29) Input/Output (67) Interrupt (19) Keil (5) Keypad (10) LCD (46) Master/Slave (1) MAX7221 (1) MCP23017 (5) MCP23S17 (4) Meter (3) MikroC (2) Motor (15) MPLABX (66) Nokia 5110 LCD (3) OLED (2) One-Wire (6) Oscillator (8) PCB (6) PCD8544 (3) PCF8574 (5) PIC (107) PIC12F (2) PIC16F628A (2) PIC16F630 (1) PIC16F716 (3) PIC16F818 (10) PIC16F818/819 (2) PIC16F84A (15) PIC16F876A (1) PIC16F877A (9) PIC16F88 (1) PIC16F887 (60) PIC18 (19) PIC18F1220 (4) PIC18F2550 (3) PIC18F4550 (12) PWM (11) RTC (8) Sensor (10) SH1106 (1) Shift Register (11) Shift Registers (2) SPI (24) STM32 (6) STM32 Blue Pill (6) STM32CubeIDE (6) STM32F103C8T6 (6) SysTick (3) temperature sensor (11) Thermometer (21) Timer/Counter (30) TM1637 (2) UART (7) Ultrasonic (4) Voltmeter (7) WDT (1) XC16 (2) XC8 (94)