
Chapter 7. Basic Experiments
7.3. Experiment with Keys
Key is most often used in interface between human and MCU system. Generally, there are two types of keys, independent key and matrix key.

In this experiment, we work with the independent key. We’ll use SW1 and SW2 to control the on off status of LED.


Key is a 4-terminal component in appearance, but actually 2 terminals are necessary. When the key is not depressed, none of the 4 terminals are connected. But when the key is pressed, there are 2 pairs of terminals being connected.
As we know, there are pull-up resistors inside the P1 port. When no external operation is exercised on the P1 port, the logical level of P1 is high. If we connect a key to any of the P1 pin, due to the disconnection of the key itself, P1 is still high level. To know when and if the key is depress, check the P1 port.
For example, if a key is connected to P1.4 and VSS. When we press the key, the P1.4 will be shortcut to VSS. Reading P1.4 at this time will get low level. When the key is not depressed, P1.4 will still be high.

01 #include <reg51.h>
02
03 sbit SW1 = P1^4;
04 sbit SW2 = P1^7;
05 sbit LED = P2^0;
06
07 void main()
08 {
09 P1 = 0xff;
10 P2 = 0xff;
11 while(1)
12 {
13 if(SW1==0) LED = 0;
14 if(SW2==0) LED = 1;
15 }
16 }
Program Notes
Line 1: include the 8051 register definition header file
Line 3: sbit define SW1 to P1.4
Line 4: sbit define SW1 to P1.7
Line 5: sbit define LED to P2.0
Line 7-16: main function
Line 9-10: initialize I/O port
Line 11-15: loop
Line 13: if SW1 is depressed, lights up the LED
Line 14: if SW2 is depressed, lights off the LED
So far, the above program runs pretty cool. But if we need to control the LED by only SW1, what should we do?
To switch between on and off state, not operand can be used. So, line 13 and 14 of the above codes, can be changed to
if(SW1==0) LED = !LED;
If we test this program, we will see that LED’s on off status is not stable. It’s because the MCU runs so fast that the statement LED = !LED has been executed more than once when we press the key. Normally, one press on key lasts over 200ms, while the MCU only spend 20us to execute the LED = !LED statement.
There are many tricks can be used to solve the problem. A delay can be inserted during the I/O port check. Or, we can count the times of depressed key. Here in this experiment, we postpone the key pressing function until the key is released.
#include <reg51.h>
sbit SW1 = P1^4;
sbit SW2 = P1^7;
sbit LED = P2^0;
void main()
{
P1 = 0xff;
P2 = 0xff;
while(1)
{
if(SW1==0) //if SW1 is depressed
{
if(SW1==1) //if SW1 is released
{
LED = !LED;
}
}
}
} |