When learning microcontroller the first program that everyone tries is Turning ON a LED or Flashing a LED. Here I will be explaining how to interface a LED to a Microcontroller & a sample code for LED flashing.
The adjoining figure shows how to interface the LED to 8051 microcontroller. As you can see the Anode is connected through a resistor to Vcc & the Cathode is connected to the Microcontroller pin. So when the Port Pin is HIGH the LED is OFF & when the Port Pin is LOW the LED is turned ON.
You may ask why we can’t connect Anode to the Port Pin and cathode to the Ground. The answer is simple, 8051 has an internal pull-up resistor of 10kΩ. So now when the port Pin is HIGH the Anode is positive with respect to the Cathode so the LED should turn ON right? But the internal pull-up resistor comes in series with the resistor thus limiting the current flowing through the LED. This current is not sufficient enough to Turn ON the LED.
Flashing LED ALGORITHM
1. Start.
2. Turn ON LED.
3. Turn OFF LED.
4. GO TO 2.
We now want to flash a LED. It works by turning ON a LED & then turning it OFF & then looping back to START. However the operating speed of microcontroller is very high so the flashing frequency will also be very fast to be detected by human eye.
Modified Flashing LED ALGORITHM
1. Start.
2. Turn ON LED.
3. Wait for some time (delay).
4. Turn OFF LED.
5. Wait for some time (delay).
6. Go To 2.
You can see in the modified algorithm that after turning ON the LED the controller waits for the delay period & then turns OFF the led & again waits for the delay period & then goes back to the start.
PROGRAM 1
1. ORG 0000h
2. loop:
3. CLR P2.0 //Turn ON LED
4. CALL DELAY
5. SETB P2.0 //Turn OFF LED
6. CALL DELAY
7. JMP loop
In the above program LED is connected to P2.0. The above program can also be written as follows.
PROGRAM 2
1. ORG 0000h
2. loop:
3. CPL P2.0 //Compliment Port Pin
4. CALL DELAY
5. JMP loop
The only drawback of the second program is that the LED's ON time will be equal to LED's OFF time. Whereas in the first program if different delay routines are called the LED's ON time can be different than that of LED's OFF time.







Todd Blackmon
Invite as author
Interesting note
Blinking will generally grab the eye better than an individual on time. A good general rule is that you can blink it at a rate below ~30Hz to see individual blinks. This is a toggle about every 16ms.
By making the duty cycle (on time divided by total period) lower, you can actually reduce the power used. Interestingly enough, the human eye can see pulses as short as 1ms. So a very short bright pulse with a longer period can actually lower power considerably and still allow good visibility.