You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:
// PWM output @ 25 kHz, only on pins 9 and 10.
// Output value should be between 0 and 320, inclusive.
void analogWrite25k(int pin, int value)
{
switch (pin) {
case 9:
OCR1A = value;
break;
case 10:
OCR1B = value;
break;
default:
// no other pin will work
break;
}
}
void setup()
{
// Configure Timer 1 for PWM @ 25 kHz.
TCCR1A = 0; // undo the configuration done by...
TCCR1B = 0; // ...the Arduino core library
TCNT1 = 0; // reset timer
TCCR1A = _BV(COM1A1) // non-inverted PWM on ch. A
| _BV(COM1B1) // same on ch; B
| _BV(WGM11); // mode 10: ph. correct PWM, TOP = ICR1
TCCR1B = _BV(WGM13) // ditto
| _BV(CS10); // prescaler = 1
ICR1 = 320; // TOP = 320
// Set the PWM pins as output.
pinMode( 9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop()
{
// Just an example:
analogWrite25k( 9, 110);
analogWrite25k(10, 210);
for (;;) ; // infinite loop
}
Writing a value of 0 with analogWrite25k()
means the pin will be
always LOW, whereas 320 means always HIGH. The regular analogWrite()
should almost work, but it will interpret 255 the same as 320 (i.e.
always HIGH).
This code assumes an Arduino Uno or similar board (ATmega168 or 328 @
16 MHz). The method used here requires a 16-bit timer, and thus it
uses Timer 1 as it's the only one available on the Uno; that's why only
two outputs are available. The method could be adapted to other
AVR-based boards with a 16-bit timer. As Gerben noted, that timer should
have a corresponding ICRx register. There are 4 such timers on the
Arduino Mega, each with 3 outputs.