MicroCore
MicroCore copied to clipboard
PWM Frequency change
Hello MCUdude,
i would like to change the PWM Frequency for driving a special IC between 1 kHz (100 Hz up to 1.5 kHz are acceptable) and 3 kHz (2.5 kHz up to 5 kHz are acceptable)
could you please provide an example on how to do this?
Also is it possible to change PWM Frequency after PWM is running? so to speak "in the loop"?
a short example:
switch (mode) {
case 0:
//set PWM to 1 kHz
analogWrite(Driver, 10);
break;
case 1:
//set PWM to 1 kHz
analogWrite(Driver, 30);
break;
case 2:
//set PWM to 5 kHz
analogWrite(Driver, 100);
break;
case 3:
//set PWM to 5 kHz
analogWrite(Driver, 150);
break;
case 4:
//set PWM to 5 kHz
analogWrite(Driver, 200);
break;
case 5:
//set PWM to 5 kHz
analogWrite(Driver, 0xff);
break;
}
reason for the change of PWM Frequency is to change the Drivers operating mode between PWM and Analog output current
Have a look at the current analogWrite implementation. By default, PRESCALER_AUTO is defined. It's very easy to create your own function based off analogWrite
https://github.com/MCUdude/MicroCore/blob/9634a5d7fc91ca14ad77f7113f1577681e25833b/avr/cores/microcore/wiring_pwm.c#L33-L97
thanks for the answer.
is the "F_CPU/256" necessary?
i was hoping to run the Tiny @600KHz to save some power.
is the "F_CPU/256" necessary?
That's just how the timer works. Alternatively, you can just PWM fast mode. You'll probably need to use this mode to achieve a fast enough speed when the processor is running at 600kHz. Read the datasheet and search for "AVR fast PWM". There are plenty of examples out there
how can i set the prescaler during sketch? without it being reset after calling analkogWrite?
fastpwm is f OCnxPWM f clk_I/O divided by Nx256
how can i set the prescaler during sketch?
You write your own PWM function and use this instead of analogWrite. You can write to the registers directly, like so:
TCCR0B = _BV(CS00);. Everything can be changed on the fly in your sketch
so i can comment out lines 33 zo 55
and can write as following?
switch (mode) {
case 0:
//set PWM to 1 kHz
TCCR0B = _BV(CS00);
analogWrite(Driver, 10);
break;
case 1:
//set PWM to 1 kHz
TCCR0B = _BV(CS01);
analogWrite(Driver, 30);
break;
case 2:
//set PWM to 5 kHz
TCCR0B = _BV(CS00);
analogWrite(Driver, 100);
break;
case 3:
//set PWM to 5 kHz
analogWrite(Driver, 150);
break;
case 4:
//set PWM to 5 kHz
analogWrite(Driver, 200);
break;
case 5:
//set PWM to 5 kHz
analogWrite(Driver, 0xff);
break;
}
where 1kHz is in reality 585Hz and 5 kHz in reality 4.68 kHz (@1.2 MHz clock)
i have found my issue, i am on OC0A on the attiny13V, is it possible to get fast and slow pwm here?
Hello @ltwin8 , you may find my FastPwmPin library useful (see my GitHub page). It supports the ATtiny13A as well as other MCU's. On the ATtiny13A @9.6 MHz I've measured frequencies from 38HZ up to 1.6MHz. Note at very high frequencies the PWM resolution is smaller and the signal can become less stable.