Hello,
I'm trying to make my Arduino Nano generate two PWM signals of varying pulse length and frequency.
Here is my initial code:
#include <avr/io.h>
void setup() {
pinMode(3, OUTPUT);
TCCR2A = _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS20);
//TIMSK2 = _BV(OCIE2B);
OCR2A = 134;
OCR2B = 67;
pinMode(5, OUTPUT);
TCCR0A = _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
TCCR0B = _BV(WGM02) | _BV(CS00);
//TIMSK0 = _BV(OCIE0B);
OCR0A = 134;
OCR0B = 67;
TCNT2 = 0;
TCNT0 = 0; //191
}
void loop() {
TCCR2A |= _BV(COM2B1);
TCCR0A |= _BV(COM0B1);
delay(2);
TCCR2A &= ~(_BV(COM2B1));
TCCR0A &= ~(_BV(COM0B1));
delay(2);
}
The first thing I noticed from this code, is that the two timers, timers 0 and 2 are not perfectly in phase here. This is because of the commands:
TCNT2 = 0;
TCNT0 = 0
Upon executing both lines, there is a clock cycle difference between the two PWM signals, 62.5 ns. Exactyly 1/ 16 MHz
The first thing I'd like to know therefore, is how do I get the two timers in exact phase with one another? Looking at the data sheet, there's a block called "Control Logic" which increments the counter for each timer. Is there a way to turn this off and on, or clear it whenever I want? Or is there a better way?
The second thing is, once I've got both timers in sync, what would be the best way to get the second timer 180 degrees out of phase with the first?
Finally, I think my method for generating pulses is a poor implementation, but I've found the literature on using interrupts quite confusing. Are there any examples anyone can refer me to so I can generate pulses correctly.
Hopefully that all makes sense.
Thank you