Changing the PWM frequency

Post here all questions related to LibMaple core if you can't find a relevant section!
Post Reply
stevestrong
Posts: 502
Joined: Fri Dec 27, 2019 4:53 pm
Answers: 8
Location: Munich, Germany
Contact:

Re: Changing the PWM frequency

Post by stevestrong »

Is the desired frequency 10kHz?
How do you know that is not correct? How did you measure it?

The problem is that when you set the period, you don't know which value your overflow register will get.
When you call pwmWrite the compare register will be set but the relationship between the overflow register and compare register is still not determined.

Instead, try following code:

Code: Select all

#define t Timer1 // Timer 1 already declared in the core files so you do not have to declare another instance of it
#define MY_FREQ  10000 // in Hz
#define MY_PERIOD  ((1000000/MY_FREQ) - 1) // in µsec

void setup() {
  // put your setup code here, to run once: 
  pinMode(pwmOutPin, PWM);

  t.pause(): // stop the timer
  t.setCount(0); // reset counter
  t.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE); // adapt for your channel
  t.setPrescaleFactor(72); // input clock 1 MHz
  t.setOverflow(MY_PERIOD);  // 100µsec, period 10 kHz
  t.setCompare(TIMER_CH1, (MY_PERIOD/2));   // adapt for your channel
  t.refresh();
  t.resume();
}
Her you can see which channel is used by the selected pin (4th value):
https://github.com/rogerclarkmelbourne/ ... pp#L58-L94
Last edited by stevestrong on Wed Mar 25, 2020 12:51 pm, edited 1 time in total.
stevestrong
Posts: 502
Joined: Fri Dec 27, 2019 4:53 pm
Answers: 8
Location: Munich, Germany
Contact:

Re: Changing the PWM frequency

Post by stevestrong »

Please use this piece of code

Code: Select all

int psc = t.getPrescaleFactor();
int ovfl = t.getOverflow();
...
Serial.begin(115200);
while(!Serial); delay(10);
Serial.print("psc="); Serial.println(psc);
Serial.print("ovfl="); Serial.println(ovfl);
after you set the timer and post here the result of psc and ovfl.

You will get the good output frequency if you use

Code: Select all

#define MY_PERIOD ((1000000/MY_FREQ) - 1) // subtraction is needed
in my code posted above.
fredbox
Posts: 125
Joined: Thu Dec 19, 2019 3:05 am
Answers: 2

Re: Changing the PWM frequency

Post by fredbox »

Here is a snippet from one of my projects with a 60khz square wave output on PA6;

Code: Select all

// set timer 3 to 60KHZ square wave on PA6 - T3C1
HardwareTimer pwmtimer(3);
void setup() 
{
  pinMode(PA6, PWM);
  pwmtimer.pause();
  pwmtimer.setPrescaleFactor(1);
  pwmtimer.setOverflow(1200 - 1); // 72MHZ / 1200 = 60KHZ
  pwmtimer.setCompare(TIMER_CH1, 600);  // 50% duty cycle
  pwmtimer.refresh();
  pwmtimer.resume();
}
To change the duty cycle, use pwmtimer.setCompare(TIMER_CH1, n) where n varies from 1 to 1198.
Post Reply

Return to “General discussion”