Unexplainable behavior of delayNanoseconds

nodemand

Member
I'm trying to generate a precise low frequency short pulsed signal of 500Hz.
This works perfectly with delayMicroseconds, but as soon as I swap it out with delayNanoseconds and adjust the delay accordingly, to me unexplainable things start to happen. I would think the following code should generate a 500Hz signal, but my scope says different. 8.06kHz.
What is going on?
Thanx for any help!

Code:
const uint8_t pin = 5;
const uint32_t d = 1995000;

void setup() {
  pinMode(pin, OUTPUT);
}

void loop() {
  digitalWriteFast(pin, HIGH);
  delayNanoseconds(5000);
  digitalWriteFast(pin, LOW);

  delayNanoseconds(d);
}
 
Why not use the harware timers, in PWM mode for the short pulse ?
It will be precise, independant of software, interrupts, ....
 
Your delay is too long, delayNanoseconds is only intended for small values. Since you don't actually need nanosecond resolution try delayMicroseconds() instead.

(You really need to use a timer module for exact precision, not relay on CPU cycle timing.)
 
Looking at the definition of delayNanoseconds in core_pins.h it looks like it ought to work for an input of upto about 470000:
Code:
static inline void delayNanoseconds(uint32_t nsec)
{
    uint32_t begin = ARM_DWT_CYCCNT;
    uint32_t cycles =   ((F_CPU_ACTUAL>>16) * nsec) / (1000000000UL>>16);
    while (ARM_DWT_CYCCNT - begin < cycles) ; // wait
}
 
Back
Top