Lab 2: Basic digital input and output
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.
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.
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.
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,
Debouncing a switchWhen 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.
For more detail: Lab 2: Basic digital input and output
EasyEDA: Ideas for Circuit Design, Innovation for Electronics Access
Free Circuit Design: Schematic – Simulation – PCB Layout – Gerber Viewer
Cheapest PCB Prototype: Only $2 for 10pcs 10×10cm PCBs, 24 hours Quick Turn, DHL Delivery in 3 Days