pwm frequency

how can i change the frequency in the sketch below?

void setup(){
Serial.begin(115200);
pwmSetup();
}
void loop(){
int targetVoltage = 100;//type in the voltage you want. Refer to guide on limiting comonents
//using resistive voltage divider, same R1 and R2 on wikipedia “voltage divider”
//R1 is connected to high voltage
//R2 is connected to ground
double R2 = 200000;
double R1 = 10000000;
double voltage = (analogRead(A1)/1023.)4.9(R2+R1)/R2;
if(voltage < targetVoltage){
OCR2A = 100;
}
if(voltage > targetVoltage){
OCR2A = 0;
}
}
void pwmSetup(){//just run once at setup
pinMode(3, OUTPUT); //OCR2B 3 and 11 are pwm channels
pinMode(11, OUTPUT); //OCR2A
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20); //phase correct pwm 31250hz
TCCR2B = _BV(CS20);//change this as datasheet says to mainly get different pwm frequencies
OCR2A = 0;
OCR2B = 0;

You will need to look into the datasheet for the microcontroller used in your Arduino.
If you have Arduino Uno, it is Atmel Atmega328 (Smart | Connected | Secure | Microchip Technology).

Look into the chapter "8-bit timer/counter2..." > "Register description" and look at the registers TCCR2A and TCCR2B. There are tables which explain the values written to those registers in your code.

You could first try to decode what the current settings in your program mean:
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20); //phase correct pwm 31250hz
TCCR2B = _BV(CS20);

Then modify it to get the new frequency.

The _BV(COM2A1) means that the bit COM2A1 will be set to 1.
So in TCCR2A you have the bits COM2A1, COM2B1 and WGM20 set to 1. In TCCR2B you have only the CS20 bit set to 1, all other bits are 0.

You will only need to change the value in TCCR2B. Now it is set so that the timer counter runs with the frequency of the input clock (only CS20 = 1 means no prescaling according to the table in the datasheet).
If you change the code to:
TCCR2B = _BV(CS21);
you will get 8-times lower frequency.
The problem is if you want to make the freq. higher. For this there is no room as far as I can see. The code already uses the highest possible frequency and you can only make it lower. :frowning:

Its perfectly possible to set to a higher range of frequencies by choosing one of
the modes where the counter's TOP value is determined by a register. For instance
8MHz is achievable (but with a fixed duty cycle!)

BTW the code shown is for 31.3725 kHz, not 31.25 kHz - in 8-bit phase-correct
mode the counter steps 0,1,2,...,254,255,254, ..., 2,1, and repeats which is a cycle
of 510 counts, not 512.

You can use fast mode rather than phase-correct and the counter simply counts
0,1,2,...,254,255,0,1,... which is nearly twice as fast (62.5kHz).

The full gen is in the datasheet (note that all the counters differ in detail).