Arduino Fast PWM

The usual way to do PWM on an arduino is using analogWrite().  This works for a lot of purposes, but is very slow.  PWM done this way operates around 500 Hz.  That’s fine if you are dimming a single LED, but PWM can be used for so much more.

Common uses for PWM include:

  • motor speed controllers
  • switch mode power supplies
  • waveform generation, including audio output

There are arduino libraries available for some of these, and shields and modules for others.  But it’s worth knowing how to do fast PWM anyway.

On any of the mega88/168/328 based arduinos (I like to use nanos) the following simple sketch will work:

 


void setup() {
// put your setup code here, to run once:
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS20); //see table for clock select
OCR2A = 180; //this value from 0-255 is the duty cycle
}


void loop() {
// put your main code here, to run repeatedly:
OCR2A = (OCR2A+1)%256;
delay(10);
}

This outputs PWM on digital pin 11 at 62500 Hz.  There are much more detailed instructions here: https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM, but I’m going somewhere with this.  I noticed a question the other day.  It was “How do I make a negative voltage with an arduino?”.  In my next post I’ll have two answers to this, one with inductors, diodes, and capacitors, and one with only capacitors and diodes.  That is going to lead into another post and video about fundamentals of switch mode power supplies.  That can be a daunting thing to get into, but once we experiment a little you’ll find all sorts of uses in your projects.

Leave a Reply

Your email address will not be published. Required fields are marked *