Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

I. Introduction of key functions and schematic diagram

In the process of learning microcontroller, embedded; Key is a peripherals must learn, common keys are divided into independent keys, matrix keys and so on. The following is an independent button, the principle is relatively simple, just need to configure the IO port connected with the single chip microcomputer into the input mode, and then constantly detect the state of the key, according to the schematic analysis can know in advance what state the key idle and press, the program detected after the corresponding processing can be.

Second, GPIO port input mode configuration

When the GPIO port is used for key detection, you need to set the mode to input mode. The detailed configuration steps are shown in the following screenshots, and each function bit is described in detail in the manual.

Core code

#include <ioCC2530.h>

// Define the LED light port
#define LED1 P1_2
#define LED2 P1_3

// Define the port for the KEY
#define KEY1 P1_0       // Define the key as P1_0 port control
#define KEY2 P1_1       // Define the button as port P1_1 control

/* Initialize hardware connection: LED1-->P1_2, LED2-->P1_3 */
void LED_Init(void)
{
    P1DIR |=0x3<<2;  // Set P1_2 and P1_3 as output modes
    LED1 = 1;
    LED2 = 1;
}

/* Key IO port initialization hardware connection: KEY1-->P1_0 KEY2-->P1_1 */
void KEY_Init(void)
{
    P1SEL&=~(0x3<<0); // Configure P1_0 so that P1_1 is in general GPIO port mode
    P1DIR&=~(0x3<<0); // Set P1_0 with P1_1 as the input mode
    P1INP|= 0x3<<0;   / /
}


void delay10ms(void)   / / error 0 us
{
    unsigned char a,b,c;
    for(c=193; c>0; c--)for(b=118; b>0; b--)for(a=2; a>0; a--); }/* Function function: key scan return value: pressed key value */
unsigned char Key_Scan(void)
{
    static unsigned char stat=1;
    if((KEY1==0||KEY2==0)&&stat)
    {
       stat=0;
       delay10ms(a);if(KEY1==0)return 1;
       if(KEY2==0)return 2;
    }
    else
    {
        if(KEY1&&KEY2)stat=1;
    }
    return 0;
}

/* Main function */
void main(void)
{
    unsigned char key;
    LED_Init(a);// Initializes the LED control IO port
    KEY_Init(a);// Key initialization
    while(1)          
    {  
       key=Key_Scan(a);if(key)
       {
          LED1 = !LED1;     
          LED2 = !LED2;
       }       
    }
}

Copy the code

After writing, compile, download, and test the keys