Arduino Due digital out frequency fluctuates

Hi,

I am a complete new to Arduino. I am trying to output a selected frequency (180hz) on pin 62. No matter what I do, the output frequency fluctuates between 179.8hz to 180.1hz.

For a frequency of 100kHz it fluctuates by 0.02us

For a frequency of 10kHz it fluctuates by 0.1us

For a frequency of 1kHz it fluctuates by 1us

What am I doing wrong?

Thanks in advance

Test.ino (761 Bytes)

Where do you find arduino pin 62 (see Graynomad pinout diagram) ?

What precision percentage are you looking for and for which PWM frequency ?

Hi,

Thanks for replying.

I am using digital pin 62 (A8). I am looking for 0.01 % precision with no PWM just a 50% duty cycle.

To achieve the best possible precision for a given frequency, you need to carefully select the clock rate (DIVA and PRES dividers). Then divide by the highest possible number with PWM_CPRD to obtain the desired frequency.

You need to look over PWM Sam3x datasheet section. Here is an example code for a 1 KHz PWM frequency with a 50% duty cycle:

/*****************************************************************************/
/***       PWMH2 on arduino pin 39, Frequency = 1 KHz, Duty cycle = 50 %    **/
/*****************************************************************************/

void setup () {

  PMC->PMC_PCER1 |= PMC_PCER1_PID36;                    // PWM power ON

  PWM->PWM_DIS = PWM_DIS_CHID2;                         // Disable PWM channel 2

  // Select Instance=PWM; Signal=PWMH2 (channel 2); I/O Line=PC7 (P7, Arduino pin 39, see pinout diagram) ; Peripheral=B
  PMC->PMC_PCER0 |= PMC_PCER0_PID13;                 // PIOC power ON
  PIOC->PIO_PDR |= PIO_PDR_P7;                          // Set PWM pin to an output

  PIOC->PIO_ABSR |= PIO_PC7B_PWMH2;                     // Set PWM pin perhipheral type B (page 973)

  // Set frequency and duty cycle for PWMH2
  // Set the PWM clock rate to 28MHz (84MHz/3).Adjust DIVA for the best possible resolution
  PWM->PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(3);   

  PWM->PWM_CH_NUM[2].PWM_CMR = PWM_CMR_CPRE_CLKA;      // The period is left aligned, clock source as CLKA on channel 2

  PWM->PWM_CH_NUM[2].PWM_CPRD = 28000;                 // Channel 2 : Set the PWM frequency 28MHz/(CPRD) = 1 KHz ;

  PWM->PWM_CH_NUM[2].PWM_CDTY = 14000;                 // Channel 2: Set the PWM duty cycle to x%= (CDTY/ CPRD)  * 100 % = 50 %;

  PWM->PWM_ENA = PWM_ENA_CHID2;                        // Enable PWMH2

}

void loop() {

}

If you have an external Crystal on your board, maybe you can obtain a better precision.

Hi,

Thanks sooooo much for your response and sample code. Works fantastic! There is no fluctuation.

Tested it on pin 39 as per example. I am sorry for the question, but how would I change it to pin 62?

Hi,

Just figured out how stupid my question was. Pin 62 does not have PWM!

Thanks once again for your help.