PWM frequency library

Hi everyone,

I want to use the library on my Mega 2560 to generate a PWM of 20kHz. I have been able to do so on my Uno but my waveform is getting distorted in Mega. I will really appreciate some help in understanding where I am going wrong.

The code I used is as follows:

#include <PWM.h>


void setup()
{
  // put your setup code here, to run once:
  pinMode(3, OUTPUT);
  InitTimersSafe();
  bool success = SetPinFrequency(3,20000);
}

void loop() 
{
  // put your main code here, to run repeatedly:
  pwmWrite(3, 127);
  
}