本帖最后由 与龙共舞 于 2018-5-3 14:09 编辑
上一篇是我自己抽象的逻辑,现在想直接看看别人怎么写的。
理解也进一步加深了。
第一步:框架
beeper.h- //常量结构体
- typedef const struct _BeepConstType{
- void (*BeepOn)(void);
- void (*BeepOff)(void);
- }BeepConstType, *PBeeperConst;
- //变量结构体
- typedef struct _BeepVarType{
- WORD wTon, wToff;
- volatile BYTE ucCnt, ucGpCnt;
- volatile WORD* pwTbl;
- volatile WORD w1msCnt;
- volatile BeepStateType Status;
- }BeepVarType, *PBeeperVar;
- //类结构体
- typedef const struct _BeeperType{
- PBeeperConst pConst;
- PBeeperVar pVar;
- }BeeperType, *PBeeper;
复制代码
_ 开头的是结构体名称 并不重要可以不要
Type 结尾的是结构体名称
*P 开头的是结构体指针名称,它和上面是一对儿
g 开头的是实例
P 开头的是类型名称
第三步:使用
先说我们最后的期望是什么 就是下面这样
用BeeperType实例化一个对象,然后用指针PBeeper gpBeeper指向它。
叫做句柄。
看到
gBeepConst
gBeepVar
所以需要实例他们
- //类结构体
- BeeperType gBeeper =
- {
- &gBeepConst, //PBeepConst pConst;
- &gBeepVar //PBeepVar pVar;
- };
- //句柄
- PBeeper gpBeeper = &gBeeper;
复制代码
第二部:实例化
- void McuSetLed1 ( void )
- {
- GPIO_SetBits ( Red_GPIO_PORT, Red_GPIO_PIN );
- }
- void McuClrLed1 ( void )
- {
- GPIO_ResetBits ( Red_GPIO_PORT, Red_GPIO_PIN );
- }
- BeepConstType gLed1Const =
- {
- McuSetLed1, //void (*BeepOn)(void);
- McuClrLed1 //void (*BeepOff)(void);
- };
- BeepVarType gLed1Var;
- //类结构体
- BeeperType gLed1 =
- {
- &gLed1Const, //PBeepConst pConst;
- &gLed1Var //PBeepVar pVar;
- };
- //句柄
- PBeeper gpLed1 = &gLed1;
复制代码 主要是用句柄拿到了对象全部的属性。
到这里就差不多了,可以看到方法已经填充好了。数据成员现在没有处理
看第一个函数吧。
void BeepLedInit ( void )
{
BeepInit ( gpLed1 );
BeepInit ( gpLed2 );
BeepInit ( gpLed3 );
BeepInit ( gpBeeper );
}
哈哈
//初始化函数
void BeepInit ( PBeeper pBp )
{
pBp->pConst->BeepOff();
pBp->pVar->wTon = 0;
pBp->pVar->wToff = 0;
pBp->pVar->pwTbl = NULL;
pBp->pVar->ucCnt = 0;
pBp->pVar->ucGpCnt = 0;
pBp->pVar->w1msCnt = 0;
pBp->pVar->Status = BPS_IDLE;
}
|
原来不是我一个人看不懂呀 这就放心了