赞
踩
1、青铜示例:
- #include <stdio.h>
-
- enum {
- LED1,
- LED2,
- LED3,
- LED_NUM
- };
-
- void Func_LED1(unsigned char state);
- void Func_LED2(unsigned char state);
- void Func_LED3(unsigned char state);
-
- /**
- * 函数指针数组定义格式
- * 函数返回类型 (*指针变量名[数组大小])(函数参数列表);
- * @param state
- * @return
- *
- */
- void (*func[LED_NUM])(unsigned char state) = {Func_LED1, Func_LED2, Func_LED3};
-
- void Func_LED1(unsigned char state)
- {
- if (state)
- printf("LED1 ON\r\n");
- else
- printf("LED1 OFF\r\n");
- }
-
- void Func_LED2(unsigned char state)
- {
- if (state)
- printf("LED2 ON\r\n");
- else
- printf("LED2 OFF\r\n");
- }
-
- void Func_LED3(unsigned char state)
- {
- if (state)
- printf("LED3 ON\r\n");
- else
- printf("LED3 OFF\r\n");
- }
-
- int main() {
-
- // for (int i = 0; i < LED_NUM; ++i) {
- // func[i](1);
- // }
-
- func[LED1](1);
- func[LED2](1);
- func[LED3](1);
-
- return 0;
- }
运行结果:
2、白银示例:
key.h文件
- //
- // Created by champion on 2021/11/30.
- //
-
- #ifndef UNTITLED1_KEY_H
- #define UNTITLED1_KEY_H
-
- typedef enum {
- KEY1,
- KEY2,
- KEY_NUM,
- }KEY_ID_TYDEF;
-
- typedef enum {
- KEY_IDLE, //空闲
- KEY_PRESS, //短按
- KEY_LONG_PRESS, //长按
- KEY_RELEASE, //释放
- }KEY_STATE_TYDEF;
-
-
-
-
- typedef void (*pKeyScanCallBack) (KEY_ID_TYDEF KEY_ID, KEY_STATE_TYDEF KEY_STATE);
-
- void keyScanCBRegister(pKeyScanCallBack pCB);
- void keyInit(void);
- void keyPoll(void);
-
- #endif; //UNTITLED1_KEY_H
key.c文件
- //
- // Created by champion on 2021/11/30.
- //
- #include <stdio.h>
- #include "key.h"
-
- KEY_ID_TYDEF keyID;
- KEY_STATE_TYDEF keyState;
- pKeyScanCallBack pkeyScanCB;
-
-
- void keyInit(void)
- {
- keyID = 0;
- keyState = KEY_IDLE;
- pkeyScanCB = NULL;
- }
-
- void keyScanCBRegister(pKeyScanCallBack pCB)
- {
- if (pkeyScanCB == NULL) {
- pkeyScanCB = pCB;
- }
- }
-
-
- void keyPoll(void)
- {
- printf("Please Enter key ID: \r\n");
- if (scanf("%d", &keyID) == 1) {
- printf("\r\n");
- printf("Please Enter key state: \r\n");
- if (scanf("%d", &keyState) == 1) {
- //keyScanHandle(keyID, keyState) 这里相当于下面这句话,通过这样的方法,封装好硬件层于应用层的API
- if (pkeyScanCB != NULL) {
- pkeyScanCB(keyID, keyState);
- }
- }
- }
- }
main.c文件
- #include <stdio.h>
- #include "key.h"
- #include "stdint.h"
-
- typedef struct {
- uint8_t value;
- void (*run_func)(void);
- }FuncTYpedef;
-
-
- void keyScanHandle(KEY_ID_TYDEF KEY_ID, KEY_STATE_TYDEF KEY_STATE)
- {
- printf("KEY_ID :%d, KEY_STATE :%d \r\n", KEY_ID, KEY_STATE);
- }
-
-
- void run_fun(void)
- {
- keyInit();
- keyScanCBRegister(keyScanHandle);
- keyPoll();
- }
-
- int main() {
-
- /**
- * 定义结构体变量
- * */
- FuncTYpedef init_fun = {
- .value = 10,
- .run_func = run_fun,
- };
- init_fun.value = 100;
- init_fun.run_func();
-
- /**
- * 结构体变量指针变量
- */
- // FuncTYpedef *pFun = {
- // // pFun->value = 0,
- // pFun->run_func = run_fun,
- // };
- // pFun->value = 200;
- // pFun->run_func();
-
- return 0;
- }
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。