This seems to work OK in a sense:
#include <SPI.h>
#include "pins_arduino.h"
void setup ()
{
SPI.begin ();
pinMode (SS, OUTPUT);
// PWM, Phase Correct, 10-bit and set D9 pin correctly
TCCR1A = _BV (WGM10) | _BV (WGM11) | _BV (COM1A1);
pinMode (9, OUTPUT);
} // end of setup
int timerVal = 240;
void loop ()
{
// debugging
digitalWrite (SS, LOW);
SPI.transfer (highByte (timerVal));
SPI.transfer (lowByte (timerVal));
digitalWrite (SS, HIGH);
// end debugging
OCR1A = timerVal; // set pwm duty
delay (20);
timerVal++;
} // end of loop
I'm using SPI to see with the logic analyzer exactly what the value is at a given moment.
At the moment when we have sent out 257, we get a pulse width of 2.0545 out of 8.1819 which gives:
2.0545 / 8.1819 * 1023 = 256.88
So, close enough to a duty cycle of 257 / 1023. That seems to work then.
You will note that the frequency has dropped down to 122 Hz. This would be because of the longer overall cycle time (counting up to 1023 rather than 255). You could bump that back up by changing the prescaler.
You can do that by changing setup to:
void setup ()
{
SPI.begin ();
pinMode (SS, OUTPUT);
// PWM, Phase Correct, 10-bit and set D9 pin correctly
TCCR1A = _BV (WGM10) | _BV (WGM11) | _BV (COM1A1);
TCCR1B &= ~7; // clear prescaler
TCCR1B |= _BV (CS11); // prescaler of 8
pinMode (9, OUTPUT);
} // end of setup
The extra two lines change the prescaler from 64 to 8, multiplying the frequency by 8. Now I measure a frequency of 978 Hz which is roughly 122 Hz * 8.
