In this tutorial we will learn how to ON OFF LED with Switch on PIC18F4520 Starter Board.
The Explore Starter PIC board has two on board LED's which are connected to PORTD.0 & PORTD.1 and two on board Switches which are connected to PORTD.2 & PORTD.3.

Steps

  1. Configure the PORT D0 as output .
  2. Configure the PORT D2 as input.
  3. Read the switch status.
  4. ON/OFF the led as per switch status.

Code

#include "gpio.h"
#define LED PD_0 // Led is connected to PORTD.0
#define SW1 PD_2 // Switch is connected to PORTD.2
/* start the main program */
void main()
{
uint8_t value;
GPIO_PinDirection(SW1,INPUT); // Configure the switch pin as Input
GPIO_PinDirection(LED,OUTPUT); // Configure the Led pin as OUTPUT
while(1)
{
value = GPIO_PinRead(SW1); // Read the switch status
GPIO_PinWrite(LED,value); // ON/OFF the led as per switch status
}
}

Demo

PIC16f877A LED Switch.gif