Will this code produce 10Khz square wave?

Hello,
I'm playing with Arduino, producing "sounds". So I want to produce 10Khz square wave and play it on piezo. So wrote small code, with look like this:

int out = 8;
void setup() {
  pinMode(out, OUTPUT);
  Serial.begin(9600);
}

void loop() {
    digitalWrite(out, HIGH);
    delayMicroseconds(5000);
    digitalWrite(out, LOW);
    delayMicroseconds(5000);
}

The square wave changes two times in one cycle, so I have to change it every 5000 us, if not please correct me.

no, it will be around the 100hz but probably slightly less.
The line changes every 5000 usec => 200 times per second => 100Hz

  • the digitalWrite() calls take some time and the call to loop() and the hidden Serial event handler take time too.

  • to minimize time for the digitalWrite check Direct Port Manipulation

  • to circumvent the loop call you can do 2 things

void loop()
{
  while(1)
  {
    digitalWrite(HIGH);
    delayMicroSeconds(50 - a); // a is correction for time digitalWrite takes
    digitalWrite(LOW);
    delayMicroSeconds(50 - b); // b, idem + while loop
  }
}
  1. you can dive into the use of timers and timer interrupts. Then you can generate a 10KHz signal in the background (no code example nearby)

Mean using ISR() routine and timer? Which mode should I select?

Try "tone(10000);" and see if it does what you want.