Ads

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

Friday, July 17, 2015

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

In my another tutorial Make Delay with Timer 0 (CTC Mode, Pooling), I have made a delay function using timer 0 in normal mode. This time I will modify the timer mode to use CTC mode. In normal mode, timer count will count up from loaded value to overflow value. In CTC mode, timer count will count up from zero to compare match value. Compare match value is stored on compare match register (OCRx). To calculate compare match value for delay 10ms, we can use this formula OCR0A = (0.01s * 16000000Hz)/1024 = 156 = 0x9C.

After we get OCR0A value, we can use that in delay function:
// Delay 10ms with timer 0 CTC mode, pooling
void T0Delay()
{
    // Load initial count value
    TCNT0 = 0;
    // Load compare match value
    OCR0A = 0x9C;
    // Init timer mode and prescaler
    TCCR0A = (1 << WGM01);
    TCCR0B = (1 << CS02) | ( 1 << CS00);
    // Wait until timer 0 compare match
    while ((TIFR0 & (1 << OCF0A)) == 0);
    // Stop timer 0
    TCCR0B = 0;
    // Clear compare math flag
    TIFR0 = (1 << OCF0A);
}
To test the delay function, we can use this main program that will toggle LED on pin 13 Arduino every 1s:
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();
}

3 comments :