Search code examples
cembeddeddelaytimedelay

How we can calculate the delay given by the following for loop in embedded C?


I was trying to interface the LCD (NHD‐0240AZ‐FL‐YBW) to the TM4C123GH6PMI. While doing so, I am supposed to give a delay in milliseconds, so I searched on Google. One guy has used the following loop to give a delay in milliseconds. Can anyone explain how it works?

void DelayMilis(unsigned long ulMilliSeconds)
{
   unsigned long i = 0, j = 0;

   for (i = 0; i < ulMilliSeconds; i++)
   {
     for (j = 0; j < 2000; j++);
   }
}

Solution

  • With your solution the controller spends most of the time in an unproductive loop just wasting CPU cycles and energy. A better solution would be to drive the LCD by a timer-interrupt with frequency t/2 (for example 5ms), put the data to be written in a ring-buffer or similar an send them in every cycle. Just to be sure, if the circuit does not signal ready, leave it allone and write in the next cycle. With this approach the cpu can be used for calculations, and if nothing is to be done it can simply idle. Btw: often this kind of loop gets optimized away.

    @Yunnosch: Thank you for your suggestion. I hope my point is more objective and clear now.