Generating accurate delay using Microcontroller




Many times, we plan and build systems that perform various tasks that depend on time. Simple example of this process is the digital wristwatch. The role of this electronic system is to display time in a very precise manner and change the display every second (for seconds), every minute (for minutes) and so on (Note: wristwatch actually uses RTC).

                        To perform the task at particular time interval we must use a timer, which needs to be very accurate in order to take necessary actions. This timers depend upon the clock which is actually a core of any electronic system. And as we know, this clock is generated by crystal oscillator which is heart of any embedded system.To generate accurate delay we also have to deal with this accurate crystal frequency.

                  So before think about generating delay one should have neat idea about system clocks and all that necessary prerequisites to generate timer interrupt.

There are mainly two ways to generate delay

  1. By software logics
  2. By hardware circuit

Here i am only show you accurate time delay generation by hardware circuit. In this delay we use timer with interrupt to generate accurate delay by using this logic you can generate delay starting from 1 mili second to many days.

Let’s Play with Delay

To generate accurate delay we have to program 1 mili second timer interrupt, following is generalize example which you can modify according to your microcontroller. Mainly logic is important.

Logic Explanation

  • Make Timer interrupt of 1 mili-second
  • Declare and initialize all time variables with zero like second, minute, hour, etc.
  • Now design your super loop (while(1) loop) with your task and use time variables as you needed
  • At every 1 milisecond automatically interrupt generate and increament the time variables as you can see

Critical issue with this delay is, you have to do all your tasks related to time variable increament or reset within 1 mili-second timer interrupt service routine (ISR). If your task is consuming more than 1 mili-second in ISR, then your controller goes in indefinite mode cause before completing one ISR, your timer hardware circuit generate another interrupt and this will become spontaneous and at the end, it will never come out of interrupt and unfortunately your stack is overflow.

If you like this Article, then don’t forget to Click on Social like buttons.