Skip to content

Instantly share code, notes, and snippets.

@hno
Last active June 28, 2022 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hno/cb74bbef2c3ce1bd4120a3200a81cde6 to your computer and use it in GitHub Desktop.
Save hno/cb74bbef2c3ce1bd4120a3200a81cde6 to your computer and use it in GitHub Desktop.
Arduino pump controller
const int SWITCH_1 = 2;
const int PUMP_1 = 12;
const int SWITCH_2 = 3;
const int PUMP_2 = 11;
const int SWITCH_3 = 4;
const int PUMP_3 = 10;
const int PUMP_OFF = 0;
const int PUMP_ON = 1;
const int SWITCH_ON = 0;
const int SWITCH_OFF = 1;
const long HOUR12 = ((long)12 * 3600 * 1000); // 12 hours as milliseconds
class PumpState {
private:
int gpio_switch;
int gpio_pump;
long timer; // millis at start of interval, signed makes delta arithemtics work correct
enum PUMP_STATE {
PUMP_STATE_RESET,
PUMP_STATE_OFF,
PUMP_STATE_RUN,
PUMP_STATE_IDLE,
} state;
void newState(enum PUMP_STATE next_state) {
timer = millis(); // reset timer
state = next_state;
}
void transitionToRun() {
newState(PUMP_STATE_RUN);
digitalWrite(gpio_pump, PUMP_ON);
}
void transitionToIdle() {
newState(PUMP_STATE_IDLE);
digitalWrite(gpio_pump, PUMP_OFF);
}
void transitionToOff() {
newState(PUMP_STATE_OFF);
digitalWrite(gpio_pump, PUMP_OFF);
}
long stateTimer() {
return millis() - timer;
}
bool stateTimeout(long msec) {
return stateTimer() > msec;
}
bool switchIsOn() {
return digitalRead(gpio_switch) == SWITCH_ON;
}
bool switchIsOff() {
return digitalRead(gpio_switch) == SWITCH_OFF;
}
public:
PumpState(int switch_in, int pump_out)
{
gpio_switch = switch_in;
gpio_pump = pump_out;
newState(PUMP_STATE_RESET);
}
void setup()
{
pinMode(gpio_switch, INPUT);
pinMode(gpio_pump, OUTPUT);
digitalWrite(gpio_pump, PUMP_OFF);
}
void loop()
{
switch (state) {
case PUMP_STATE_RESET:
transitionToOff();
break;
case PUMP_STATE_OFF:
if (switchIsOn()) {
transitionToRun();
break;
}
break;
case PUMP_STATE_RUN:
if (switchIsOff()) {
transitionToOff();
break;
}
if (stateTimeout(HOUR12)) {
transitionToIdle();
break;
}
break;
case PUMP_STATE_IDLE:
if (switchIsOff()) {
transitionToOff();
break;
}
if (stateTimeout(HOUR12)) {
transitionToRun();
break;
}
break;
}
}
};
PumpState pump1(SWITCH_1, PUMP_1);
PumpState pump2(SWITCH_2, PUMP_2);
PumpState pump3(SWITCH_2, PUMP_3);
void setup() {
pump1.setup();
pump2.setup();
pump3.setup();
}
void loop() {
pump1.loop();
pump2.loop();
pump3.loop();
// slow down the Arduino a bit. Not strictly needed but handles switch debounce and
// can make the code more power friendly on some CPUs.
delay(50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment