电路分析
- 引脚为P37
- 开关未按下时,P37是高电平
- 开关按下时,GND导通,P37是低电平
编程思路
- Driver目录中添加KEY.h文件,应包含引脚定义、开关GPIO实例化函数、开关状态获取函数以及当按下和未按下时执行不同的函数(函数指针作为函数参数)
- Driver目录中添加KEY.c文件,做具体实现
代码示例
KEY.H
#ifndef __KEY_H
#define __KEY_H
#include "GPIO.h"#define KEY_PIN P37void KEY_init();
void Key_Get_State(void(*keydown)(),void(*keyup)());#endif
KEY.C
#include "Key.h"void KEY_init(){GPIO_InitTypeDef GPIO_InitStructure; //结构定义GPIO_InitStructure.Pin = GPIO_Pin_7; //指定要初始化的IO,GPIO_InitStructure.Mode = GPIO_OUT_PP; //指定IO的输入或输出方式,GPIO_PullUp,GPIO_HighZ,GPIO_OUT_OD,GPIO_OUT_PPGPIO_Inilize(GPIO_P3, &GPIO_InitStructure);//初始化}
u8 last_state=1;
void Key_Get_State(void(*keydown)(),void(*keyup)()){if (last_state==1&& KEY_PIN==0){if(keydown != NULL){keydown();}last_state=0;}else if(last_state==0&& KEY_PIN==1){if(keyup != NULL){keyup();}last_state=1;}
}
main.c
#include "RTX51TNY.h"
#include "GPIO.h"
#include "NVIC.h"
#include "UART.h"
#include "Switch.h"
#include "LED.h"
#include "Key.h"#define TASK_MAIN 0
#define TASK_LED 1
#define TASK_KEY 2void UART_config(void) {// >>> 记得添加 NVIC.c, UART.c, UART_Isr.c <<<COMx_InitDefine COMx_InitStructure; //结构定义COMx_InitStructure.UART_Mode = UART_8bit_BRTx; //模式, UART_ShiftRight,UART_8bit_BRTx,UART_9bit,UART_9bit_BRTxCOMx_InitStructure.UART_BRT_Use = BRT_Timer1; //选择波特率发生器, BRT_Timer1, BRT_Timer2 (注意: 串口2固定使用BRT_Timer2)COMx_InitStructure.UART_BaudRate = 115200ul; //波特率, 一般 110 ~ 115200COMx_InitStructure.UART_RxEnable = ENABLE; //接收允许, ENABLE或DISABLECOMx_InitStructure.BaudRateDouble = DISABLE; //波特率加倍, ENABLE或DISABLEUART_Configuration(UART1, &COMx_InitStructure); //初始化串口1 UART1,UART2,UART3,UART4NVIC_UART1_Init(ENABLE,Priority_1); //中断使能, ENABLE/DISABLE; 优先级(低到高) Priority_0,Priority_1,Priority_2,Priority_3UART1_SW(UART1_SW_P30_P31); // 引脚选择, UART1_SW_P30_P31,UART1_SW_P36_P37,UART1_SW_P16_P17,UART1_SW_P43_P44
}void task_led() _task_ TASK_LED{while(1){// leftLED_ON(left);os_wait2(K_TMO, 100);LED_OFF(left);os_wait2(K_TMO, 100);// rightLED_ON(right);os_wait2(K_TMO, 100);LED_OFF(right);os_wait2(K_TMO, 100);// Hazard lightsLED_ON(all);os_wait2(K_TMO, 100);// all offLED_OFF(all);os_wait2(K_TMO, 100);}
}void keydown(){printf("key down");
}void keyup(){printf("key up");
}void task_key() _task_ TASK_KEY{KEY_init();while(1){Key_Get_State(keydown,keyup);os_wait2(K_TMO, 4);}
}void task_main() _task_ TASK_MAIN{EA=1;//LED_init();UART_config();// os_create_task(TASK_LED);os_create_task(TASK_KEY);os_delete_task(0);
}