Arduino (AVR) PWM with duty cycle for IR

This post will give you some code to generate high frequency square waves for IR sensors as well as explain how the Fast PWM mode works for Arduino.

block-diagram3I needed to interface with some IR sensors when designing the high tech mini golf hole and had to generate a 38 kHz square wave to drive the infrared LED so that it could be seen by the TSOP4838 IR receivers.

The basic Arduino analogWrite function is limited to less than 1 kHz (depending on your board), so you need to directly access one of the other on board Timer/PWM modules. The Arduino Uno (ATmega328) has 3 timer/counters:

  • Timer/Counter0: 8 bit, already used by Arduino for timing functions like millis() and delay().
  • Timer/Counter1: 16 bit, which is more than I need for this, so I'd rather save it for something else.
  • Timer/Counter2: 8 bit, fits my needs perfectly.