Drive LED or Opto-isolators with AVR

This might seem very simple to many of you, but I still get questions about simple microcontroller interfacing. So I will put a thread of notes about interfacing AVR microcontrollers to devices like LED’s, relays, I2C, etc.

As you might know, Diodes require a pretty small current. This current depends on diode type and can be from 3mA up to 20mA and more. Working voltage is from 1.5 to 4V.

One AVR pin can sink up to 20mA of current; it is convenient to connect the diode directly to it with a current limiting resistor. Never connect the diode to the pin without a resistor – you may damage your AVR as your current may exceed the 20mA limit!

There are two ways to drive LEDs with AVR: sink and source. The sink method is better because the tour microcontroller doesn’t have to generate current to power LEDs. This may be critical when connecting more Diodes to AVR.

When connecting more than one diode, remember a maximum current that the microcontroller can drive. For example, Atmega8’s maximum current can be 200mA.

The same situation is with optoisolators as inside them; the same diodes are packed together with sensors. Optoisolators are convenient when you need to untie the controller from power circuits.

FYI: Current limiting resistor can be calculated very simply. Find out maximum current LED can handle and divide the applied voltage by this current, then you will have a resistance of your resistor. R=5V/20mA=250Ohm. I usually double this resistance as I’m not particularly eager to drive my LEDs on maximum.

2 Comments:

  1. Your calculation of the resistance does not take into account the voltage drop of the LED. The voltage you divide by the current is the supply LESS the LED voltage drop. eg Blue LED drop is ~3V so 5V-3V = 2V. 2V/20ma = 100 ohm. Red LED drop is ~1.8V so 3.2V/20ma = 160 ohm. Green ~2.2V drop (140 ohm). These are the MINIMUM resistance values since – as you correctly stated – the maximum sink current of an AVR is 20 ma per pin.

    Also, if you are advising people to interface silicon components to relays, insist they use a freewheeling diode across the coil to prevent back EMF spikes damaging components. Idealy this should be a ‘fast’ diode, but that is getting picky.

    Otherwise good stuff dude.

  2. Yep you are right. For smaller supply voltages is more visible, but for higher this can be neglected to simplify calculations and do it faster. But if keep in mind that it is better to chose at least 50% higher resistor values to preserve LEDs lifetime, such calculation can be accepted. Any way thanks for pointing that out.

Leave a Reply