位运算:更加简便,单片机的内存就小,占的内存空间小一点
案例:
# include "GPIO.h"
# include "Delay.h"
# include "UART.h"
# include "NVIC.h"
# include "Switch.h"
# define KEY1 P51
# define KEY2 P52
# define KEY3 P53
# define KEY4 P54
# define DOWN 0
# define UP 1
u8 last_state = 0x0f ;
# define IS_KEY_UP ( i) ( ( last_state >> i & 1 ) == 1 )
# define IS_KEY_DOWN ( i) ( ( last_state >> i & 1 ) == 0 )
# define SET_KEY_UP ( i) ( last_state |= ( 1 << i) )
# define SET_KEY_DOWN ( i) ( last_state &= ~ ( 1 << i) ) void GPIO_config ( ) { GPIO_InitTypeDef info; info. Mode = GPIO_PullUp; info. Pin = GPIO_Pin_0 | GPIO_Pin_1; GPIO_Inilize ( GPIO_P3, & info) ; P5_MODE_IO_PU ( GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4) ;
}
void UART_config ( void ) { COMx_InitDefine COMx_InitStructure; COMx_InitStructure. UART_Mode = UART_8bit_BRTx; COMx_InitStructure. UART_BRT_Use = BRT_Timer1; COMx_InitStructure. UART_BaudRate = 115200ul ; COMx_InitStructure. UART_RxEnable = ENABLE; COMx_InitStructure. BaudRateDouble = DISABLE; UART_Configuration ( UART1, & COMx_InitStructure) ; NVIC_UART1_Init ( ENABLE, Priority_1) ; UART1_SW ( UART1_SW_P30_P31) ;
} void main ( ) { EA = 1 ; GPIO_config ( ) ; UART_config ( ) ; while ( 1 ) { if ( IS_KEY_UP ( 0 ) && KEY1 == DOWN) { SET_KEY_DOWN ( 0 ) ; printf ( "key1按下\n" ) ; } else if ( IS_KEY_DOWN ( 0 ) && KEY1 == UP) { SET_KEY_UP ( 0 ) ; printf ( "key1抬起\n" ) ; } if ( IS_KEY_UP ( 1 ) && KEY2 == DOWN) { SET_KEY_DOWN ( 1 ) ; printf ( "key2按下\n" ) ; } else if ( IS_KEY_DOWN ( 1 ) && KEY2 == UP) { SET_KEY_UP ( 1 ) ; printf ( "key2抬起\n" ) ; } if ( IS_KEY_UP ( 2 ) && KEY3 == DOWN) { SET_KEY_DOWN ( 2 ) ; printf ( "key3按下\n" ) ; } else if ( IS_KEY_DOWN ( 2 ) && KEY3 == UP) { SET_KEY_UP ( 2 ) ; printf ( "key3抬起\n" ) ; } if ( IS_KEY_UP ( 3 ) && KEY4 == DOWN) { SET_KEY_DOWN ( 3 ) ; printf ( "key4按下\n" ) ; } else if ( IS_KEY_DOWN ( 3 ) && KEY4 == UP) { SET_KEY_UP ( 3 ) ; printf ( "key4抬起\n" ) ; } delay_ms ( 50 ) ; }
}