Re: Changing the PWM frequency
Posted: Tue Mar 24, 2020 9:29 am
Everything relating to using STM32 boards with the Arduino IDE and alternatives
https://www.stm32duino.com/
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();
}
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);
Code: Select all
#define MY_PERIOD ((1000000/MY_FREQ) - 1) // subtraction is needed
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();
}