简体   繁体   English

从 Arduino 库中的方法获取私有 bool 属性

[英]Getting private bool property from method in Arduino library

I'm creating my own library in arduino to controlling a pump.我正在 arduino 中创建自己的库来控制泵。 The library is very simple:该库非常简单:


Pump.h泵.h

#ifndef Pump_h
#define Pump_h

#include "Arduino.h"

class Pump
{
  public:
    Pump(int pin);
    void Open(void);
    void Close(void);
    boolean IsOpen(void);
  private:
    int _pin;
    bool _status;
};

#endif

Pump.cpp泵.cpp


#include "Arduino.h"
#include "Pump.h"

Pump::Pump(int pin)
{
  pinMode(pin, OUTPUT);
  digitalWrite(pin,HIGH);
  _pin = pin;
  _status = false;
}

void Pump::Open(void)
{
  digitalWrite(_pin, LOW);
  _status = true;
}

void Pump::Close(void)
{
  digitalWrite(_pin, HIGH);
  _status = false;
}

boolean Pump::IsOpen(void)
{
  return _status;
}

loop()环形()


#include <Pump.h>
#define PUMP1 Pump(9)

void loop() {
  BridgeClient client = server.accept(); // Get clients coming from server
  if (client) {  // There is a new request from client?
    Console.println("Client connected");
    process(client);  // Process request
    client.stop();    // Close connection and free resources.
  }
  Console.println(PUMP1.IsOpen());
  delay(50); // Poll every 50ms
}

The problem is that when I call the function IsOpen inside the loop() function of Arduino I get always false and the Pump is immediately turned off.问题是,当我在 Arduino 的 loop() 函数中调用函数 IsOpen 时,我总是错误,并且泵会立即关闭。 What's wrong with my code?我的代码有什么问题?

Your PUMP1.IsOpen() simply creates a temporary object of Pump class that is immediately destroyed.您的PUMP1.IsOpen()只是创建一个Pump类的临时对象,该对象会立即被销毁。

You need to create an object of Pump that live throughout the execution of program.您需要创建一个在程序执行过程中一直存在的Pump对象。 I am not familiar with Arduino call flow, but you could achieve this with some initialization/setup method or use singleton design or for this simple use case create a global object of Pump (which I normally don't educate people and is against using such design)我不熟悉 Arduino 调用流程,但您可以通过一些初始化/设置方法或使用单例设计或为这个简单的用例创建一个Pump的全局对象(我通常不教育人们并且反对使用这样的设计)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM