Lab 2: Basic digital input and output

Description

Today we will learn how to read digital inputs from a push button switch. A digital input has only two values: 1 and 0. The configuration of the push button switch is same as that of the reset switch except it goes to a different port pin. The status of the switch will be read through RC1 and every time when it is pressed, an LED connected to RC0 will be toggled ON and OFF.

Required Theory

You must be familiar with the digital I/O ports of PIC16F688 and their direction settings. If you are not, read Digital I/O Ports in PIC16F688.

Circuit Diagram

To our last setup (see Lab 1: Flashing an LED), connect a push button switch to RC1 as shown below. The input ports of a PIC microcontroller have very high input impedance, and therefore, during normal condition when the switch is open, the RC1 pin is pulled ‘High’ through the external 10K resistor. When the switch is pressed, RC1 is pulled to ground and the microcontroller will read it as logic ‘Low’. In this way, a simple push button switch with a pull-up resistor can be used to provide digital inputs (1 and 0) to the microcontroller.

Circuit for reading digital inputs.

Prototyped circuit on the breadboard

Software

Since the switch is connected to RC1, this port pin must be defined as input. This is done by setting the corresponding bit in the TRISC register. Again, don’t forget to disable the comparators and ADC channels. The code for this experiment is provided below. You should compile it with the MikroC compiler and load the output hex file inside the PICMicro. The MikroC compiler has an in-built library routine (named Button) for reading digital inputs from push button switches. The syntax is,

You can see that the Button command has debounce features built in.

Debouncing a switch

When a mechanical switch (like a push button) is pressed or released to make or break an electrical contact, the switch tends to make multiple transitions between ‘open’ and ‘close’ before coming to the stable final state. This is called switch bounce and this activity may go on for tens of milliseconds. We cannot see this bouncing but a microcontroller is relatively fast as compared to the action of the switch, and is, therefore, able to recognize this as multiple button presses and respond accordingly. Therefore, the switch must be debounced before it’s status is read by a microcontroller. Debouncing circuits require extra hardware and thus raises the cost of the embedded system. The easiest solution is to implement debouncing in software. The simplest logic is to wait for a few milliseconds (5-20 ms) after the key press or release is detected, and read the final state of the switch again to make sure it is a valid button press or release.

Note that the configuration bits setting is same as in Lab 1.

 /*
  Lab 2: Toggle LED with a Tact Switch Input
  Internal Oscillator @ 4MHz, MCLR Enabled, PWRT Enabled, WDT OFF
  Copyright @ Rajendra Bhatt
  Oct 8, 2010
 */
 // Define LED @ RC0 and Tact switch @ RC1
 sbit LED at RC0_bit;
 sbit Switch at RC1_bit;
 #define Switch_Pin 1
 #define Switch_Port PORTC
 #define Debounce_Time 20
 void main() {
 ANSEL = 0b00000000; //All I/O pins are configured as digital
 CMCON0 = 0x07 ; // Disbale comparators
 TRISC = 0b00000010; // PORTC All Outputs
 TRISA = 0b00001000; // PORTA All Outputs, Except RA3
 LED = 0;
 do {
  if (Button(&Switch_Port, Switch_Pin, Debounce_Time, 0)) {
    if (!Switch) {
    LED = ~LED;
    }
    while (!Switch); // Wait for release of the button
  }
 } while(1);  // Infinite Loop
}

Download the complete mikroC project files

Output

Every time the switch is pressed, the LED toggles ON and OFF. Once the switch is pressed, the microcontroller will wait for its release before it detects another press.

Related Posts

