Saturday, September 11, 2010

Speeding up Arduino PWM

If you ever need to speed up the Arduino PWM frequency, here is an example. You can manipulate the counter prescalar with TCCR1B, and the amount it counts up each cycle with ICR1:

int i;

void setup()
{

pinMode(2, OUTPUT); // direction pin
digitalWrite(2, LOW); // set direction CW

TCCR1A = 0x00; // sets timer control bits to PWM Phase and Frequency Correct mode
TCCR1B = 0x12; // sets timer control bits to Prescaler N = 8
ICR1 = 500; // Upper Timer Limit

analogWrite(9,1); // for Geckodrive controller you want a very short on pulse

Serial.begin(115200);
Serial.println("Delaying 100...");
delay(100);

}

void loop()

{
for(i=500;i>70;i=i-1){
Serial.println(i);
ICR1=i;
delay(20);
}
for(i=70;i<500;i=i 1){
Serial.println(i);
ICR1=i;
delay(20);
}
}


I believe the prescalar leads to 16 MHz / 8 = 2 MHz, then I count up to 500 meaning about 4 kHz frequency output, then I move it up to a 70 count or 28.5 kHz.

No comments: