Using my Arduino Mega 2560 I am trying to generate a PWM signal where I can change both PWM frequency and Duty Cycle. For that I decided to use Timer2 OC2A output. The code is the following one:
void setup()
{
// ======================================================
// Timer 2 example: Phase and Frequency correct PWM
// ======================================================
pinMode(10, OUTPUT);
TCCR2A = 0;//reset the register
TCNT2 = 0;
TCCR2A = 0b10000001; // COM2A1 COM2A0 COM2B1 COM2B0 - - WGM21 WGM20
// 1 0 0 0 0 0 0 1
// Behavior: PWM on OC2A (Arduino pin 10) ; Waveform generation mode 5 (Phase and Frequency Correct)
TCCR2B = 0b00001001; // FOC2A FOC2B - - WGM22 CS22 CS21 CS20
// 0 0 0 0 1 0 0 1
// Behavior: Waveform generation mode 5 (Phase and Frequency Correct) ; Prescaler -> clk/1
OCRA = 319; // TOP value -> defines de PWM frequency (25 kHz)
OCR2A = 159; // duty cycle value (80% of ICR1)
}
void loop()
{
}
When I try to compile I get the following error:
PWM_Mega.ino:43:3: note: suggested alternative: 'OCR2A'
OCRA = 319; // TOP value -> defines de PWM frequency (25 kHz)
^~~~
OCR2A
exit status 1
'OCRA' was not declared in this scope
I understand the error is because OCRA is not defined. In the uC datasheet (see picture below), mode 5 TOP, that defines the PWM frequency, is defined using register OCRA but when I put that name into my code, it is not recognized. Does anyone know the name of that register so that I can use it in the code?
Thanks
As you want to change the Timer2 frequency you'll have to sacrifice channel A (unlike Timer1 there is no input capture register, that can be used as TOP value)
The OCRA in the image means OCR2A (OCR2A means: Output Compare Register for timer2 channel A)
Therefore you can use only channel B as PWM output
note: Timer2 is 8b only and values like 319 (0x13F) will overflow into 63 (0x3F)