PWM frequency change on 328PB

I am trying to change the PWM frequency of 328PB version from default 487 hz on pins 2, 3 to about 1 kHz.
I could have sucess on pin 3 by adding this in the setup:

TCCR2B = TCCR2B & 0b11111000 | 0x03; // 970 Hz // pino 3 a 975 hz

But no on the pin 2 that is connected to Timer 3. Also no success on pins 9 and 10 (Timer 1).

Nano 328PB have different timers.

Any help ?

https://www.arduino.cc/reference/tr/language/functions/analog-io/analogwrite/

Did you try to change the settings of Timer1and Timer3, as you did it for Timer2? Please show the code.

This should set Timer 3 to pahse correct PWM mode with 977Hz PWM frequency and still having the two output compare channels OCR3A and OCR3B available.

/**
  * URL: https://dbuezas.github.io/arduino-web-timers/#mcu=ATMEGA328PB&timer=3&CompareOutputModeA=clear-up%2C+set-down&CompareOutputModeB=clear-up%2C+set-down&topValue=0x03FF&clockPrescalerOrSource=8&timerMode=PCPWM&OCR3A=508&OCR3B=794
  * Mode     : PCPWM
  * Period   : 1.023 ms
  * Frequency: 977.51711 Hz
  * Outputs  : 
  *  - D0: 46.04%, clear-up, set-down
  *  - D2: 77.61%, clear-up, set-down
  */
void setup(){
  TCCR3A = 
    1 << COM3A1 |
    1 << COM3B1 |
    1 << WGM31 |
    1 << WGM30;
  TCCR3B = 
    1 << CS31;
  DDRD = 
    1 << DDD0 |
    1 << DDD2;
}

void loop(){
  OCR3A = 471; // change at will between 0 - 1023
  OCR3B = 794; // same
}

Thank you for the solution. Now I could enable 10 bit (1023 values) PWM at 976 kHz on 16 bit Timers (1, 3 and 4) with your code.
This is the code for T1 and T3 :
call from setup()

void enableT1T3PWM() {
  //////////work 10bit for pins 9 and 10 Timer 1  978hz
  TCCR1A =
    1 << COM1A1 |
    1 << COM1B1 |
    1 << WGM11 |
    1 << WGM10;
  TCCR1B =  1 << CS11;
  
  /////// work 10bit for pins 0 and 2 Timer 3  978hz
  TCCR3A =
    1 << COM3A1 |
    1 << COM3B1 |
    1 << WGM31 |
    1 << WGM30;
  TCCR3B =  1 << CS31;
  
}

This allows simple

analogWrite (pin, value10bit);

Note that to enable PWM on pin 0 Serial.begin() must be ended with Serial.end().
Work fine on At Mega328PB (Nano)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.