C Example: Digital Outputs (Ports)

From Mech
Jump to navigationJump to search


Program to count in binary from 0-15 and display on LEDs.

First include header file with definitions for specific PIC. Set fuses. HS is type of external clock, low voltage protection (LVP) is off, and the watchdog timer (WDT) is off. External clock frequency of 20 MHz is specified.

  #include <18f4520.h>
  #use delay (clock=20000000)

Define variables to be used in main program. Both are defined as 8-bit numbers, with count already being assigned a value while temp is left unassigned.

  int count = 0;
  int temp;

Begin main body of program.

  void main(void) {

Set Port D to be an output (0). The SET_TRIS_X function can also be used to set ports to be inputs (1).


Use while to create an infinite loop.


Assign the value of "count" to Port D, thus displaying it on the LEDs connected to Port D.


Check the value of "count", and either increment it or reset it to zero.

           temp = count;
           count = temp + 1;}
        else {
           count = 0;}

Associated Circuitry