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.