still in the dark i’ve been trying to understand
TCCRxA/B : to select prescale of the timer & mode
OCxA/B: to select output related to the pin (described earlier)
OCRxA/B : to select the top or bottom overflow (pwm)
OCxA/B are just the names of the pins that will output timer 2 PMWs A and B. OC2A is pin 11 on the Arduino (pin PB3 on the mega168) and OC2B is pin 3 on the Arduino (pin PD3 on the mega168). Using this terminology lets Atmel keep use the same documentation for multiple microcontrollers, even if they use different pins for the PWM outputs.
OCRxA and OCRxB can serve two functions:
If TOP is specified as a fixed value (e.g. 0xFF) by the mode, OCRxA controls the duty cycle of the PWM output on pin OCxA and OCRxB controls the duty cycle of the PWM output on pin OCxB. Specifically, when the timer has a compare match with OCRxA or B, the associated PWM signal will go from high to low or vice versa, depending on whether the PWM is normal or inverted.
If TOP is specified as a controllable value by the mode, OCRxA controls the TOP and OCRxB controls the duty cycle. Put another way, the timer experience a compare match when it equals OCRxB and will overflow when it equals OCRxA. In this mode, the only usable PWM is generated on pin OCxB (you can’t use the PWM on OCxA for much because OCRxA is being used to control the TOP of OCxB).
Note that the above applies mainly to timers 0 and 2. Timer 1 is special in that you can run it in a mode where ICR1 can be used to control the TOP value of both PWMs A and B.
the example you gave earlier dont use OCxA/B
timer 2 A/B are not related or i dont get it at all
please can u give one example of code on one pin(ex. pin5) but re-usable for all other pins at around 20khz
You can use the TCCR2x control registers to disconnect the PWM outputs so that nothing happens on OC2A or OC2B as this code runs. See the datasheet for more details.
ISR(TIMER2_COMPB_vect) // interrupt that occurs on timer 2 compare match with OCR2B
PORTD ^= 1 << PD5; // toggle the output on Arduino pin 5 (much faster than digitalWrite(5, LOW))
ISR(TIMER2_OVF_vect) // interrupt that occurs when timer 2 overflows (i.e. when TCNT2 = OCR2A)
PORTD ^= 1 << PD5; // toggle the output on Arduino pin 5 (much faster than digitalWrite(5, HIGH))
For the above code to work, you will need to enable timer 2 compare match A and overflow interrupts. Once again, the timer 2 section of the datasheet (see the “registers” sub-section) should show you how this is done.
Note that this is not an ideal solution. If you only need one such PWM output, you really should try to use an actual PWM hardware output so that you don’t needlessly waste processing time. Additionally, this method will result in a slightly distorted PWM if there are delays in executing the ISRs that are driving the PWM. The longer the delays relative to the timescale of the PWM, the greater the distortion.