21 comments

  • Hi
    Could you please help me. I dont know enough about progrmming to write my own.
    I am using a pic16f877a and want to use MPLAB run the program.
    I want to light 3 leds with one input buttom. push button once lights led 1, push again will
    light led 1 and 2, push again will led 1+2+3, forth push will put out all leds.
    Using more than one buttin to light another 3 leds. If i use a 3x 10 led matrix with 10 input
    buttons or more.
    I know how to start the program and to program all input and output ports.
    Only one led must be lit at a time.
    Than you for a very informative tutorial.
    Thys

  • hi..hw shud i write my code and do connection in proteus if i using pic18f4520? thx

  • I have burned my simple led glowing program of MPLAB IDE v8.83(hightech C compiler ) of PIC 16F877A with Pickit3.And it is showing programming is successfully.But during hardware interfacing the led is not glowing .
    1. Board is well connected.
    2.Crystal oscillator frequency is 16MHz or 16.9344MHz
    What can be the error?
    If it is oscillator problem,how to check crystal oscillator is damaged or not?

    • My program: need to glow one led at pin RB1 connected with a resistor

      #include
      #define _XTAL_FREQ 16934400
      // #define __XTAL_FREQ 16000000
      void main(void)
      {
      TRISB=0x00;
      //PORTB=0x00;
      while(1)
      {
      PORTB=0xFF;
      __delay_ms(1000);

      //__delay_ms(1000);

      }

      }

    • Moumita- can you send code and hardware circuit diagram, then I can try,

  • Hi, how can i coding. using IC pic16f676

    input port
    RA0/AN0
    RA2/AN2
    RC0/AN4
    RA3

    And other port want output port
    RA5
    RA4
    RC5
    RC4
    RC3/AN7
    RC1/AN5
    RC2AN6

    anyone help?

  • sbit b at RB0_bit;
    sbit led at RA0_bit;
    sbit button_direction at TRISB0_bit;
    sbit led_direction at TRISA0_bit;
    void main() {
    if(b=0){
    PORTA=!PORTA;
    }

    while(1);

    }

    not working i want use push botton on port b0 and o/p on port a0

  • hi,
    please can i have more explanation about this
    if (!Switch) {
    LED = ~LED;
    }
    while (!Switch); // Wait for release of the button

    and why we use switch and while wethout do

  • hi i like your website.I need to use pic16F887 and what modifications do i have to apply in the code.
    It is better if you can list the components used in the design. thanks

  • Could you pls tell what this condition meant for

    if (Button(&Switch_Port, Switch_Pin, Debounce_Time, 0))

    and why y use this

    #define Switch_Pin 1
    #define Switch_Port PORTC
    #define Debounce_Time 20

  • R-B

    I tried to Flash a LED connected in RB0 (Pin 6) of PIC 16F628A and write following program in Micro C (getting idea from your example with PIC 16f688 LED Flashing)

    sbit LED at RB0_bit;
    void main()
    {
    CMCON = 0x07; //disable comparator
    TRISA= 0b00001000;
    TRISB =0b00000000;// PORTB all output
    do
    {
    LED = 1;
    Delay_ms(1000);
    LED= 0;
    Delay_ms(1000);
    }
    while (1); // infinite loop

    }

    Compilation done successfully and .HEX file downloaded but found LED glows contentiously , not flashing,

    I kept MCLR disable and 4 MHZ internal oscillator selection from MICRO C project editor and used “IC-Prog” (1.05D)- to download the .HEX file .
    Can you please help me , where I am doing wrong .
    Regards,
    Uttam
    NB:-can you provide attachment option with comment field

  • Pingback: Connecting multiple tact switches on a single input pin of a microcontroller » Hallo, here is Pane!

  • hello
    in mikroc pro this code give an error as “button” not defined.
    so i used #define button;
    but it is not working practically
    help plz

    regards and thanks

  • Pingback: Connecting multiple tact switches on a single input pin of a microcontroller » Geko Geek

  • hello sir all i can say is that ur doing a great job
    i complied the same the code in my micro c version 4.60
    but am getting these errors sir please give me correct solution
    am a novice to the microcontroller field

    0 1 mikroCPIC1618.exe -MSF -DBG -pP16F688 -DL -O11111114 -fo4 -N”F:\pic projects new(25.6.11)\just.mcppi” -SP”C:\Users\Public\Documents\Mikroelektronika\mikroC PRO for PIC\defs\” -SP”C:\Users\Public\Documents\Mikroelektronika\mikroC PRO for PIC\Uses\P16\” -SP”F:\pic projects new(25.6.11)\” “just.c” “__Lib_Math.mcl” “__Lib_MathDouble.mcl” “__Lib_System.mcl” “__Lib_Delays.mcl” “__Lib_CType.mcl” “__Lib_CString.mcl” “__Lib_CStdlib.mcl” “__Lib_CMath.mcl” “__Lib_Conversions.mcl” “__Lib_Sprinti.mcl” “__Lib_Sprintl.mcl” “__Lib_Time.mcl” “__Lib_Trigonometry.mcl” “__Lib_Button.mcl” “__Lib_Manchester.mcl” “__Lib_OneWire.mcl” “__Lib_PS2.mcl” “__Lib_Sound.mcl” “__Lib_SoftI2C.mcl” “__Lib_SoftSPI.mcl” “__Lib_SoftUART.mcl” “__Lib_ADC_A_B.mcl” “__Lib_EEPROM.mcl” “__Lib_FLASH_R.mcl” “__Lib_UART_c45.mcl” “__Lib_LcdConsts.mcl” “__Lib_Lcd.mcl” “__Lib_RS485.mcl”
    0 1139 Available RAM: 240 [bytes], Available ROM: 4096 [bytes]
    0 122 Compilation Started P16F688.c
    484 123 Compiled Successfully P16F688.c
    0 126 All files Preprocessed in 124 ms
    0 122 Compilation Started just.c
    9 304 Local variables can not be of sbit type just.c
    9 300 Syntax Error: ‘;’ expected, but ‘at’ found just.c
    9 424 ‘}’ expected ‘;’ found just.c
    9 1163 Variable ‘LED’ has been declared, but not used just.c
    26 371 Specifier needed just.c
    26 396 Invalid declarator expected'(‘ or identifier just.c
    26 371 Specifier needed just.c
    26 300 Syntax Error: ‘)’ expected, but ‘!’ found just.c
    27 371 Specifier needed just.c
    27 396 Invalid declarator expected'(‘ or identifier just.c
    28 371 Specifier needed just.c
    28 300 Syntax Error: ‘)’ expected, but ‘1’ found just.c
    28 312 Internal error ” just.c
    0 102 Finished (with errors): 25 Jun 2011, 17:54:45 just.mcppi

    • @Magesh,
      While copying and pasting the source code from website to mikroC editor, I have experienced formatting error a couple of times. So I have uploaded the entire mikroC project files (including source code), which you can download from the link provided in the software section.

  • What type of programmer are you using?
    is that from mikroE (mikroICD), the yellow one on the picture

  • Hi,
    I really liked your webiste as it provides not only the schematics but also the real arrangement of components. Simply a neat and clean work. Good job. Would you mind if I send you some of my own schematics and projects.

Leave a Reply to Avinash Kashyap Cancel reply

Your email address will not be published. Required fields are marked *