Hello World – Blinking LED

There are many ways for you to test if your code is working and the simplest is via LEDs. LEDs are effective because 1) there is inexpensive visual indication 2) the flashing LED indicates that your code is looping successfully.

The flashing led is a combination of an LED and a resistor. The PIC port provides 5Vdc at a maximum of 20mA. 20mA is more that enough current to drive the LED and to reduce illumination you can increase the resistance.

 

5Vdc —[ 680 Ohm ] —–|>|—— GND

(FIG 1 – LED & Resistor Network)

To wire the above up, is quite simple and provided that the LED orientation is correct your LED should illuminate as expected.

I will demonstrate this by using PORT B as this is the most common port in 18, 28 and 40 PIN devices.

The PIC16F887

The PIC16F887 has a number ports from A to E, but a full discussion of how each port functions is beyond the scope of this article. You can locate PIN RB.1 using the PCB labelling and connect the resistor LED combination as indicated.

Using PORTB

The code sample below uses PORTB and one of the PINs on PORTB. The TRIS register is initialised and the PIn set high and low alternatively as the code loops. This code sample’s structure is somewhat more complex than would be expected, but I am planning to build on the structure used to include additional functionality.

What the code does:

  1. Initialses the PIC
  2. Loops using the while(1) statement which is always true to maintain the loop
  3. Calls LED() function during which the led is on for 1 second and then off for one second

The code sample is below using the mikroC compiler.

/*

copyright (c) 2011, ZarDynamix: An embedded solutions company

Hello World Code Sample for ProtoDev

*/

void led(){

    TRISB=0xfc;
    PORTB.B1=1;
    Delay_ms(1000);  /* second pause */
    PORTB.B1 = 0;
    Delay_ms(1000);
    }

void main(){ 

    ANSEL  = 0;            // Configure AN pins as digital
    ANSELH = 0;
    C1ON_bit = 0;          // Disable comparators
    C2ON_bit = 0;

    while (1) {                     // Endless loop
              led();
               }
     }
}

“An important note with working with a PIC16F887 is that the analogue inputs must be disabled when using the IO pins on PORTB as Digital I/O.”

References
I/O Ports