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?
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:
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.