#include <Button.h>

// all the physical connection of the push button, loads and FLS

const int tank1Pin = 4;
const int tank2Pin = 5;
const int buttonPin = 9;
const int ledButtonPin = 10;
const int flowPin = 3;

const unsigned long TANK1_MAX = 5;    // capacity of maximum mL tank1_max
const unsigned long TANK2_MAX = 7;    // capacity of maximum mL tank2_max

typedef enum {
  IDLE,
  TANK1,
  TANK2
} MachineState;
MachineState state = IDLE;

volatile unsigned long pulseCounter;          // this integer needs to be set as volatile to ensure it updates correctly during the interrupt process.

Button button(buttonPin);

//========================================

void setup() {
  Serial.begin(9600);
  Serial.println("Machine started");       // so we know what sketch is running

  button.begin();
  pinMode(tank1Pin, OUTPUT);
  pinMode(tank2Pin, OUTPUT);
  pinMode(ledButtonPin, OUTPUT);

  pinMode(flowPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(flowPin), isrCount, RISING);     // interrupt programme when signal to pin 3 detected (1 = pin 3)
}

//========================================

void stopMachine() {
  Serial.println("Stopping machine");
  noInterrupts();
  digitalWrite(tank1Pin, LOW);
  digitalWrite(tank2Pin, LOW);
  digitalWrite(ledButtonPin, LOW);
  state = IDLE;
  interrupts();
}

void fillTank1() {
  Serial.println("Filling tank 1");
  noInterrupts();
  digitalWrite(ledButtonPin, HIGH);
  digitalWrite(tank1Pin, HIGH);
  state = TANK1;
  pulseCounter = 0;
  interrupts();
}

void fillTank2() {
  Serial.println("Filling tank 2");
  noInterrupts();
  digitalWrite(tank1Pin, LOW);
  digitalWrite(tank2Pin, HIGH);
  state = TANK2;
  pulseCounter = 0;
  interrupts();
}

void loop() {
  bool buttonDown = button.pressed();

  switch (state) {
    case IDLE:
      if (buttonDown) {
        fillTank1();
      }
      break;

    case TANK1:
      if (buttonDown) {
        stopMachine();
      } else if (pulseCounter == TANK1_MAX) {
        fillTank2();
      }
      break;

    case TANK2:
      if (buttonDown || pulseCounter == TANK2_MAX) {
        stopMachine();
      }
      break;
  }
}

void isrCount() {
  pulseCounter++;
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
led1:A
led1:C
led2:A
led2:C
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
btnFlow:1.l
btnFlow:2.l
btnFlow:1.r
btnFlow:2.r
ledbtn1:A
ledbtn1:C