In Arduino we can use the analogWrite(pin, value) method to create a PWM signal on the digital pins. The value parameter is used to change the duty cycle but the PWM frequency which is fixed at usually 490 Hz and can not be changed.

Here is a simple example sketch that also works with the UNO R4:

void setup() {
  pinMode(D2, OUTPUT);
  // set 100%
  analogWrite(D2,255) 
}

void loop() {}

Fortunately the Arduino UNO R4 provides some easy to use PwmOut class which provides more flexibility: You define the frequncy in hz and the initial duty percent. There is also a method to update the duty cycle using percent.

#include "pwm.h"

PwmOut pwm(D2);

void setup() {
  //period 50us = 20000hz; pulse 0 us = 0%
  begin(20000.0f, 0.0f);

  // set 100%
  pwm.pulse_perc(100.0f);

}

void loop() {}
Categories: Arduino

9 Comments

Andy Beer · 17. April 2024 at 14:03

As of the latest R4 PWM library update 08/04/2024, this example code generates a compile error,
“Compilation error: call of overloaded ‘begin(int, double)’ is ambiguous”
Why has this happened? Surely there should be some documentation on the effect of the library update?

    pschatzmann · 20. April 2024 at 0:48

    The compile error gives the relevant new method: bool begin(float freq_hz, float duty_perc);
    I have updated the blog…

      Andy Beer · 22. April 2024 at 12:17

      Many thanks

Michiel · 12. March 2024 at 20:07

What is the highest PWM frequency of which the Arduino R4 is capable?

For the Arduino R3 I use a special-purpose library that talks directly to the timers involved so I’m no longer limited to the stated 490Hz. I have used this superb library to get as high as 50kHz for smoother running without whine and little loss of efficiency.

https://forum.arduino.cc/t/pwm-frequency-library/114988

If the Arduino R4 is similarly limited then I hope an expert will update this library to reflect the RA4M1 timers and instruction set!

Justin · 6. March 2024 at 5:03

I found your code really helpful in generating a pwm signal with the frequency and duty cycle I’m looking for but is there a way to change frequency and duty cycle while holding a button?

Felix · 1. December 2023 at 7:57

Where can i find the pwm.h libary your are using?
And does it work for all pwm-pins?
Thanks for your support!

    pschatzmann · 1. December 2023 at 8:27

    It’s part of the arduino core! No library is needed.

      Felix · 1. December 2023 at 8:41

      Thanks for your fast reply.
      I’ve been using the old IDE 1.xx where it was not integrated.
      But I installed the ide 2.xx now and now its working!

Amrit · 12. September 2023 at 8:45

I want to know that how can I generate Complementary PWM signal using arduino r4, I need example for both using timers and the other way if there is any..

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *