This is my first time using the Forum.
I have been trying for 2 days to get both works simultaneously but with independent compare match value (Timer2 OCR2A & B) and control its own output accordingly . Each OCR2A and OCR2B has different match compare value. Also each output pin (11 ,3) (OCR2A & B) would be active ( PWM) output for a duration and then OFF for a different duration. I just could not make this works.
![]()
Please help me.
The following is my sketch.
#include <Wire.h>
const int ocr2top = 255; //Mode 1 default top xFF.
float i = 0;
float j = 0;
//----------------------------------------------
void setup()
{
// OC2A arduino pin11 (PB3) OC2B arduino pin3 (PD3)
Serial.begin(9600);
// mode1 1 phasecorrection
TCCR2A = (1 << COM2A1)+(1 << COM2B1) + (0 << WGM21) + (1 << WGM20);
// WGM20 set -> Mode 1, phasecorrect xFF top
// COM2A1=1 and COM2B0 = 0 means clear OC2A n B compare match.
TCCR2B = (1 << CS22) + (1 << CS21) + (0 << CS20) + (0 << WGM22); // prescaler
//pinMode(3, OUTPUT); //OCR2B
//pinMode(11, OUTPUT); //OCR2A
delay ( 100);
}
//==================== LOOP ===========================
void loop()
{
// -------------------OCR2A--------------
if (i < 400)
{
i = i + 1;
}
else {
i = 0;
}
if (( i > 0 ) && (i < 4))
{
fun_OCR2A(140);
}
if ((i > 210) && (i < 214))
{
fun_FWDoff();
}
//--------------OCR2B------------
if (j < 600)
{
j = j + 1;
}
else {
j = 0;
}
if (( j > 0 ) && (j < 9 ))
{
fun_OCR2B(204);
}
else if ((j > 300) && (j < 308))
{
fun_REVoff();
}
}
//========= functions ==========================
//--------------------------------------------------------
void fun_FWDoff()
{
OCR2A = 0 ;
digitalWrite (11, LOW);
Serial.print(" OCR2A off= ");
Serial.println(OCR2A);
}
//------------------------------------
void fun_OCR2A(int val)
{
pinMode(11, OUTPUT); //OCR2A
OCR2A = val;
Serial.print(" OCR2A = ");
Serial.println(OCR2A);
}
//--------------------------------------------------------
void fun_REVoff()
{
OCR2B = 0 ;
digitalWrite (3, LOW);
Serial.print(" OCR2B off= ");
Serial.println(OCR2B);
}
//------------------------------------
void fun_OCR2B(int val)
{
pinMode(3, OUTPUT);
OCR2B = val;
Serial.print(" OCR2B = ");
Serial.println(OCR2B);
}