I'm trying to get two PWM pins out of the timer1 but it seems to a more convoluted process and easier on PICs. I've been playing with the sample code for Fast PWM mode at:
But it doesn't seem like I can control the duty cycle of each pin independently?
Is there any way to have both pins (9 and 10) PWM at the same frequency and adjust their duty cycles INDEPENDENTLY?
Basically, I'm trying to write two functions, but am having a bugger of a time:
InitPWM(my_period);
UpdateDutyCycle(my_pin, my_new_duty_cycle);
Appreciate any feedback in advance.
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
ICR1 = 0xffff; // This would vary depending on the period I want for PWM on both pins?
// configure for PWM mode 14 (see p.136 of datasheet)
TCCR1B |= ((1 << WGM13) | (1 << WGM12));
TCCR1A |= (1 << WGM11);
// configure for non-inverting mode on both pins (see Table 15-2, p.135)
TCCR1A |= (1 << COM1A0); // toggle OC1A on compare match, OC1B disconnected
TCCR1A |= (1 << COM1B1); // clear OC1B on compare match, set OC1B at bottom (non-inverting mode)
TCCR1B |= (1 << CS10); // configure prescaler to divide-by-1 and start counting
// update the duty cycle as needed BETWEEN THESE TWO REGISTERS?
// this currently delivers T_pin10 = 40ms, DC_pin10 = 10% and T_pin9 = 80ms, DC_pin9 = 50%
OCR1A = 10000;
OCR1B = 1000;
Funnily enough, I had another question about Timer 1 today.
As far as I can see, the code below varies the two output pins of Timer 1 completely independently. I chose mode 3 which we used in the other thread (10-bit PMW phase-correct).
void setup ()
{
// PWM, Phase Correct, 10-bit and set D9/D10 pins correctly
TCCR1A = _BV (WGM10) | _BV (WGM11) | _BV (COM1A1) | _BV (COM1B1);
TCCR1B &= ~7; // clear prescaler
TCCR1B |= _BV (CS11); // prescaler of 8
pinMode (9, OUTPUT);
pinMode (10, OUTPUT);
} // end of setup
int countA,
countB;
void loop ()
{
countA += 5;
countB += 20;
// wrap
if (countA > 1023)
countA = 0;
if (countB > 1023)
countB = 0;
OCR1A = countA; // set pwm duty
OCR1B = countB;
delay (5);
} // end of loop
After some initial configuration the main loop varies the PWM width by different amounts each time. The logic analyzer confirms that they are varying independently.
wow thank you for the responses! To answer the first questions, the bits that weren't referenced are assumed to default to 0 at power up (as the datasheet says). I just took another look to confirm these and realized that Arduino must have been configuring WGM10 to 1 somehow. I also realized I forgot an |= where I had an =. Thank you!
More things seem to be making sense now, especially now that I have something outputting on pin9 (PORTB1 on the microcontroller).
stellios:
I just took another look to confirm these and realized that Arduino must have been configuring WGM10 to 1 somehow.
The "somehow" is the init() function doing that for you, in preparation for using analogWrite. Best not to assume those bits are in any particular state.