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.


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() {
  REG_PWM_CPRD0 = 42000; //1kHz
  REG_PWM_CDTY0 = 42000/2;

void loop() {   
  timer = millis();
  while(millis() - timer < 2000){  }

void PWM_Handler(void){ 

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.