I am using this code to vary the frequency from 73 kHz to 130 kHz. It works fine for Pin 9, but for Pin 10, which is supposed to output the inverted PWM signal, it is showing 32 MHz. I don't know why this issue is occurring.
void setup() {
pinMode(9, OUTPUT); // OC2A - Switch A (High Side)
pinMode(10, OUTPUT); // OC2B - Switch B (Low Side)
// Disable interrupts during timer setup
cli();
// Reset Timer2 control registers
TCCR2A = 0;
TCCR2B = 0;
// Configure Timer2 for Fast PWM Mode 7 (WGM2[2:0] = 111)
// COM2A1:0 = 10 (Clear OC2A on Compare Match, set at BOTTOM) - non-inverting
// COM2B1:0 = 11 (Set OC2B on Compare Match, clear at BOTTOM) - inverting
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(COM2B0) | _BV(WGM21) | _BV(WGM20);
// Set Fast PWM Mode 7 (WGM22 bit) and no prescaler (CS2[2:0] = 001)
TCCR2B = _BV(WGM22) | _BV(CS20);
// Set initial TOP value for ~73kHz frequency
OCR2A = 218; // TOP value for ~73kHz
OCR2B = OCR2A / 2; // 50% duty cycle for complementary operation
// Re-enable interrupts
sei();
}
void loop() {
// Sweep frequency from ~73kHz to ~130kHz by adjusting OCR2A (TOP value)
for (int ocr = 218; ocr >= 122; ocr--) {
OCR2A = ocr; // Adjust TOP value to change frequency
OCR2B = ocr / 2; // Maintain 50% duty cycle (ensure OCR2B < OCR2A)
delay(100); // Delay for smooth frequency sweep
}
// Hold at minimum frequency briefly
delay(100);
// Sweep back from ~130kHz to ~73kHz
for (int ocr = 122; ocr <= 218; ocr++) {
OCR2A = ocr; // Adjust TOP value to change frequency
OCR2B = ocr / 2; // Maintain 50% duty cycle (ensure OCR2B < OCR2A)
delay(100); // Delay for smooth frequency sweep
}
// Hold at maximum frequency briefly
delay(100);
}