Is there any way in Arduino to set a particular pin(pwm or not) to just generate a square wave out of the desired pin?

For instance, I want to have two pins on my Arduino Uno that output two square waves of 50% duty cycle with different frequencies. But at the same time i want my program to be doing something else. This means that bit-banging two pins in the loop() function just isn't really feasible.

Is there any way I can just set and forget a pin to output a wave?

  • 1
    why not analogWrite()? arduino.cc/reference/en/language/functions/analog-io/… – Juraj Apr 11 '19 at 4:27
  • 1
    If you don't need more than three different frequencies I highly recommend using the atmega's hardware timers to generate a pwm. In this way you get real parallelism and the main-period will not get delayed. – Sim Son Apr 11 '19 at 16:07

Setting a pin to output a square wave unattended is exactly what analogWrite does. It just turns on a square wave. If you want a 50% duty cycle then use analogWrite(127) and that will give you a square wave with 50% duty cycle. If you want to alter the frequency then search for altering the frequency of analogWrite, it has been discussed in many many places all over the web.


What frequencies are you after? You can use blink-without-delay style programming to generate many frequencies. I did that to make this organ-like device with Atmega1284P


It was programmed for 13 notes (full octave), the demo only played CDEFGABC as that was all the switches I had. (13 buttons, 13 outputs, leaving 2 pins for serial and then 4 more free).

The sketch continuously checks to see if a button is pressed, if it is then it checks if enough time has passed to change the output for that note from low to high, or high to low (half-period). While it's waiting for time to pass, other things can be occurring.

If you need higher frequencies, than PWM is the way to go.

About 1/2 way down this page, Nick Gammon explains how to set up the timers for various frequencies.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.