C++/Arduino:如何从子类访问对象



我在Ardunio上附加了一个移位寄存器,并为它创建了一个自己的类

ShiftRegister myRegister;
//myRegister.begin(int arduinoPin, int state);
myRegister.begin(int 8, int LOW);
myRegister.write(1, HIGH);

到目前为止,这还可以。通过调用begin((方法,我得到了带有8个自己引脚的Shift Register对象。我可以通过write((方法(在这种情况下是移位寄存器的引脚1(直接切换移位寄存器的输出。

现在,将一个设备连接到移位寄存器。我通过从主文件创建它

Device myDevice;
myDevice.switchOn();

我需要告诉设备,它连接到哪个移位寄存器引脚。类似的东西

myDevice.begin(5);

之后,我只想调用函数myDevice.switchOn((来打开设备。所以我不想直接通过

myRegister.write(5,HIGH(我如何让类设备做到这一点?到目前为止,这个类对移位寄存器一无所知。通过指针?具体的方法是什么?

我对C++/Arduino还很陌生,所以请原谅我,以防这可能是一个微不足道的问题。此外,我对面向对象编程还不太深入。。。

我不熟悉arduino组件,但。。

您可以扩展设备类别:

class DeviceWithShiftReference: public Device{
private: ShiftRegister * myShiftReference;
public: DeviceWithShiftReference(ShiftRegister* reg) {
myShiftReference = reg
}
public: doSomething() {
// here you can perform stuff with the shift register inside your device 
}
};
void main(void){
ShiftRegister myRegister;
DeviceWithShiftReference myDevice(&myRegister);
myDevice.doSomething();
}

通过这种方式,您可以在类中保留对寄存器的引用,从doSomething((中,您可以尊重myShiftReference并使用执行操作

myShiftRegister->begin( ... )

您可以向Device类构造函数添加两个参数,一个参数是指向ShiftRegister对象的指针,另一个参数则是它所在的引脚。这两个参数可以在对象内部保存。

class Device 
{
public:
Device(ShiftRegister *pReg, int iPin)
{
reg = pReg;
pin = iPin;
}
private:
int pin;
ShiftRegister *reg;
}  

然后你可以做

ShiftRegister myRegister;
myRegister.initStuff(...);
Device  myDevice(&myRegister, 5);
.
.
myDevice.switchOff();  // Uses the saved pin value
myDevice.switchOn();

最新更新