9.2.14 __delay_ms Builtin

A builtin function that delays execution for the specified time.

Include

<xc.h>

Prototype

void __delay_ms(unsigned long time);

Argument

time
The number of milli seconds to delay

Remarks

This is an inbuilt function that is expanded by the code generator. When called, this routine expands to an in-line assembly delay sequence. The sequence will consist of code that delays for the number of milli seconds specified as the argument. The argument must be a constant expression that does not contain variables or function calls and that can be fully evaluated at compile time.

This macro require the prior definition of the preprocessor macro _XTAL_FREQ, which indicates the system frequency. This macro should equate to the oscillator frequency (in hertz) used by the system. Note that this macro only controls the behavior of these delays and does not affect the device execution speed.

The __delay_ms() builtin function can use loops and the nop instruction to implement the delay.

An error will result if the requested delay is not a constant expression or is too large. For larger delays, call this function multiple times.

Example

All of the inbuilt delay routines are shown in the following example.

#include <xc.h>

/* _XTAL_FREQ is defined by MCC headers; when not using MCC, place a definition similar to:
  #define _XTAL_FREQ 4000000
in your code to ensure that the 'us' and 'ms' forms of delay routines work as expected. */

unsigned char count;

void main(void) {
  SYSTEM_Initialize();

  while (1) {
    LATA = 0xFF;
    _delay(100);         /* wait 100 cycles*/
    LATA = 0xAA;
    _delaywdt(100);      /* wait 100 cycles, clearing the watchdog */
    LATA = 0x55;
    _delay3(10);         /* wait 30 cycles */
    LATA = 0xFF;
    __delay_us(800);     /* wait 800 micro seconds */
    LATA = 0x00;
    __delaywdt_us(800);  /* wait 800 micro seconds, clearing the watchdog */
    LATA = count;
    __delay_ms(500);     /* wait half a second */
    LATA = ~count;
    __delaywdt_ms(500);  /* wait half a second, clearing the watchdog */
    count++;
  }
}