Week 16

H2Gen: Embedded Programming

#include <Debounce_Trigger.h>
#include <Oled_Console.h>
#include <Rotary_Encoder.h>

#define BUFFER_FULL D3
#define BUFFER_EMPTY D0
Debounce_Trigger buf_f(BUFFER_FULL);
Debounce_Trigger buf_e(BUFFER_EMPTY);

#define SCREEN_I2C_ADDR 0x3C
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Oled_Console console(SCREEN_WIDTH, SCREEN_HEIGHT);

#define SW D8
Debounce_Trigger btn(SW);

#define ELECTROLYZER_RELAY D7
#define COMPRESSOR_RELAY D6

void setup() {
  console.begin(115200, SCREEN_I2C_ADDR);
  console.print("System initialized");

  pinMode(ELECTROLYZER_RELAY, OUTPUT);
  pinMode(COMPRESSOR_RELAY, OUTPUT);

  console.print("Starting electrolyzer");
  digitalWrite(ELECTROLYZER_RELAY, HIGH);
}

byte cycle = 0;
bool compressing = false;

void loop() {
  if (cycle < 3) {
    delay(10000);
    compressingHydrogen();
    delay(1500);
    generateHydrogen();
  }

  // Buffer Full
  buf_f.debounce([]() {
    if (cycle >= 3)
      return;

    console.print("Compressing air from buffer to canister");
    digitalWrite(ELECTROLYZER_RELAY, LOW);
    digitalWrite(COMPRESSOR_RELAY, HIGH);
    compressing = true;
  });

  // Buffr Empty
  buf_e.debounce([]() {
    if (!compressing)
      return;
    
    console.print("Shutting down compressor");
    digitalWrite(COMPRESSOR_RELAY, LOW);
    compressing = false;

    cycle++;
    
    if (cycle >= 3) {
      console.print("Canister is full!");
      return;
    }

    console.print("Restart electrolyzer");
    digitalWrite(ELECTROLYZER_RELAY, HIGH);
  });

  // Reset Button
  btn.debounce([]() {
    cycle = 0;
    console.print("Retarting cycle");
    digitalWrite(ELECTROLYZER_RELAY, HIGH);
  });
}

void compressingHydrogen() {
  if (cycle >= 3)
      return;

    console.print("Compressing air from buffer to canister");
    digitalWrite(ELECTROLYZER_RELAY, LOW);
    digitalWrite(COMPRESSOR_RELAY, HIGH);
    compressing = true;
}

void generateHydrogen() {
  if (!compressing)
      return;
    
    console.print("Shutting down compressor");
    digitalWrite(COMPRESSOR_RELAY, LOW);
    compressing = false;

    cycle++;
    
    if (cycle >= 3) {
      console.print("Canister is full!");
      return;
    }

    console.print("Restart electrolyzer");
    digitalWrite(ELECTROLYZER_RELAY, HIGH);
}