从Arduino IDE中的类中读取和写入值

Read and write values from a Class in arduino IDE

本文关键字:读取 Arduino IDE      更新时间:2023-10-16

我正在使用一个计时器库,该计时器库具有一个void函数作为参数以在一定时间后执行它的函数。我想使用一个函数,该函数根据我在变量中初始化的设备上写入值。

我以为我可以使用类存储特定的别针,然后从类中读取PIN并使用读取类中的PIN的功能,而不是将参数传递给函数,因为计时器库不接受带有参数的void函数。

class output_control{
  int pin;
  void output_on();
 };
void output_control::output_on(){
digitalWrite(pin,HIGH);  //Just an example 
}

我遇到的麻烦是在此类中声明带有10个"设备"的数组,然后将值分配给我在类中的整数变量" pin"。

output_control device[10];
device.pin[1]=6;
device.pin[2]=5;

我认为我正在误解类,IDE输出了错误:"'indevice'in Device'的请求是非类型'output_control [10]',我想要的东西能够阅读从我在类中创建的变量中,我创建的void函数能够读取这些值以与它们一起运行某些操作并在类的变量上写入值,以便我可以在某些任务中使用它们。

使用Arduino/接线的类可能会变得棘手。

对于您的任务,编写一个函数来设置PIN应该有效(以及良好的实践 - 整个封装的东西)。下面的代码编译(尽管我没有运行)。

虽然小心Arduino上的课程 - 有时没有太多的记忆可使用,因此,更清洁,更明显的方法无法正常工作,并且需要诉诸于存储阵列并使用许多变量。

class output_control{
public:
  void  output_on(){
    digitalWrite(_pin,HIGH);  //Just an example 
  }
  void  setPin(int p){
    _pin = p;
  }
  private:
   int _pin;
};

output_control device[10]; // declare the array of objects
void setup(){
  //init the variables
  device[0].setPin(6);
  device[1].setPin(7);
}
void loop(){
 // do some stuff

}