digitalWrite() problem

Dear all,

I am trying to use my Arduino Nano for providing 50kHz switching freq. However, I discover that there is a delay at the output which come form the time require for digitalWrite() to chance status of the pin.

How can I due with this problem?
Is there are any information about the time required for "digitalWrite()" chance the output status?
Is it possible to solve this problem by using another Arduino board, like Arduino Due?

Thank you very much!!

Best,
Wave

Hello and welcome,

Yes, digitalWrite is relatively slow, compared to direct port manipulation.

And if you just want a 50khz square wave, just take over a timer and generate it in the background on a PWM pin....

For alternating signals, try the toneAC library. It is perfect to drive a H-bridge.
https://bitbucket.org/teckel12/arduino-toneac/wiki/Home

WaveT:
Dear all,

I am trying to use my Arduino Nano for providing 50kHz switching freq. However, I discover that there is a delay at the output which come form the time require for digitalWrite() to chance status of the pin.

How can I due with this problem?

It's the code, man!

What about simply using the Arduino tone() function:

tone(9,50000); // create 50 kHz tone on pin-9

Doesn't that work well enough?

I think digitalWrite is just fast enough, so long as you do proper time-accounting.

Does this code not work??

void loop ()
{
  unsigned long last_time = 0L ;
  boolean sense = false ;
  while (true)
  {
    while (micros() - last_time < 10) {}   // wait till 10us are up
    digitalWrite (pin, (sense = !sense)) ; // flip pin
    last_time += 10 ;                      // move goalpost 10us for next time
  }
}

You often see poor time accounting like this:

  if (millis () - last_time > DELAY)   // call millis to test
  {
    last_time = millis () ;   // no guarantee this returns same value as the test - misaccounts time
    ....
  }

Which you can get away with using millis() usually, but not with micros().

50kHz. On a 16MHz clock, that's 320 clock ticks. A single instruction can take multiple ticks, and you have a hardware abstraction layer on the Arduino platform. Arduino code that does anything else at all beyond sitting there generating the square wave is almost certainly not going to generate a nice, clean wave at that frequency.

As everyone else is saying - you need to use a tone generator of some sort.

digitalWrite takes about 5us or so, micros() I'm not sure - but yes this is a problem best solved
with a timer/PWM