18F LED Example

    LED's are great as indicators, and are very easy to interface with. PIC's can produce around 25mA on an output. This is much more than most logic outputs will deliver, and it helps to interface with many devices, especially simple LED's that only require 5mA-20mA usally.

    Here's a simple program that will turn an LED on and off twice a second in Swordfish;

Device = 18F4520
Clock = 8
Config OSC = INTIO67                // Use the Internal Oscillator

Include "utils.bas"

Dim LED As PORTA.0                  // Assign an alias for "LED"

// Start Of Program...
OSCCON = %01111111                  // Sets up the internal oscillator
SetAllDigital                       // Make all Pins digital I/O's
Low(LED)                            // Make the LED pin an output and set it low

While True

    LED = 1                         // Turn on the LED
    
    DelayMS(500)                    // Delay for half a second
    
    LED = 0                         // Turn off the LED
    
    DelayMS(500)                    // Delay for half a second
    
Wend


The wiring diagram is as follows

Note the PIC's power supply/oscillator are not shown

    Your LED will have a predefined forward voltage and current, which can be found from the supplier your buy it from. You need to use this forward voltage to calculate the series resistor required. Say for example, my LED had a Vf of 2.0 volts, and and If of 20mA(forward current) . This means that the series resistor needs to drop 3V and yet allow 20mA to pass through it. Simple maths allows us to calculate exactly what resistance we need.

Ohms Law: V = IR
Therefore R = V/I

And if R = 3/0.020
Then R = 150 ohms

    Now you know that the series resistor must be 150 ohms or greater to safely run your LED.

Where you can get the components;

 

Skip Navigation Links.

Collapse Site Tutorial IndexSite Tutorial Index
Expand 16F PIC Examples16F PIC Examples
Collapse 18F PIC Examples18F PIC Examples
LED's
Switches
Expand 7 Segment Displays7 Segment Displays
LCD's
Expand 7 Segment Displays7 Segment Displays
ADC
ADC (Another Example)
EEPROM's
DS1307
Expand RS232 and UARTRS232 and UART
DS18B20
External ADC
Hall Effect Sensor
Pulse Width Modulation (PWM)
Infrared UART
Swordfish Modules
Expand Code SnippetsCode Snippets
Expand Handy TipsHandy Tips