So we have the tone library, which produces a 50% duty cycle square wave of varying frequency, and analogWrite() which produces a fixed frequency wave of varying duty cycle. Is there any way to control frequency and duty cycle at the same time on an Atmega328-based board?

  • I don't know of any ready-made library for that, but you can always configure the timer yourself. Read the datasheet and use one of the so called “CTC” (Clear Timer on Compare Match) modes. Avoid using Timer 0 unless you don't care about loosing the Arduino timing functions (millis(), micros(), delay() and delayMicroseconds()). May 3, 2016 at 19:20
  • Also, another related question: will using setPwmFrequency() disrupt the operation of micros() and delayMicroseconds()? The sample code at the arduino playground only says it will stop millis() and delay() from working.
    – 3871968
    May 3, 2016 at 20:42
  • If you change the Timer 0 prescaler with setPwmFrequency(), then yes, you will also disrupt micros() and delayMicroseconds(). But this gives you a limited choice between only a few frequencies. If you want a specific frequency, you should better configure the timer yourself, based on the datasheet. May 4, 2016 at 7:03


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.