Using Push Button Switch with PIC Microcontroller – CCS C

Using Push Button Switch with PIC Microcontroller – CCS C

Contents

I hope that you already go through our first tutorial of CCS C Compiler, Getting Started with PIC Microcontroller – CCS C Compiler. In that tutorial we learn how to use an output pin of PIC Microcontroller by blinking an LED with a delay of 1 second. In this tutorial we will learn how to read the status of an input pin and to make decisions according to its state. For the demonstration of its working we are connecting an LED and a Micro Switch to PIC 16F877A microcontroller. Pin connected to LED is configured as an output and pin connected to switch is configured as input. We will program in such a way that when the switch is pressed, LED will glow for 2 seconds.

Connecting Switch to a Microcontroller

PULL-UP and PULL-DOWN Resistors
PULL-UP and PULL-DOWN Resistors

Circuit Diagram

Using Push Button Switch - PIC Microcontroller
Using Push Button Switch – PIC Microcontroller

VDD and VSS of PIC Microcontroller is connected to 5V and GND respectively to provide necessary power for its operation. 8MHz crystal will provide clock for the operation of the microcontroller and 22pF capacitors will stabilize the oscillations produced by the crystal. Pin RD0 (PIN 19) is configured as an input pin to which switch is connected and Pin RB0 (PIN 33) is configured as an output pin to which LED is connected. A 10KΩ resistor is used along with switch to ensure that the pin RD0 is at Logic HIGH (VDD) state when the switch is not pressed. Whenever the switch is pressed pin RD0 becomes Logic LOW (VSS) state. A 470Ω resistor is used to limit the current through the LED.

CCS C Code

#include <main.h>

#use delay (clock=8000000)

void main()
{
  output_low(PIN_B0);     //LED OFF
  output_float(PIN_D0);   //Set RD0 as Input Pin
                          //OR set_tris_x(0b00000001)
  while(TRUE)
  {
    if(input_state(PIN_D0) == 0)
    {
      output_high(PIN_B0); //LED ON
      delay_ms(2000);      //2 Second Delay
      output_low(PIN_B0);  //LED OFF
    }
  }
}

If you are not familiar with functions used above, please read our first tutorial Getting Started with PIC Microcontroller – CCS C Compiler.

Download

You can download the entire project files here…


Share this post


>