Arduino DUE pulse generation?

Good day all, I started playing with the PWM macrocell on DUE few weeks ago, and I wonder is it possible to generate pulses precisely using PWM macrocell?(Q1)

I havent explore with Timer Counter(TC) on DUE, and I found out that there is pulse generation function in TC, so is it better to use TC instead of PWM to generate precise amount of pulses? (Q2)

The pulses need to be generated in high frequency up to 250kHz, I chose PWM at first because it can easily manipulate the frequency of the output by changing the value of PRE, DIV, CPRD, CDTY etc, but now I believe that the PWM macrocell is not meant for pulse generation(maybe? or there are some ways to achieve this).

I'm looking for someone to point me to correct direction to generate precise amount of pulses using DUE.

Thank you.

Desmond

Q1 : yes

Q2: no

There are numerous example sketches with PWM or Timer Counter registers programing in the DUE sub forum.

If you don't feel like using PWM or TC registers, have a look at tc_lib oand PWM_lib from antodom.

Alright, thanks. I will look for the forum again, there must be something I missed out.

Another question is: Is there any register in PWM that able to count the amount of pulses generate? or I can only do it programmatically.

The PWM generates one pulse per period, idem for TC. You can trigger an interrupt evry time a period is completed and increment a counter inside the interrupt handler.

Do you mean like this?

  unsigned long timer = 0;
  long N = 0;


void setup() {
  Serial.begin(115200);
  
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PWM_DIS = PWM_DIS_CHID0;
  PIOC->PIO_PDR |= PIO_PDR_P3; 
  PIOC->PIO_ABSR |= PIO_PC3B_PWMH0; 
  PIOC->PIO_PDR |= PIO_PDR_P2; 
  PIOC->PIO_ABSR |= PIO_PC2B_PWML0; 
  PWM->PWM_CLK = PWM_CLK_PREB(0) | PWM_CLK_DIVB(2); 
  REG_PWM_CMR0 = PWM_CMR_CPRE_CLKB;
  REG_PWM_CPRD0 = 42000; //1kHz
  REG_PWM_CDTY0 = 42000/2;
  REG_PWM_IER1 = PWM_IER1_CHID0; 
  NVIC_EnableIRQ(PWM_IRQn); 
  REG_PWM_ENA = PWM_ENA_CHID0;  
}

void loop() {   
  timer = millis();
  while(millis() - timer < 2000){  }
    Serial.println(N);
}

void PWM_Handler(void){ 
  N++;
  PWM->PWM_ISR1;   
}

The outputs are

13:46:00.645 → 1999
13:46:02.634 → 3999
13:46:04.627 → 5999
13:46:06.620 → 7999
13:46:08.652 → 9999
13:46:10.626 → 11999

Based on Figure 38-5 Waveform Properties (pg 980 Atmel datasheet), the interrupt is triggered after each pulse, I assume this is the reason why the output is one pulse lesser(first pulse is not counted).

Yes BUT declare N as volatile, since N incrementation is done INSIDE an interrupt handler.