Friday, March 31, 2017

Arduino (ATmega328) Direct Register Manipulation for Custom PWM Output (ex: 1us HIGH followed by 99us LOW --> 1% Duty Cycle at 10kHz)


Subscribe by Email!
Here's a quick example of how to make a hardware-based 1us HIGH pulse followed by a 99us LOW pulse (ie: 100us period, or 10kHz, PWM with a 1% duty cycle), via direct timer register manipulation. I've left ample comments for you to read and follow. This example below is therefore quite easy to follow and learn from, but just as it took me dozens of hours originally to learn how to do all this stuff from scratch--and to learn about all the different PWM modes possible as described in the datasheet and elsewhere, expect to spend at least a few hours if you are truly going to read the references and dig into it enough to understand it yourself. Good luck and have fun!

References to Study:
  1. Secrets of Arduino PWM, by Ken Shirriff
  2. ATmega328 Datasheet (660 pg version from 11/2015)
  3. ATmega168/328-Arduino Pin Mapping

Here's some oscilloscope screenshots of the output on Pin 3 produced by an Arduino Nano running the code below.

Rising edge to rising edge: Δx = 100us


***Subscribe by Email!***