I'm creating my own library in arduino to controlling a pump. The library is very simple:
Pump.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
#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. What's wrong with my code?
Your PUMP1.IsOpen()
simply creates a temporary object of Pump
class that is immediately destroyed.
You need to create an object of Pump
that live throughout the execution of program. 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)