C Example: Digital Outputs (Ports)

From Mech
Revision as of 15:43, 25 June 2007 by LIMS (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Code

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>
  #fuses HS,NOLVP,NOWDT
  #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).

     SET_TRIS_D(0);

Use while to create an infinite loop.

     while(TRUE){

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

        OUTPUT_D(count);
        delay_ms(500);

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

        if(count<15){
           temp = count;
           count = temp + 1;}
        else {
           count = 0;}
     }
  }

Associated Circuitry