Generating 100ms Delay with 12MHZ Frequency Using Embedded C Programming

30 Apr 2023 Balmiki Mandal 0 Embedded C

Create 100ms Time Delay Using Embedded C Programming

Creating a time delay in embedded C programming for an MCU (microcontroller unit) is a necessary programming skill for virtually any embedded systems project. For example, if one wishes to create a 100 ms time delay for a 12MHz MCU, the following code can be used.

Solution


// Code using 1ms and 10ms delay frequency 
// for a 12MHz MCU

// Declare variables
int i; // Counter

// Begin loop
for (i=0; i<100; i++)
{ 
    _delay_ms(10); // 10ms Delay 
    _delay_ms(1);  // 1ms Delay
} 

// End loop

This code will generate a 100 ms time delay on a 12 MHz MCU by looping through a for loop and creating a combined 1 ms and 10 ms delay frequency. After the loop has been completed, the program exits the loop, and thus completes the 100 ms delay.

 

Example 01 of an embedded C program that uses 1ms and 10ms delays to generate a 100ms delay

#include <avr/io.h>
#include <avr/interrupt.h>

void delay_ms(uint16_t count)
{
    while(count--)
    {
        // 1ms delay using timer0
        TCNT0 = 0x00;
        TCCR0A = 0x00;
        TCCR0B = 0x05;
        while((TIFR0 & 0x01) == 0);
        TCCR0B = 0x00;
        TIFR0 = 0x01;
    }
}

void delay_10ms(uint16_t count)
{
    while(count--)
    {
        // 10ms delay using timer1
        TCNT1 = 0x0000;
        TCCR1A = 0x00;
        TCCR1B = 0x0D;
        while((TIFR1 & 0x01) == 0);
        TCCR1B = 0x00;
        TIFR1 = 0x01;
    }
}

int main(void)
{
    // set clock frequency to 12MHz
    CLKPR = 0x80;
    CLKPR = 0x00;
    
    // generate 100ms delay
    delay_10ms(10);
    delay_ms(50);
    delay_10ms(5);
    
    return 0;
}

Conclusion

This program uses two timers, timer0 and timer1, to generate 1ms and 10ms delays, respectively. The delay_ms function uses timer0 to generate a 1ms delay, and the delay_10ms function uses timer1 to generate a 10ms delay.

To generate a 100ms delay, the program calls delay_10ms to generate a 10ms delay, then delay_ms to generate a 50ms delay, and then delay_10ms again to generate another 10ms delay. The total delay time is 10ms + 50ms + 10ms = 70ms.

Note that the actual delay time may not be exactly 100ms due to the overhead of the timer setup and loop execution.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.