一、在controlDevices.h中
struct Devices
{
char deviceName[128];
int status;
int pinNum;
int (*open)(int pinNum);
int (*close)(int pinNum);
int (*deviceInit)(int pinNum);
int (*readStatus)(int pinNum);
int (*changeStatus)(int status);
struct Devices *next;
};
struct Devices *addBathroomLightToDeviceLink(struct Devives *phead)
二、在bathroomLight中
#include "controlDevices.h"
#include<stdlib.h>
//在controlDevice.h中声明了变量和函数指针
int bathroomLightOpen(int pinNum)
{
digitalWrite(pinNum,LOW);
}
int bathroomLightClose(int pinNum)
{
digitalWrite(pinNum,HIGH);
}
int bathroomLightCloseInit(int pinNum)
{
pinMode(pinNum,OUTPUT);
digitalWrite(pinNum,HIGH);
}
int bathroomLightCloseStatus(int status)
{
}
struct Devices bathroomLight={
.deviceName = "bathroomLight",
.pinNum = 22,
.open = bathroomLightOpen,
.close = bathroomLightClose,
.deviceInit = bathroomLightCloseInit,
.changeStatus = bathroomLightCloseStatus
};
//属于链表,插入一个bathroomLight节点,属于头插法
struct Devices *addBathroomLightToDeviceLink(struct Devives *phead)
{
if(phead == NULL)
{
return &bathroomLight;
}
else{
bathroomLight.next = phead;
phead = &bathroomLight;
}
};
三、写一个测试主函数,在mainpro.c中
#include<stdio.h>
#include"controlDevices.h"
#include<string.h>
struct Device *findDeviceByName(char *name,struct Devices *phead)
{
structmpt Devices *tmp = phead;
if(phead == NULL)
{
return NULL;
}
else{
while(tmp!=NULL)
{
if(strcmp(tmp->devicename , name){
return tmp;
}
tmp = tmp->next;
}
return NULL;
}
}
int main()
{
char *name = "bathroomLight";
struct Devices *pdeviceHead = NULL;
pdeviceHead = addBathroomLightToDeviceLink(pdeviceHead)
struct Devices *tmp = findDeviceByName(name,pdeviceHead);
if(tmp !=NULL)
{
tmp->deviceInit(tmp->pinNum);
tmp->open(tmp->pinNum);
}
}
总体流程是这样:定义一个bathroomLight,将bathroomLight节点加到链表里面,通过名字在链表里面找就是遍历链表,找到了就先初始化然后打开灯。