Ads

Get STM32 tutorial using HAL at $10 for a limited time!

Friday, July 17, 2015

Arduino Tutorial - Make Delay with Timer 0 (Normal Mode, Pooling)

In this tutorial, I will show you how to make a delay function with timer 0 on Arduino Uno. The delay function will generate a delay of 10ms. The settings that I used for this timer is normal mode. In this mode, timer will count from a loaded value up to timer overflow value. Loaded value for timer 0 (TCNT0) can be calculated with this formula TCNT0 = (1 + 0xFF) - (T * CLK)/N. T is the period of this timer will be overflow (0.01s), N is the prescaler, and CLK is the crystal frequency (16 MHz). The prescaler that I use is 1024. Therefore the TCNT0 value is (1 + 0xFF) - (0.01s * 16000000Hz)/1024 = 100 = 0x64.

This is the function for generating 10ms delay using timer 0:
// Delay 10ms with timer 0 normal mode, pooling
void T0Delay()
{
    // Load initial count value
    TCNT0 = 0x64;
    // Init timer mode and prescaler
    TCCR0A = 0;
    TCCR0B = (1 << CS02) | (1 << CS00);
    // Wait until timer 0 overflow
    while ((TIFR0 & (1 << TOV0)) == 0);
    // Stop timer 0
    TCCR0B = 0;
    // Clear time 0 overflow flag
    TIFR0 = (1 << TOV0);
}
In this function there is a while loop for waiting until timer 0 is overflow. Using while loop for waiting something happen is usually called pooling method. When use pooling method, CPU is not do anything and can't do other task, just wait until something happen.

To test the delay function, we can use this main program:
void setup()
{
    // PORTB.5(pin 13 Arduino) as an output 
    bitSet(DDRB, 5);
}

void loop()
{
    // Toggle LED on pin 13 Arduino
    bitSet(PINB, 5);
    // Delay 1s(100 * 10ms)
    for (int i = 0; i < 100; i++)
        T0Delay();
}
In main function, we test delay function that we have made before to generate 1s delay by looping it 100 times. So, every 1s LED will be toggled.

2 comments :