1 kHz PWM frequency on Arduino Nano 33 IoT

How to get the PWM frequency to 1 kHz on Arduino Nano 33 IoT?

Default PWM frequency is 732 Hz.

Hi veelu,

The following code sets up 1kHz PWM on a Nano IoT on D7:

// Output 1kHz PWM on digital pin D7 using the Nano33 IoT
void setup()
{
  // Feed GCLK0 at 48MHz to TCC0 and TCC1
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_CLKEN |         // Enable GCLK0 as a clock source
                      GCLK_CLKCTRL_GEN_GCLK0 |     // Select GCLK0 at 48MHz
                      GCLK_CLKCTRL_ID_TCC0_TCC1;   // Route GCLK0 to TCC0 and TCC1
  while (GCLK->STATUS.bit.SYNCBUSY);               // Wait for synchronization

  // Enable the port multiplexer for pins D7
  PORT->Group[g_APinDescription[7].ulPort].PINCFG[g_APinDescription[7].ulPin].bit.PMUXEN = 1;

  // D7 is on EVEN port pin PA06 and TCC1/WO[0] channel 0 is on peripheral E
  PORT->Group[g_APinDescription[7].ulPort].PMUX[g_APinDescription[7].ulPin >> 1].reg |= /*PORT_PMUX_PMUXO_E |*/ PORT_PMUX_PMUXE_E;
  
  // Normal (single slope) PWM operation: timer countinuously counts up to PER register value and then is reset to 0
  TCC1->WAVE.reg = TCC_WAVE_WAVEGEN_NPWM;          // Setup single slope PWM on TCC1
  while (TCC1->SYNCBUSY.bit.WAVE);                 // Wait for synchronization

  TCC1->CTRLA.reg = TC_CTRLA_PRESCALER_DIV8 |      // Set prescaler to 8, 48MHz/8 = 6MHz
                    TC_CTRLA_PRESCSYNC_PRESC;      // Set the reset/reload to trigger on prescaler clock
  
  TCC1->PER.reg = 5999;                            // Set the frequency of the PWM on TCC1 to 1kHz: 48MHz / (8 * 5999 + 1) = 1kHz
  while (TCC1->SYNCBUSY.bit.PER);                  // Wait for synchronization
  
  TCC1->CC[0].reg = 3000;                          // TCC1 CC0 - 50% duty cycle on D7
  while (TCC1->SYNCBUSY.bit.CC0);                  // Wait for synchronization
  
  TCC1->CTRLA.bit.ENABLE = 1;                     // Enable the TCC1 counter
  while (TCC1->SYNCBUSY.bit.ENABLE);              // Wait for synchronization
}

void loop() 
{ 
  // Using buffered counter compare registers (CCBx)
  TCC1->CCB[0].reg = 1500;                        // TCC1 CCB1 - 25% duty cycle on D7
  while (TCC1->SYNCBUSY.bit.CCB0);                // Wait for synchronization
  delay(1000);                                    // Wait for 1 second
  TCC1->CCB[0].reg = 4500;                        // TCC1 CCB1 - 75% duty cycle on D7
  while (TCC1->SYNCBUSY.bit.CCB0);                // Wait for synchronization
  delay(1000);                                    // Wait for 1 second
}