brew.ino 63 KB
Newer Older
João Lino's avatar
Rel.3  
João Lino committed
1 2 3 4 5
/*
  brew.ino - Main execution file.
  Created by João Lino, August 28, 2014.
  Released into the public domain.
*/
6

João Lino's avatar
Rel.3  
João Lino committed
7
#define DEBUG
8

9
// ######################### LIBRARIES #########################
João Lino's avatar
João Lino committed
10
#include "brew.h"
11

12
// ######################### VARIABLES #########################
13
// ++++++++++++++++++++++++ State Machine ++++++++++++++++++++++++
14
eRotaryEncoderMode      rotaryEncoderMode;
João Lino's avatar
Rel.3  
João Lino committed
15 16 17 18 19 20

eCookingStages          cookingStage;
eBeerProfile            beerProfile;

eMenuType               eMenuType;

João Lino's avatar
João Lino committed
21 22 23 24 25 26
MenuData                mdMainMenu =            { ._title = MENU_MAIN_TITLE, ._dialog = MENU_MAIN_DIALOG, ._position = MENU_MAIN_INIT_POSITION, ._selection = MENU_MAIN_INIT_SELECTION, ._repaint = MENU_MAIN_INIT_REPAINT, ._selectionFunction = MENU_MAIN_FUNCTION };
MenuData                mdBeerProfileMenu =     { ._title = MENU_PROFILE_TITLE, ._dialog = MENU_PROFILE_DIALOG, ._position = MENU_PROFILE_INIT_POSITION, ._selection = MENU_PROFILE_INIT_SELECTION, ._repaint = MENU_PROFILE_INIT_REPAINT, ._selectionFunction = MENU_PROFILE_FUNCTION };
MenuData                mdStageMenu =           { ._title = MENU_STAGE_TITLE, ._dialog = MENU_STAGE_DIALOG, ._position = MENU_STAGE_INIT_POSITION, ._selection = MENU_STAGE_INIT_SELECTION, ._repaint = MENU_STAGE_INIT_REPAINT, ._selectionFunction = MENU_STAGE_FUNCTION };
MenuData                mdMaltMenu =            { ._title = MENU_MALT_TITLE, ._dialog = MENU_MALT_DIALOG, ._position = MENU_MALT_INIT_POSITION, ._selection = MENU_MALT_INIT_SELECTION, ._repaint = MENU_MALT_INIT_REPAINT, ._selectionFunction = MENU_MALT_FUNCTION };
MenuData                mdSettingsMenu =        { ._title = MENU_SETTINGS_TITLE, ._dialog = MENU_SETTINGS_DIALOG, ._position = MENU_SETTINGS_INIT_POSITION, ._selection = MENU_SETTINGS_INIT_SELECTION, ._repaint = MENU_SETTINGS_INIT_REPAINT, ._selectionFunction = MENU_SETTINGS_FUNCTION };
MenuData                mdStartFromStageMenu =  { ._title = MENU_START_TITLE, ._dialog = MENU_START_DIALOG, ._position = MENU_START_INIT_POSITION, ._selection = MENU_START_INIT_SELECTION, ._repaint = MENU_START_INIT_REPAINT, ._selectionFunction = MENU_START_FUNCTION };
João Lino's avatar
Rel.3  
João Lino committed
27

28
// ++++++++++++++++++++++++ Global Variables ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
29 30
boolean                 cooking;

João Lino's avatar
Rel.3  
João Lino committed
31 32 33 34
unsigned long           clockStartTime;
unsigned long           clockLastUpdate;
long                    clockCounter;
unsigned long           clockIgnore;
João Lino's avatar
João Lino committed
35 36 37
boolean                 clockStart;
boolean                 clockEnd;

João Lino's avatar
Rel.3  
João Lino committed
38
unsigned long           cookTime;
João Lino's avatar
João Lino committed
39
int                     cookTemperature;
João Lino's avatar
Rel.3  
João Lino committed
40
int                     finalYield;
41

João Lino's avatar
Rel.3  
João Lino committed
42 43 44 45 46 47 48 49 50 51 52 53
unsigned long           startpointTime;
unsigned long           betaGlucanaseTime;
unsigned long           debranchingTime;
unsigned long           proteolyticTime;
unsigned long           betaAmylaseTime;
unsigned long           alphaAmylaseTime;
unsigned long           mashoutTime;
unsigned long           recirculationTime;
unsigned long           spargeTime;
unsigned long           boilTime;
unsigned long           coolingTime;
unsigned long           cleaningTime;
54

João Lino's avatar
João Lino committed
55 56 57 58 59 60 61 62 63 64 65
int                     startpointTemperature;
int                     betaGlucanaseTemperature;
int                     debranchingTemperature;
int                     proteolyticTemperature;
int                     betaAmylaseTemperature;
int                     alphaAmylaseTemperature;
int                     mashoutTemperature;
int                     recirculationTemperature;
int                     spargeTemperature;
int                     boilTemperature;
int                     coolingTemperature;
João Lino's avatar
Rel.3  
João Lino committed
66
int                     cleaningTemperature;
João Lino's avatar
João Lino committed
67 68 69

boolean                 refresh;
boolean                 repaint;
João Lino's avatar
João Lino committed
70
boolean                 cancel;
71

João Lino's avatar
Rel.3  
João Lino committed
72 73
boolean                 bStatusElement;

74
// ++++++++++++++++++++++++ Interrupts ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
75
static unsigned long    lastInterruptTime;
76

77
// ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
78 79 80 81 82
volatile int            rotaryEncoderVirtualPosition = 0;
volatile int            rotaryEncoderMaxPosition = 1;
volatile int            rotaryEncoderMinPosition = 0;
volatile int            rotaryEncoderSingleStep = 1;
volatile int            rotaryEncoderMultiStep = 1;
83

João Lino's avatar
João Lino committed
84 85
volatile boolean        onISR = false;

João Lino's avatar
João Lino committed
86 87
unsigned long           rotarySwDetectTime;

88
// ++++++++++++++++++++++++ Heating Element Relay ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
89 90 91
int                     iWindowSize;             // Time frame to operate in
unsigned long           windowStartTime;
double                  dWattPerPulse;
92

93 94 95
// ++++++++++++++++++++++++ Pump ++++++++++++++++++++++++
int                     iPumpSpeed;             // Time frame to operate in

96
// ######################### INITIALIZE #########################
97
// ++++++++++++++++++++++++ Library - LiquidCrystal_I2C ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
98
LiquidCrystal_I2C       lcd(LCD_I2C_ADDR, LCD_EN_PIN, LCD_RW_PIN, LCD_RS_PIN, LCD_D4_PIN, LCD_D5_PIN, LCD_D6_PIN, LCD_D7_PIN);
99

João Lino's avatar
João Lino committed
100
// +++++++++++++++++++++++ Temperature +++++++++++++++++++++++
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
Temperature                   basePT100("base",
                                        PT100_BASE_OUTPUT_PIN,
                                        PT100_BASE_INPUT_PIN,
                                        PT100_BASE_TIME_BETWEEN_READINGS,
                                        2.0298, 2.0259, 665.24, 662.17);
Temperature                   upPT100("up",
                                      PT100_UP_OUTPUT_PIN,
                                      PT100_UP_INPUT_PIN,
                                      PT100_UP_TIME_BETWEEN_READINGS,
                                      2.0274, 2.0245, 659.43, 656.72);
Temperature                   downPT100("down",
                                        PT100_DOWN_OUTPUT_PIN,
                                        PT100_DOWN_INPUT_PIN,
                                        PT100_DOWN_TIME_BETWEEN_READINGS,
                                        2.0309, 2.0288, 658.15, 655.35);
116 117

// ######################### INTERRUPTS #########################
João Lino's avatar
João Lino committed
118
void isr ()  {    // Interrupt service routine is executed when a HIGH to LOW transition is detected on CLK
119
  unsigned long interruptTime = millis();
João Lino's avatar
João Lino committed
120
  unsigned long diff = interruptTime - lastInterruptTime;
121

122
  // If interrupts come faster than [ROTARY_ENCODER_DEBOUNCE_TIME]ms, assume it's a bounce and ignore
João Lino's avatar
João Lino committed
123
  if (diff > ROTARY_ENCODER_DEBOUNCE_TIME) {
João Lino's avatar
João Lino committed
124
    lastInterruptTime = interruptTime;
125 126

    switch (rotaryEncoderMode) {
127 128
      // Input of rotary encoder controling menus
      case eRotaryEncoderMode_Menu: {
129
          if (!digitalRead(ROTARY_ENCODER_DT_PIN)) {
130
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderSingleStep);
131 132
          }
          else {
133
            rotaryEncoderVirtualPosition = rotaryEncoderVirtualPosition - rotaryEncoderSingleStep;
134 135
          }
          if (rotaryEncoderVirtualPosition > rotaryEncoderMaxPosition) {
João Lino's avatar
João Lino committed
136
            rotaryEncoderVirtualPosition = rotaryEncoderMaxPosition;
137 138
          }
          if (rotaryEncoderVirtualPosition < rotaryEncoderMinPosition) {
João Lino's avatar
João Lino committed
139
            rotaryEncoderVirtualPosition = rotaryEncoderMinPosition;
140 141 142
          }

          break;
143
        }
144

145 146
      // Input of rotary encoder controling time variables
      case eRotaryEncoderMode_Time: {
147 148 149 150 151 152 153
          if (!digitalRead(ROTARY_ENCODER_DT_PIN)) {
            if (rotaryEncoderVirtualPosition >= 60) {
              rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderMultiStep);
            }
            else {
              rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderSingleStep);
            }
154 155
          }
          else {
156 157
            if (rotaryEncoderVirtualPosition == rotaryEncoderMinPosition) {
              rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + 60);
158 159
            }
            else {
160 161 162 163 164 165
              if (rotaryEncoderVirtualPosition >= (60 + rotaryEncoderMultiStep)) {
                rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition - rotaryEncoderMultiStep);
              }
              else {
                rotaryEncoderVirtualPosition = rotaryEncoderVirtualPosition - rotaryEncoderSingleStep;
              }
166 167
            }
          }
168
          if (rotaryEncoderVirtualPosition > rotaryEncoderMaxPosition) {
169
            rotaryEncoderVirtualPosition = rotaryEncoderMaxPosition;
170 171
          }
          if (rotaryEncoderVirtualPosition < rotaryEncoderMinPosition) {
172
            rotaryEncoderVirtualPosition = rotaryEncoderMinPosition;
173 174 175
          }

          break;
176
        }
177

178 179
      // Input of rotary encoder controling generic integer variables within a range between rotaryEncoderMinPosition and rotaryEncoderMaxPosition
      case eRotaryEncoderMode_Generic: {
180 181 182 183 184 185 186
          if (!digitalRead(ROTARY_ENCODER_DT_PIN)) {
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderSingleStep);
          }
          else {
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition - rotaryEncoderSingleStep);
          }
          if (rotaryEncoderVirtualPosition > rotaryEncoderMaxPosition) {
service-config's avatar
Mixer  
service-config committed
187
            rotaryEncoderVirtualPosition = rotaryEncoderMaxPosition;
188 189
          }
          if (rotaryEncoderVirtualPosition < rotaryEncoderMinPosition) {
190
            rotaryEncoderVirtualPosition = rotaryEncoderMinPosition;
191 192 193
          }

          break;
service-config's avatar
Mixer  
service-config committed
194
        }
195
      default: {
196 197

        }
198
    }
199

João Lino's avatar
João Lino committed
200 201
    repaint = true;
    refresh = true;
202 203 204
  }
}

205
void xSetupRotaryEncoder( eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep ) {
206 207 208 209 210 211
  if ( newMode >= 0 ) rotaryEncoderMode = newMode;
  if ( newPosition >= 0 ) rotaryEncoderVirtualPosition = newPosition;
  if ( newMaxPosition >= 0 ) rotaryEncoderMaxPosition = newMaxPosition;
  if ( newMinPosition >= 0 ) rotaryEncoderMinPosition = newMinPosition;
  if ( newSingleStep >= 0 ) rotaryEncoderSingleStep = newSingleStep;
  if ( newMultiStep >= 0 ) rotaryEncoderMultiStep = newMultiStep;
212 213
}

214
// ######################### START #########################
215
void xSafeHardwarePowerOff() {
216
  // Turn off gracefully
João Lino's avatar
João Lino committed
217
  iPumpSpeed = PUMP_SPEED_STOP_MOSFET;
218 219 220
  xRegulatePumpSpeed();

  // Force shutdown
João Lino's avatar
João Lino committed
221
  analogWrite(PUMP_PIN, PUMP_SPEED_STOP_MOSFET);  // analogWrite values from 0 to 255
João Lino's avatar
João Lino committed
222
  digitalWrite(HEATING_ELEMENT_OUTPUT_PIN, LOW);  // Turn heading element OFF for safety
João Lino's avatar
Rel.3  
João Lino committed
223 224
  bStatusElement = false;

João Lino's avatar
João Lino committed
225 226 227
  basePT100.setPumpStatus( false );
  upPT100.setPumpStatus( false );
  downPT100.setPumpStatus( false );
228

João Lino's avatar
Rel.3  
João Lino committed
229
  //analogWrite(MIXER_PIN, 0);        // Turn mixer OFF for safety
230 231
}

João Lino's avatar
Rel.3  
João Lino committed
232 233 234
void xWelcomeUser() {
  //#ifndef DEBUG
  lcdPrint(&lcd, "  Let's start", "    Brewing!");    // Write welcome
235

236 237 238
  // Play Melody;
  sing(MELODY_SUPER_MARIO_START, PIEZO_PIN);

239
  //termometerCalibration();
João Lino's avatar
João Lino committed
240
  delay(SETTING_WELCOME_TIMEOUT);      // pause for effect
João Lino's avatar
Rel.3  
João Lino committed
241
  //#endif
242 243
}

244 245
const char *_dialogs[] = {"", "b"};

246
void setup() {
João Lino's avatar
João Lino committed
247
  // ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
248
  pinMode                         (ROTARY_ENCODER_CLK_PIN, INPUT);
João Lino's avatar
João Lino committed
249 250 251 252 253 254 255
  pinMode                         (ROTARY_ENCODER_DT_PIN, INPUT);
  pinMode                         (ROTARY_ENCODER_SW_PIN, INPUT);
  attachInterrupt                 (ROTARY_ENCODER_INTERRUPT_NUMBER, isr, FALLING);

  // ++++++++++++++++++++++++ Heating Element Relay ++++++++++++++++++++++++
  pinMode                         (HEATING_ELEMENT_OUTPUT_PIN, OUTPUT);
  digitalWrite                    (HEATING_ELEMENT_OUTPUT_PIN, LOW);
João Lino's avatar
Rel.3  
João Lino committed
256
  bStatusElement              =   false;
João Lino's avatar
João Lino committed
257 258 259 260 261
  windowStartTime             =   millis();
  dWattPerPulse               =   HEATING_ELEMENT_MAX_WATTAGE / HEATING_ELEMENT_AC_FREQUENCY_HZ;

  // ++++++++++++++++++++++++ Mixer ++++++++++++++++++++++++

262 263
  // ++++++++++++++++++++++++ Pump ++++++++++++++++++++++++
  pinMode(PUMP_PIN, OUTPUT);   // sets the pin as output
João Lino's avatar
João Lino committed
264
  iPumpSpeed                  =   PUMP_SPEED_STOP_MOSFET;             // Time frame to operate in
265 266
  analogWrite(PUMP_PIN, iPumpSpeed);  // analogWrite values from 0 to 255

João Lino's avatar
João Lino committed
267
  // ++++++++++++++++++++++++ Piezo ++++++++++++++++++++++++
268 269
  pinMode(PIEZO_PIN, OUTPUT);

João Lino's avatar
João Lino committed
270
  // ++++++++++++++++++++++++ Temperature Sensor PT100 ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
271

João Lino's avatar
João Lino committed
272 273 274 275 276
  // ++++++++++++++++++++++++ Serial Monitor ++++++++++++++++++++++++
  Serial.begin                    (SETTING_SERIAL_MONITOR_BAUD_RATE);    // setup terminal baud rate
  Serial.println                  (SETTING_SERIAL_MONITOR_WELCOME_MESSAGE);  // print a start message to the terminal

  // ++++++++++++++++++++++++ Library - LiquidCrystal_I2C ++++++++++++++++++++++++
277 278
  lcd.begin                       (LCD_HORIZONTAL_RESOLUTION, LCD_VERTICAL_RESOLUTION);   //  <<----- My LCD was 16x2
  lcd.setBacklightPin             (LCD_BACKLIGHT_PIN, POSITIVE);       // Setup backlight pin
João Lino's avatar
João Lino committed
279 280 281 282 283 284
  lcd.setBacklight                (HIGH);              // Switch on the backlight

  // ######################### INITIALIZE #########################
  // ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
  // set operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
  xSetupRotaryEncoder             ( eRotaryEncoderMode_Disabled, 0, 0, 0, 0, 0 );
João Lino's avatar
João Lino committed
285
  rotarySwDetectTime = 0;
João Lino's avatar
João Lino committed
286 287

  // ++++++++++++++++++++++++ State Machine ++++++++++++++++++++++++
João Lino's avatar
João Lino committed
288
  eMenuType                   =   MENU_INIT;
João Lino's avatar
João Lino committed
289

João Lino's avatar
João Lino committed
290 291 292 293
  cookingStage                =   SETTING_COOKING_STAGE_INIT;
  beerProfile                 =   SETTING_BEER_PROFILE_INIT;

  cancel                      =   false;
João Lino's avatar
João Lino committed
294
  // ++++++++++++++++++++++++ Global Variables ++++++++++++++++++++++++
João Lino's avatar
Rel.3  
João Lino committed
295

João Lino's avatar
João Lino committed
296
  cooking                     =   false;
297

João Lino's avatar
João Lino committed
298
  clockStartTime              =   0;
João Lino's avatar
Rel.3  
João Lino committed
299
  clockLastUpdate             =   0;
João Lino's avatar
João Lino committed
300 301 302 303
  clockCounter                =   0;
  clockIgnore                 =   0;
  clockStart                  =   false;
  clockEnd                    =   false;
304

João Lino's avatar
João Lino committed
305 306
  cookTime                    =   3600;
  cookTemperature             =   25;
João Lino's avatar
João Lino committed
307
  finalYield                  =   SETTING_MACHINE_YIELD_DEFAULT;
João Lino's avatar
João Lino committed
308

João Lino's avatar
João Lino committed
309 310 311 312 313 314 315 316 317 318 319
  startpointTime              =   PROFILE_BASIC_STARTPOINT_TIME;
  betaGlucanaseTime           =   PROFILE_BASIC_BETAGLUCANASE_TIME;
  debranchingTime             =   PROFILE_BASIC_DEBRANCHING_TIME;
  proteolyticTime             =   PROFILE_BASIC_PROTEOLYTIC_TIME;
  betaAmylaseTime             =   PROFILE_BASIC_BETAAMYLASE_TIME;
  alphaAmylaseTime            =   PROFILE_BASIC_ALPHAAMYLASE_TIME;
  mashoutTime                 =   PROFILE_BASIC_MASHOUT_TIME;
  recirculationTime           =   PROFILE_BASIC_RECIRCULATION_TIME;
  spargeTime                  =   PROFILE_BASIC_SPARGE_TIME;
  boilTime                    =   PROFILE_BASIC_BOIL_TIME;
  coolingTime                 =   PROFILE_BASIC_COOLING_TIME;
João Lino's avatar
Rel.3  
João Lino committed
320
  cleaningTime                =   SETTING_CLEANING_TIME;
João Lino's avatar
João Lino committed
321

João Lino's avatar
João Lino committed
322 323 324 325 326 327 328 329 330 331 332
  startpointTemperature       =   PROFILE_BASIC_STARTPOINT_TEMPERATURE;
  betaGlucanaseTemperature    =   PROFILE_BASIC_BETAGLUCANASE_TEMPERATURE;
  debranchingTemperature      =   PROFILE_BASIC_DEBRANCHING_TEMPERATURE;
  proteolyticTemperature      =   PROFILE_BASIC_PROTEOLYTIC_TEMPERATURE;
  betaAmylaseTemperature      =   PROFILE_BASIC_BETAAMYLASE_TEMPERATURE;
  alphaAmylaseTemperature     =   PROFILE_BASIC_ALPHAAMYLASE_TEMPERATURE;
  mashoutTemperature          =   PROFILE_BASIC_MASHOUT_TEMPERATURE;
  recirculationTemperature    =   PROFILE_BASIC_RECIRCULATION_TEMPERATURE;
  spargeTemperature           =   PROFILE_BASIC_SPARGE_TEMPERATURE;
  boilTemperature             =   PROFILE_BASIC_BOIL_TEMPERATURE;
  coolingTemperature          =   PROFILE_BASIC_COOLING_TEMPERATURE;
João Lino's avatar
Rel.3  
João Lino committed
333
  cleaningTemperature         =   SETTING_CLEANING_TEMPERATURE;
João Lino's avatar
João Lino committed
334 335 336 337 338 339 340 341 342

  refresh                     =   true;
  repaint                     =   true;

  // ++++++++++++++++++++++++ Interrupts ++++++++++++++++++++++++
  lastInterruptTime           =   0;

  // ++++++++++++++++++++++++ PID  ++++++++++++++++++++++++
  iWindowSize                 =   HEATING_ELEMENT_DEFAULT_WINDOW_SIZE;    // Time frame to operate in
343

João Lino's avatar
Rel.3  
João Lino committed
344
  // ######################### Code - Run Once #########################
João Lino's avatar
João Lino committed
345
  xSafeHardwarePowerOff           ();
João Lino's avatar
Rel.3  
João Lino committed
346
  xWelcomeUser                    ();
347

João Lino's avatar
Rel.3  
João Lino committed
348
  xSetupRotaryEncoder             ( eRotaryEncoderMode_Menu, eMainMenu_GO, MENU_SIZE_MAIN_MENU - 1, 1, 1, 0 );
349
}
350

351
// ######################### MAIN LOOP #########################
352 353

void loop() {
João Lino's avatar
João Lino committed
354
  unsigned long inactivityTime = getInactivityTime();
355

356 357
  if ( inactivityTime > SETTING_MAX_INACTIVITY_TIME ) {   // Inactivity check
    if (refresh) {
358 359 360
      repaint = true;
      refresh = false;
    }
João Lino's avatar
Rel.3  
João Lino committed
361
    repaint = displayStatus( &lcd, cooking, cookTemperature, basePT100.getCurrentTemperature(), upPT100.getCurrentTemperature(), downPT100.getCurrentTemperature(), clockCounter, repaint );
362 363
  }
  else {
João Lino's avatar
Rel.3  
João Lino committed
364
    runMenu();
365
  }
366

João Lino's avatar
Rel.3  
João Lino committed
367
  xManageMachineSystems();
368 369
}

370 371
// ######################### FUNCTIONS ########################

372 373 374



João Lino's avatar
João Lino committed
375 376
void xCountTheTime( int temperatureMarginRange, boolean bMaximumOfUpDown ) {
  unsigned long now = millis();
João Lino's avatar
João Lino committed
377

João Lino's avatar
João Lino committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391
  // Get current maximum sensed temperaure
  double temperatureCount = 0;
  if ( bMaximumOfUpDown ) {
    float tup = upPT100.getCurrentTemperature();
    float tdown = downPT100.getCurrentTemperature();
    if (tup > tdown) {
      temperatureCount = tdown;
    }
    else {
      temperatureCount = tup;
    }
  } else {
    temperatureCount = basePT100.getCurrentTemperature();
  }
João Lino's avatar
João Lino committed
392

João Lino's avatar
João Lino committed
393 394 395 396 397
  // Ignote time ticks if temperature is not within the acceptable margin for this stage
  unsigned long elapsedTime = now - clockLastUpdate;
  if ( temperatureCount < (cookTemperature - temperatureMarginRange) ) {
    clockIgnore += elapsedTime;
  }
João Lino's avatar
João Lino committed
398

João Lino's avatar
João Lino committed
399 400
  // Calculate the remaining time on the clock
  clockCounter = cookTime * 1000 - (elapsedTime - clockIgnore);
401

João Lino's avatar
João Lino committed
402 403 404 405
  // Don't let clock get bellow 0
  if ( clockCounter < 0 ) {
    clockCounter = 0;
  }
João Lino's avatar
João Lino committed
406

João Lino's avatar
João Lino committed
407
  clockLastUpdate = now;
João Lino's avatar
João Lino committed
408

João Lino's avatar
João Lino committed
409 410 411 412 413 414 415 416 417
#ifdef DEBUG_OFF
  debugPrintFunction("xCountTheTime");
  debugPrintVar("millis()", now);
  debugPrintVar("cookTime", cookTime);
  debugPrintVar("clockStartTime", clockStartTime);
  debugPrintVar("clockIgnore", clockIgnore);
  debugPrintVar("clockCounter", clockCounter);
#endif
}
418

João Lino's avatar
João Lino committed
419 420 421 422 423 424
bool isTimeLeft() {
  if ( clockCounter > 0 ) {
    return true;
  }
  return false;
}
João Lino's avatar
João Lino committed
425

João Lino's avatar
João Lino committed
426 427 428 429 430
//HEATING_ELEMENT_MAX_WATTAGE / HEATING_ELEMENT_AC_FREQUENCY_HZ
double ulWattToWindowTime( double ulAppliedWatts ) {
  double ulPulsesRequired = ulAppliedWatts / dWattPerPulse;
  return (double)iWindowSize / 1000.0 * ulPulsesRequired * 1000.0 / HEATING_ELEMENT_AC_FREQUENCY_HZ;
}
431

João Lino's avatar
João Lino committed
432 433 434 435
bool xRegulateTemperature( boolean bMaximumOfUpDown ) {
  double difference = 0;
  bool overTemperature = false;
  double wattage = 0.0;
436

João Lino's avatar
João Lino committed
437 438 439
  float tup = upPT100.getCurrentTemperature();
  float tdown = downPT100.getCurrentTemperature();
  float tbase = basePT100.getCurrentTemperature();
440

João Lino's avatar
João Lino committed
441 442 443 444 445 446 447
  if ( bMaximumOfUpDown ) {
    if (tup > tdown) {
      difference = cookTemperature - tup;
    }
    else {
      difference = cookTemperature - tdown;
    }
448

João Lino's avatar
João Lino committed
449 450 451
    if (tbase > cookTemperature && (tbase >= (PUMP_TEMPERATURE_MAX_OPERATION - 2.0) || difference >= 5.0)) {
      difference = cookTemperature - tbase;
    }
452

João Lino's avatar
João Lino committed
453 454 455 456 457 458
    if ( (tbase < cookTemperature) && (difference < (cookTemperature - tbase)) ) {
      difference = cookTemperature - tbase;
    }
  } else {
    difference = cookTemperature - tbase;
  }
459

João Lino's avatar
João Lino committed
460 461 462 463 464
  // Deviation between the cook temperature set and the cook temperature measured
  if ( difference < 0.0 ) {
    difference = difference * (-1.0);
    overTemperature = true;
  }
465

João Lino's avatar
João Lino committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
  // Calculate applied wattage, based on the distance from the target temperature
  if ( overTemperature ) {
    // turn it off
    wattage = 0.0;
  } else {
    //if(difference <= 0.1) {
    // turn it off
    //  wattage = 0.0;
    //} else {
    if (difference <= 0.5) {
      // pulse lightly at 500 watt
      if (cookTemperature > 99.0) {
        wattage = 2000.0;
      }
      else {
        if (cookTemperature > 70.0) {
          wattage = 1000.0;
        }
        else {
          wattage = 500.0;
486
        }
João Lino's avatar
Rel.3  
João Lino committed
487
      }
João Lino's avatar
João Lino committed
488 489 490 491 492 493 494 495 496
    } else {
      if (difference <= 1.0) {
        // pulse moderately at 1000 watt
        if (cookTemperature > 99.0) {
          wattage = 2000.0;
        }
        else {
          wattage = 1000.0;
        }
497

João Lino's avatar
João Lino committed
498 499 500 501 502 503 504
      } else {
        if (difference <= 3.0) {
          // pulse hardly at 2000 watt
          wattage = 2000.0;
        } else {
          //pulse constantly at HEATING_ELEMENT_MAX_WATTAGE watt
          wattage = HEATING_ELEMENT_MAX_WATTAGE;
505
        }
João Lino's avatar
João Lino committed
506 507 508 509
      }
    }
    //}
  }
510

João Lino's avatar
João Lino committed
511 512 513 514
  // Update the recorded time for the begining of the window, if the previous window has passed
  while ((millis() - windowStartTime) > iWindowSize) { // Check if it's time to vary the pulse width modulation and if so do it by shifting the "Relay in ON" Window
    windowStartTime += iWindowSize;
  }
515

João Lino's avatar
João Lino committed
516 517 518 519 520 521 522
  // Apply wattage to the element at the right time
  if ( ulWattToWindowTime( wattage ) > (millis() - windowStartTime) ) {
    digitalWrite(HEATING_ELEMENT_OUTPUT_PIN, HIGH);
    bStatusElement = true;
  } else {
    digitalWrite(HEATING_ELEMENT_OUTPUT_PIN, LOW);
    bStatusElement = false;
523
  }
João Lino's avatar
Rel.3  
João Lino committed
524

525
#ifdef DEBUG_OFF
João Lino's avatar
João Lino committed
526 527 528 529 530 531 532 533
  //debugPrintFunction("xRegulateTemperature");
  debugPrintVar("difference", difference);
  //debugPrintVar("overTemperature", overTemperature);
  debugPrintVar("wattage", wattage);
  //debugPrintVar("ulWattToWindowTime( wattage )", ulWattToWindowTime( wattage ) );
  //debugPrintVar("millis()", millis());
  //debugPrintVar("windowStartTime", windowStartTime);
  //debugPrintVar("test", ulWattToWindowTime( wattage ) > (millis() - windowStartTime) );
534
#endif
535 536
}

João Lino's avatar
João Lino committed
537 538 539 540 541 542 543 544
void xPurgePump() {
  for (int i = 0; i < 2; i++) {
    analogWrite(PUMP_PIN, PUMP_SPEED_MAX_MOSFET);  // analogWrite values from 0 to 255
    delay(1000);
    analogWrite(PUMP_PIN, PUMP_SPEED_STOP_MOSFET);  // analogWrite values from 0 to 255
    delay(1500);
  }
}
João Lino's avatar
Rel.3  
João Lino committed
545

João Lino's avatar
João Lino committed
546 547
bool xRegulatePumpSpeed() {
  //  analogWrite(PUMP_PIN, iPumpSpeed);  // analogWrite values from 0 to 255
548

João Lino's avatar
João Lino committed
549 550
  if (basePT100.getCurrentTemperature() > PUMP_TEMPERATURE_MAX_OPERATION) {
    analogWrite(PUMP_PIN, PUMP_SPEED_STOP_MOSFET);  // analogWrite values from 0 to 255
João Lino's avatar
Rel.3  
João Lino committed
551

João Lino's avatar
João Lino committed
552 553 554 555 556 557
    basePT100.setPumpStatus( false );
    upPT100.setPumpStatus( false );
    downPT100.setPumpStatus( false );
  }
  else {
    analogWrite(PUMP_PIN, iPumpSpeed);  // analogWrite values from 0 to 255
558

João Lino's avatar
João Lino committed
559 560 561
    basePT100.setPumpStatus( true );
    upPT100.setPumpStatus( true );
    downPT100.setPumpStatus( true );
João Lino's avatar
Rel.3  
João Lino committed
562
  }
João Lino's avatar
João Lino committed
563
}
João Lino's avatar
Rel.3  
João Lino committed
564

João Lino's avatar
João Lino committed
565 566
void xWarnClockEnded() {
  sing(MELODY_SUPER_MARIO_START, PIEZO_PIN);
João Lino's avatar
Rel.3  
João Lino committed
567 568
}

João Lino's avatar
João Lino committed
569 570 571
void xWarnCookEnded() {
  sing(MELODY_UNDERWORLD_SHORT, PIEZO_PIN);
}
João Lino's avatar
Rel.3  
João Lino committed
572

João Lino's avatar
João Lino committed
573 574 575 576 577
void xPrepareForStage( int stageTime, int stageTemperature, int stagePumpSpeed, eCookingStages stage ) {
#ifdef DEBUG_OFF
  debugPrintFunction("xPrepareForStage");
  debugPrintVar("cookingStage", stage);
#endif
578

João Lino's avatar
João Lino committed
579 580 581 582 583
  // Reset the clock
  unsigned long now = millis();
  clockStartTime  = now;
  clockLastUpdate = now;
  clockIgnore     = 0;
João Lino's avatar
Rel.3  
João Lino committed
584

João Lino's avatar
João Lino committed
585 586 587 588
  iPumpSpeed      = stagePumpSpeed;         // Set the pump speed
  cookingStage    = stage;                  // Set Stage
  cookTime        = stageTime;              // Set the clock
  cookTemperature = stageTemperature;       // Set the target temperature
João Lino's avatar
Rel.3  
João Lino committed
589 590
}

João Lino's avatar
João Lino committed
591 592 593 594 595
void xSetupStage(eCookingStages nextStage) {
#ifdef DEBUG_OFF
  debugPrintFunction("xSetupStage");
  debugPrintVar("cookingStage", nextStage);
#endif
João Lino's avatar
Rel.3  
João Lino committed
596

João Lino's avatar
João Lino committed
597 598 599 600 601 602 603 604 605 606 607 608
  // Operate the machine according to the current mode
  switch (nextStage) {
    case eCookingStage_Startpoint: {
        switch (beerProfile) {
          case eBeerProfile_Trigo: {
              float wheatAmount = 0.05 * ((float) finalYield);
              float pilsnerAmount = 0.2 * ((float) finalYield);
              String say = "Cruch ";
              say += String(wheatAmount);
              say += String("Kg of Wheat and ");
              say += String(pilsnerAmount);
              say += String("Kg of Pilsner Malt into a pot.");
609

João Lino's avatar
João Lino committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
              xWaitForAction("Malt", say);
              repaint = true;
              break;
            }
          case eBeerProfile_IPA: {
              float caramelAmount = 0.013157895 * ((float) finalYield);
              float wheatAmount = 0.060526316 * ((float) finalYield);
              float pilsnerAmount = 0.115789474 * ((float) finalYield);
              float munichAmount = 0.028947368 * ((float) finalYield);
              String say = "Cruch ";
              say += String(caramelAmount);
              say += String("Kg of Caramel 120, ");
              say += String(wheatAmount);
              say += String("Kg of Wheat, ");
              say += String(pilsnerAmount);
              say += String("Kg of Pilsner, ");
              say += String(munichAmount);
              say += String("Kg of Munich into a pot.");
628

João Lino's avatar
João Lino committed
629 630 631 632 633
              xWaitForAction("Malt", say);
              repaint = true;
              break;
            }
          default: {
João Lino's avatar
Rel.3  
João Lino committed
634

João Lino's avatar
João Lino committed
635 636
            }
        }
637

João Lino's avatar
João Lino committed
638 639
        // Make sure there is water
        xWaitForAction("Water", "Make sure there is water in the machine before start cooking.");
640

João Lino's avatar
João Lino committed
641 642
        repaint = true;
        xPrepareForStage( startpointTime, startpointTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Startpoint );
643 644
        break;
      }
João Lino's avatar
João Lino committed
645 646 647 648 649 650 651 652 653 654
    case eCookingStage_BetaGlucanase: {
        switch (beerProfile) {
          case eBeerProfile_Trigo: {
              float wheatAmount = 0.05 * ((float) finalYield);
              float pilsnerAmount = 0.2 * ((float) finalYield);
              String say = "Put ";
              say += String(wheatAmount);
              say += String("Kg of Wheat and ");
              say += String(pilsnerAmount);
              say += String("Kg of Pilsner Malt in.");
655

João Lino's avatar
João Lino committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
              xWaitForAction("Malt", say);
              repaint = true;
              break;
            }
          case eBeerProfile_IPA: {
              float caramelAmount = 0.013157895 * ((float) finalYield);
              float wheatAmount = 0.060526316 * ((float) finalYield);
              float pilsnerAmount = 0.115789474 * ((float) finalYield);
              float munichAmount = 0.028947368 * ((float) finalYield);
              String say = "Cruch ";
              say += String(caramelAmount);
              say += String("Kg of Caramel 120, ");
              say += String(wheatAmount);
              say += String("Kg of Wheat, ");
              say += String(pilsnerAmount);
              say += String("Kg of Pilsner, ");
              say += String(munichAmount);
              say += String("Kg of Munich into a pot.");
674

João Lino's avatar
João Lino committed
675 676 677 678 679 680 681
              xWaitForAction("Malt", say);
              repaint = true;
              break;
            }
          default: {}
        }
        xPrepareForStage( betaGlucanaseTime, betaGlucanaseTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_BetaGlucanase );
682 683
        break;
      }
João Lino's avatar
João Lino committed
684 685
    case eCookingStage_Debranching: {
        xPrepareForStage( debranchingTime, debranchingTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Debranching );
686 687
        break;
      }
João Lino's avatar
João Lino committed
688 689
    case eCookingStage_Proteolytic: {
        xPrepareForStage( proteolyticTime, proteolyticTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Proteolytic );
690 691
        break;
      }
João Lino's avatar
João Lino committed
692 693
    case eCookingStage_BetaAmylase: {
        xPrepareForStage( betaAmylaseTime, betaAmylaseTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_BetaAmylase );
694 695
        break;
      }
João Lino's avatar
João Lino committed
696 697
    case eCookingStage_AlphaAmylase: {
        xPrepareForStage( alphaAmylaseTime, alphaAmylaseTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_AlphaAmylase );
698 699
        break;
      }
João Lino's avatar
João Lino committed
700 701
    case eCookingStage_Mashout: {
        xPrepareForStage( mashoutTime, mashoutTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Mashout );
702 703
        break;
      }
João Lino's avatar
João Lino committed
704 705 706 707
    case eCookingStage_Recirculation: {
        xWaitForAction("Sparge Water", "Start heating your sparge water.");
        repaint = true;
        xPrepareForStage( recirculationTime, recirculationTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Recirculation );
708 709
        break;
      }
João Lino's avatar
João Lino committed
710 711 712 713
    case eCookingStage_Sparge: {
        xWaitForAction("Sparge Water", "Start pouring the sparge water.");
        repaint = true;
        xPrepareForStage( spargeTime, spargeTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Sparge );
714 715
        break;
      }
João Lino's avatar
João Lino committed
716 717 718 719
    case eCookingStage_Boil: {
        switch (beerProfile) {
          case eBeerProfile_Trigo: {
              String say = "Get ";
720

João Lino's avatar
João Lino committed
721 722
              float hopAmount = 0.8 * ((float) finalYield);
              say += String(hopAmount);
723

João Lino's avatar
João Lino committed
724
              say += String("g of Magnum 9.4\% and Styrian Golding 5\% ready.");
João Lino's avatar
Rel.3  
João Lino committed
725

João Lino's avatar
João Lino committed
726
              xWaitForAction("Hops", say);
727

João Lino's avatar
João Lino committed
728 729 730 731
              break;
            }
          case eBeerProfile_IPA: {
              String say = "Get ";
João Lino's avatar
Rel.3  
João Lino committed
732

João Lino's avatar
João Lino committed
733 734
              float hopAmount = 0.8 * ((float) finalYield);
              say += String(hopAmount);
João Lino's avatar
Rel.3  
João Lino committed
735

João Lino's avatar
João Lino committed
736
              say += String("g of Chinook, Cascade and Styrian Golding ready.");
737

João Lino's avatar
João Lino committed
738
              xWaitForAction("Hops", say);
739

João Lino's avatar
João Lino committed
740 741 742 743
              break;
            }
          default: {
              xWaitForAction("Hops", "Add the hops in the right order, at the right time.");
744

João Lino's avatar
João Lino committed
745 746
            }
        }
747

João Lino's avatar
João Lino committed
748
        repaint = true;
749

João Lino's avatar
João Lino committed
750 751
        // A basic operation for a basic stage
        xPrepareForStage( boilTime, boilTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Boil );
João Lino's avatar
Rel.3  
João Lino committed
752

753 754
        break;
      }
João Lino's avatar
João Lino committed
755 756 757
    case eCookingStage_Cooling: {
        // Make sure there is water
        xWaitForAction("Coil", "Add the coil and connect it to the main water supply.");
758

João Lino's avatar
João Lino committed
759 760 761 762
        repaint = true;

        // A basic operation for a basic stage
        xPrepareForStage( coolingTime, coolingTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Cooling );
763 764 765

        break;
      }
João Lino's avatar
João Lino committed
766 767 768
    case eCookingStage_Clean: {
        // Make sure there is water
        xWaitForAction("Water", "Add 13 liters.");
769

João Lino's avatar
João Lino committed
770 771
        // Make sure there is water
        xWaitForAction("Star San HB", "Add 0.89oz/26ml.");
772

João Lino's avatar
João Lino committed
773
        repaint = true;
774

João Lino's avatar
João Lino committed
775 776
        // A basic operation for a basic stage
        xPrepareForStage( cleaningTime, cleaningTemperature, PUMP_SPEED_MAX_MOSFET, eCookingStage_Clean );
777 778 779

        break;
      }
João Lino's avatar
João Lino committed
780 781 782
    case eCookingStage_Purge: {
        // A basic operation for a basic stage
        xPrepareForStage( 0, 0, PUMP_SPEED_MAX_MOSFET, eCookingStage_Purge );
783

João Lino's avatar
João Lino committed
784
        xRegulatePumpSpeed();
785 786 787

        break;
      }
João Lino's avatar
João Lino committed
788 789 790
    case eCookingStage_Done: {
        // A basic operation for a basic stage
        xPrepareForStage( 0, 0, PUMP_SPEED_STOP_MOSFET, eCookingStage_Done );
791 792 793

        break;
      }
794
  }
795 796
}

João Lino's avatar
João Lino committed
797 798 799
void xTransitionIntoStage(eCookingStages nextStage) {
  // Turn off all hardware that can damage itself if the machine is not cooking
  xSafeHardwarePowerOff();
800

João Lino's avatar
João Lino committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
  // Warn the user a stage has ended
  xWarnClockEnded();

  // Reset global stage variables
  xSetupStage( nextStage );
}

void xBasicStageOperation( int iStageTime, int iStageTemperature, int iStageTemperatureRange, eCookingStages nextStage, boolean bMaximumOfUpDown ) {

  // Account for time spent at the target temperature | Input 1: range in ºC within which the target temperature is considered to be reached
#ifdef DEBUG_OFF
  xCountTheTime( iStageTemperatureRange, false );
#else
  xCountTheTime( iStageTemperatureRange, bMaximumOfUpDown );
#endif

  if ( isTimeLeft() ) {
    // Do temperature control
    xRegulateTemperature( bMaximumOfUpDown );

    // Do flow control
    xRegulatePumpSpeed();

  } else {
#ifdef DEBUG_OFF
    debugPrintFunction("xBasicStageOperation");
    debugPrintVar("clockCounter", clockCounter);
#endif

    // Continue to the next stage, there is nothing to do, in this stage
    xTransitionIntoStage( nextStage );
    return;
833
  }
João Lino's avatar
João Lino committed
834 835 836 837 838 839 840 841 842 843 844

  return;
}

void xManageMachineSystems() {

#ifdef DEBUG
  Serial.print(millis());
  Serial.print(",");
  if (cooking) {
    Serial.print("1");
845
  }
João Lino's avatar
João Lino committed
846 847
  else {
    Serial.print("0");
848
  }
João Lino's avatar
João Lino committed
849 850 851 852 853 854 855 856
  Serial.print(",");
  Serial.print(cookTemperature);
  Serial.print(",");
  if (bStatusElement) {
    Serial.print("1");
  }
  else {
    Serial.print("0");
857
  }
João Lino's avatar
João Lino committed
858 859
  Serial.print(",");
#endif
860

João Lino's avatar
João Lino committed
861 862 863 864
  // Measure temperature, for effect
  basePT100.measure(false);
  upPT100.measure(false);
  downPT100.measure(true);
João Lino's avatar
João Lino committed
865

João Lino's avatar
João Lino committed
866 867 868
  // If cooking is done, return (this is a nice place to double check safety and ensure the cooking parts aren't on.
  if (!cooking) {
    xSafeHardwarePowerOff();
João Lino's avatar
João Lino committed
869

João Lino's avatar
João Lino committed
870 871
    return;
  }
João Lino's avatar
João Lino committed
872

João Lino's avatar
João Lino committed
873 874 875 876
  // Operate the machine according to the current mode
  switch (cookingStage) {
    case eCookingStage_Startpoint: {
        xBasicStageOperation( startpointTime, startpointTemperature, 0, eCookingStage_BetaGlucanase, false);
877 878
        break;
      }
João Lino's avatar
João Lino committed
879 880
    case eCookingStage_BetaGlucanase: {
        xBasicStageOperation( betaGlucanaseTime, betaGlucanaseTemperature, 3, eCookingStage_Debranching, true );
881 882
        break;
      }
João Lino's avatar
João Lino committed
883 884
    case eCookingStage_Debranching: {
        xBasicStageOperation( debranchingTime, debranchingTemperature, 3, eCookingStage_Proteolytic, true );
885 886
        break;
      }
João Lino's avatar
João Lino committed
887 888
    case eCookingStage_Proteolytic: {
        xBasicStageOperation( proteolyticTime, proteolyticTemperature, 3, eCookingStage_BetaAmylase, true );
889 890
        break;
      }
João Lino's avatar
João Lino committed
891 892
    case eCookingStage_BetaAmylase: {
        xBasicStageOperation( betaAmylaseTime, betaAmylaseTemperature, 4, eCookingStage_AlphaAmylase, true );
893 894
        break;
      }
João Lino's avatar
João Lino committed
895 896
    case eCookingStage_AlphaAmylase: {
        xBasicStageOperation( alphaAmylaseTime, alphaAmylaseTemperature, 2, eCookingStage_Mashout, true );
897 898
        break;
      }
João Lino's avatar
João Lino committed
899 900
    case eCookingStage_Mashout: {
        xBasicStageOperation( mashoutTime, mashoutTemperature, 1, eCookingStage_Recirculation, true );
901 902
        break;
      }
João Lino's avatar
João Lino committed
903 904
    case eCookingStage_Recirculation: {
        xBasicStageOperation( recirculationTime, recirculationTemperature, 1, eCookingStage_Sparge, true );
905 906
        break;
      }
João Lino's avatar
João Lino committed
907 908
    case eCookingStage_Sparge: {
        xBasicStageOperation( spargeTime, spargeTemperature, 3, eCookingStage_Boil, false );
909 910
        break;
      }
João Lino's avatar
João Lino committed
911 912
    case eCookingStage_Boil: {
        xBasicStageOperation( boilTime, boilTemperature, 2, eCookingStage_Cooling, false );
913 914
        break;
      }
João Lino's avatar
João Lino committed
915 916
    case eCookingStage_Cooling: {
        xBasicStageOperation( coolingTime, coolingTemperature, 0, eCookingStage_Done, false );
917 918
        break;
      }
João Lino's avatar
João Lino committed
919 920
    case eCookingStage_Clean: {
        xBasicStageOperation( cleaningTime, cleaningTemperature, 0, eCookingStage_Done, false );
921 922
        break;
      }
João Lino's avatar
João Lino committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    case eCookingStage_Purge: {
      iPumpSpeed = PUMP_SPEED_MAX_MOSFET;
      xRegulatePumpSpeed();
      break;
    }
    case eCookingStage_Done: {
      stopBrewing();                  // Update cooking state
      repaint = true;                 // Ask for screen refresh
      xWarnCookEnded();               // Warn the user that the cooking is done
      break;
    }
  }
}

// ##################################################### Menus ###################################################################

// *************************** MENU BASE *********************************
void runMenu() {
#ifdef DEBUG_OFF
  boolean debug_go = repaint;
  if (debug_go) {
    debugPrintFunction("runMenu");
    debugPrintVar("repaint", repaint);
    debugPrintVar("eMenuType", eMenuType);
    debugPrintVar("rotaryEncoderVirtualPosition", rotaryEncoderVirtualPosition);
  }
#endif

  switch (eMenuType) {
    case eMenuType_Main: {
      runMenuProcessor( &mdMainMenu );
      break;
    }
    case eMenuType_BeerProfile: {
      runMenuProcessor( &mdBeerProfileMenu );
      break;
    }
    case eMenuType_Stage: {
      runMenuProcessor( &mdStageMenu );
      break;
    }
    case eMenuType_Malt: {
      runMenuProcessor( &mdMaltMenu );
      break;
    }
    case eMenuType_Settings: {
      runMenuProcessor( &mdSettingsMenu );
      break;
    }
    case eMenuType_StartFromStage: {
      runMenuProcessor( &mdStartFromStageMenu );
      break;
    }
  }

#ifdef DEBUG_OFF
  if (debug_go) {
    debugPrintVar("repaint", repaint);
João Lino's avatar
João Lino committed
981
  }
João Lino's avatar
João Lino committed
982
#endif
João Lino's avatar
João Lino committed
983 984
}

João Lino's avatar
João Lino committed
985
// ************************ MENU SELECTIONS ******************************
João Lino's avatar
Rel.3  
João Lino committed
986
void runMainMenuSelection() {
987 988
  switch (mdMainMenu._selection) {
  //switch (eMainMenuSelection) {
João Lino's avatar
João Lino committed
989
    case eMainMenu_GO: {
990 991 992
        xStartStage( NULL, NULL, eCookingStage_Startpoint, true, true, false, false );
        break;
      }
João Lino's avatar
João Lino committed
993
    case eMainMenu_GO_FROM_STAGE: {
994 995
        eMenuType = eMenuType_StartFromStage;
        repaint = true;
João Lino's avatar
João Lino committed
996
        xSetupRotaryEncoder( eRotaryEncoderMode_Menu, mdBeerProfileMenu._position, MENU_SIZE_PROFILES_MENU - 1, 1, 1, 0 );
997 998
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
999
    case eMainMenu_STOP: {
1000 1001 1002 1003
        stopBrewing();
        backToStatus();
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1004
    case eMainMenu_SKIP: {
1005 1006 1007 1008
        cookTime = 0;
        backToStatus();
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1009
    case eMainMenu_BeerProfile: {
1010 1011
        eMenuType = eMenuType_BeerProfile;
        repaint = true;
João Lino's avatar
João Lino committed
1012
        xSetupRotaryEncoder( eRotaryEncoderMode_Menu, mdBeerProfileMenu._position, MENU_SIZE_PROFILES_MENU - 1, 1, 1, 0 );
1013 1014 1015 1016 1017
        break;
      }
    case eMainMenu_Stage: {
        eMenuType = eMenuType_Stage;
        repaint = true;
João Lino's avatar
João Lino committed
1018
        xSetupRotaryEncoder( eRotaryEncoderMode_Menu, mdStageMenu._position, MENU_SIZE_STAGE_MENU - 1, 1, 1, 0 );
1019 1020
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1021
    case eMainMenu_Malt: {
1022 1023
        eMenuType = eMenuType_Malt;
        repaint = true;
João Lino's avatar
João Lino committed
1024
        xSetupRotaryEncoder( eRotaryEncoderMode_Menu, mdMaltMenu._position, MENU_SIZE_MALT_MENU - 1, 1, 1, 0 );
1025 1026
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1027
    case eMainMenu_Hops: {
1028 1029 1030
        backToStatus();
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1031
    case eMainMenu_Clean: {
1032 1033 1034
        xStartStageHeadless( eCookingStage_Clean, true );
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1035
    case eMainMenu_Purge: {
1036 1037 1038
        xStartStageHeadless( eCookingStage_Purge, true );
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1039
    case eMainMenu_Settings: {
1040 1041
        eMenuType = eMenuType_Settings;
        repaint = true;
João Lino's avatar
João Lino committed
1042
        xSetupRotaryEncoder( eRotaryEncoderMode_Menu, mdSettingsMenu._position, MENU_SIZE_SETTINGS_MENU - 1, 1, 1, 0 );
1043 1044
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1045
    case eMainMenu_Back: {
1046 1047 1048
        backToStatus();
        break;
      }
João Lino's avatar
Rel.3  
João Lino committed
1049
    default: {
1050
      }
João Lino's avatar
Rel.3  
João Lino committed
1051
  }
1052
  mdMainMenu._selection = eMainMenu_NULL;
1053 1054
}

João Lino's avatar
João Lino committed
1055

João Lino's avatar
João Lino committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
void runStartFromStageSelection() {
  switch (mdStartFromStageMenu._selection) {
    case eStageMenu_Startpoint: {
        xStartStageInteractive( &startpointTime, &startpointTemperature, eCookingStage_Startpoint );
        break;
      }
    case eStageMenu_BetaGlucanase: {
        xStartStageInteractive( &betaGlucanaseTime, &betaGlucanaseTemperature, eCookingStage_BetaGlucanase );
        break;
      }
    case eStageMenu_Debranching: {
        xStartStageInteractive( &debranchingTime, &debranchingTemperature, eCookingStage_Debranching );
        break;
      }
    case eStageMenu_Proteolytic: {
        xStartStageInteractive( &proteolyticTime, &proteolyticTemperature, eCookingStage_Proteolytic );
        break;
      }
    case eStageMenu_BetaAmylase: {
        xStartStageInteractive( &betaAmylaseTime, &betaAmylaseTemperature, eCookingStage_BetaAmylase );
        break;
      }
    case eStageMenu_AlphaAmylase: {
        xStartStageInteractive( &alphaAmylaseTime, &alphaAmylaseTemperature, eCookingStage_AlphaAmylase );
        break;
      }
    case eStageMenu_Mashout: {
        xStartStageInteractive( &mashoutTime, &mashoutTemperature, eCookingStage_Mashout );
        break;
      }
    case eStageMenu_Recirculation: {
        xStartStageInteractive( &recirculationTime, &recirculationTemperature, eCookingStage_Recirculation );
        break;
      }
    case eStageMenu_Sparge: {
        xStartStageInteractive( &spargeTime, &spargeTemperature, eCookingStage_Sparge );
        break;
      }
    case eStageMenu_Boil: {
        xStartStageInteractive( &boilTime, &boilTemperature, eCookingStage_Boil );
        break;
      }
    case eStageMenu_Cooling: {
        xStartStageInteractive( &coolingTime, &coolingTemperature, eCookingStage_Cooling );
        break;
      }
    case eStageMenu_Back: {
        resetMenu( true );
        break;
      }
    default: {
      }
João Lino's avatar
João Lino committed
1108
  }
João Lino's avatar
João Lino committed
1109 1110
  mdStartFromStageMenu._selection = eStageMenu_NULL;
}
1111

João Lino's avatar
João Lino committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
void runBeerProfileSelection() {
  switch (mdBeerProfileMenu._selection) {
    case eBeerProfileMenu_Basic: {
      beerProfile                 =   eBeerProfile_Basic;
      startpointTime              =   PROFILE_BASIC_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_BASIC_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_BASIC_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_BASIC_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_BASIC_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_BASIC_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_BASIC_MASHOUT_TIME;
      recirculationTime           =   PROFILE_BASIC_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_BASIC_SPARGE_TIME;
      boilTime                    =   PROFILE_BASIC_BOIL_TIME;
      coolingTime                 =   PROFILE_BASIC_COOLING_TIME;
      startpointTemperature       =   PROFILE_BASIC_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_BASIC_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_BASIC_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_BASIC_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_BASIC_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_BASIC_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_BASIC_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_BASIC_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_BASIC_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_BASIC_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_BASIC_COOLING_TEMPERATURE;
      
      backToStatus();
      break;
    }
    case eBeerProfileMenu_Trigo: {
      beerProfile                 =   eBeerProfile_Trigo;
      startpointTime              =   PROFILE_TRIGO_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_TRIGO_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_TRIGO_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_TRIGO_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_TRIGO_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_TRIGO_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_TRIGO_MASHOUT_TIME;
      recirculationTime           =   PROFILE_TRIGO_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_TRIGO_SPARGE_TIME;
      boilTime                    =   PROFILE_TRIGO_BOIL_TIME;
      coolingTime                 =   PROFILE_TRIGO_COOLING_TIME;
      startpointTemperature       =   PROFILE_TRIGO_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_TRIGO_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_TRIGO_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_TRIGO_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_TRIGO_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_TRIGO_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_TRIGO_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_TRIGO_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_TRIGO_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_TRIGO_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_TRIGO_COOLING_TEMPERATURE;

      backToStatus();
      break;
    }
    case eBeerProfileMenu_IPA: {
      beerProfile                 =   eBeerProfile_IPA;
      startpointTime              =   PROFILE_IPA_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_IPA_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_IPA_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_IPA_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_IPA_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_IPA_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_IPA_MASHOUT_TIME;
      recirculationTime           =   PROFILE_IPA_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_IPA_SPARGE_TIME;
      boilTime                    =   PROFILE_IPA_BOIL_TIME;
      coolingTime                 =   PROFILE_IPA_COOLING_TIME;
      startpointTemperature       =   PROFILE_IPA_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_IPA_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_IPA_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_IPA_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_IPA_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_IPA_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_IPA_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_IPA_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_IPA_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_IPA_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_IPA_COOLING_TEMPERATURE;

      backToStatus();
      break;
    }
    case eBeerProfileMenu_Belga: {
      beerProfile                 =   eBeerProfile_Belga;
      startpointTime              =   PROFILE_BELGA_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_BELGA_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_BELGA_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_BELGA_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_BELGA_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_BELGA_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_BELGA_MASHOUT_TIME;
      recirculationTime           =   PROFILE_BELGA_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_BELGA_SPARGE_TIME;
      boilTime                    =   PROFILE_BELGA_BOIL_TIME;
      coolingTime                 =   PROFILE_BELGA_COOLING_TIME;
      startpointTemperature       =   PROFILE_BELGA_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_BELGA_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_BELGA_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_BELGA_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_BELGA_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_BELGA_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_BELGA_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_BELGA_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_BELGA_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_BELGA_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_BELGA_COOLING_TEMPERATURE;

      backToStatus();
      break;
    }
    case eBeerProfileMenu_Red: {
      beerProfile                 =   eBeerProfile_Red;
      startpointTime              =   PROFILE_RED_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_RED_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_RED_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_RED_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_RED_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_RED_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_RED_MASHOUT_TIME;
      recirculationTime           =   PROFILE_RED_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_RED_SPARGE_TIME;
      boilTime                    =   PROFILE_RED_BOIL_TIME;
      coolingTime                 =   PROFILE_RED_COOLING_TIME;
      startpointTemperature       =   PROFILE_RED_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_RED_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_RED_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_RED_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_RED_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_RED_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_RED_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_RED_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_RED_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_RED_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_RED_COOLING_TEMPERATURE;

      backToStatus();
      break;
    }
    case eBeerProfileMenu_APA: {
      beerProfile                 =   eBeerProfile_APA;
      startpointTime              =   PROFILE_APA_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_APA_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_APA_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_APA_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_APA_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_APA_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_APA_MASHOUT_TIME;
      recirculationTime           =   PROFILE_APA_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_APA_SPARGE_TIME;
      boilTime                    =   PROFILE_APA_BOIL_TIME;
      coolingTime                 =   PROFILE_APA_COOLING_TIME;
      startpointTemperature       =   PROFILE_APA_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_APA_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_APA_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_APA_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_APA_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_APA_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_APA_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_APA_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_APA_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_APA_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_APA_COOLING_TEMPERATURE;

      backToStatus();
      break;
    }
    case eBeerProfileMenu_Custom: {
      beerProfile                 =   eBeerProfile_Custom;
      startpointTime              =   PROFILE_CUSTOM_STARTPOINT_TIME;
      betaGlucanaseTime           =   PROFILE_CUSTOM_BETAGLUCANASE_TIME;
      debranchingTime             =   PROFILE_CUSTOM_DEBRANCHING_TIME;
      proteolyticTime             =   PROFILE_CUSTOM_PROTEOLYTIC_TIME;
      betaAmylaseTime             =   PROFILE_CUSTOM_BETAAMYLASE_TIME;
      alphaAmylaseTime            =   PROFILE_CUSTOM_ALPHAAMYLASE_TIME;
      mashoutTime                 =   PROFILE_CUSTOM_MASHOUT_TIME;
      recirculationTime           =   PROFILE_CUSTOM_RECIRCULATION_TIME;
      spargeTime                  =   PROFILE_CUSTOM_SPARGE_TIME;
      boilTime                    =   PROFILE_CUSTOM_BOIL_TIME;
      coolingTime                 =   PROFILE_CUSTOM_COOLING_TIME;
      startpointTemperature       =   PROFILE_CUSTOM_STARTPOINT_TEMPERATURE;
      betaGlucanaseTemperature    =   PROFILE_CUSTOM_BETAGLUCANASE_TEMPERATURE;
      debranchingTemperature      =   PROFILE_CUSTOM_DEBRANCHING_TEMPERATURE;
      proteolyticTemperature      =   PROFILE_CUSTOM_PROTEOLYTIC_TEMPERATURE;
      betaAmylaseTemperature      =   PROFILE_CUSTOM_BETAAMYLASE_TEMPERATURE;
      alphaAmylaseTemperature     =   PROFILE_CUSTOM_ALPHAAMYLASE_TEMPERATURE;
      mashoutTemperature          =   PROFILE_CUSTOM_MASHOUT_TEMPERATURE;
      recirculationTemperature    =   PROFILE_CUSTOM_RECIRCULATION_TEMPERATURE;
      spargeTemperature           =   PROFILE_CUSTOM_SPARGE_TEMPERATURE;
      boilTemperature             =   PROFILE_CUSTOM_BOIL_TEMPERATURE;
      coolingTemperature          =   PROFILE_CUSTOM_COOLING_TEMPERATURE;

      backToStatus();
      break;
    }
    case eBeerProfileMenu_Back: {
      resetMenu( true );
      break;
    }
    default: {}
João Lino's avatar
João Lino committed
1315
  }
João Lino's avatar
João Lino committed
1316
  mdBeerProfileMenu._selection = eBeerProfileMenu_NULL;
1317 1318
}

João Lino's avatar
João Lino committed
1319 1320 1321 1322 1323
void runStageSelection() {
  switch (mdStageMenu._selection) {
    case eStageMenu_Startpoint: {
      runStageSelection_Generic( &startpointTime, &startpointTemperature );
      break;
João Lino's avatar
Rel.3  
João Lino committed
1324
    }
João Lino's avatar
João Lino committed
1325 1326 1327
    case eStageMenu_BetaGlucanase: {
      runStageSelection_Generic( &betaGlucanaseTime, &betaGlucanaseTemperature );
      break;
João Lino's avatar
Rel.3  
João Lino committed
1328
    }
João Lino's avatar
João Lino committed
1329 1330 1331
    case eStageMenu_Debranching: {
      runStageSelection_Generic( &debranchingTime, &debranchingTemperature );
      break;
João Lino's avatar
Rel.3  
João Lino committed
1332
    }
João Lino's avatar
João Lino committed
1333 1334 1335
    case eStageMenu_Proteolytic: {
      runStageSelection_Generic( &proteolyticTime, &proteolyticTemperature );
      break;
João Lino's avatar
Rel.3  
João Lino committed
1336
    }
João Lino's avatar
João Lino committed
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    case eStageMenu_BetaAmylase: {
      runStageSelection_Generic( &betaAmylaseTime, &betaAmylaseTemperature );
      break;
    }
    case eStageMenu_AlphaAmylase: {
      runStageSelection_Generic( &alphaAmylaseTime, &alphaAmylaseTemperature );
      break;
    }
    case eStageMenu_Mashout: {
      runStageSelection_Generic( &mashoutTime, &mashoutTemperature );
      break;
    }
    case eStageMenu_Recirculation: {
      runStageSelection_Generic( &recirculationTime, &recirculationTemperature );
      break;
    }
    case eStageMenu_Sparge: {
      runStageSelection_Generic( &spargeTime, &spargeTemperature );
      break;
    }
    case eStageMenu_Boil: {
      runStageSelection_Generic( &boilTime, &boilTemperature );
      break;
    }
    case eStageMenu_Cooling: {
      runStageSelection_Generic( &coolingTime, &coolingTemperature );
      break;
    }
    case eStageMenu_Back: {
      resetMenu( true );
      break;
    }
    default: {}
João Lino's avatar
João Lino committed
1370
  }
João Lino's avatar
João Lino committed
1371 1372
  mdStageMenu._selection = eStageMenu_NULL;
}
1373

João Lino's avatar
João Lino committed
1374 1375 1376
void runSettingsSelection() {
  switch (mdSettingsMenu._selection) {
    case eSettingsMenu_Pump: {
João Lino's avatar
João Lino committed
1377 1378 1379 1380 1381 1382
        bool bNewPumpStatus = xSetGenericValue( iPumpSpeed ? 0 : 1, PUMP_SPEED_DEFAULT, 0, 1, "pump", "bool" );
        if( cancel ) {
          cancel = false;
          return;
        }
        if ( bNewPumpStatus ) {
João Lino's avatar
João Lino committed
1383
          iPumpSpeed = PUMP_SPEED_MAX_MOSFET;
João Lino's avatar
João Lino committed
1384
        } else {
João Lino's avatar
João Lino committed
1385
          iPumpSpeed = PUMP_SPEED_STOP_MOSFET;
João Lino's avatar
João Lino committed
1386
        }
João Lino's avatar
João Lino committed
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
        analogWrite(PUMP_PIN, iPumpSpeed);
        backToStatus();
        break;
      }
    case eSettingsMenu_PT100_Element: {
        backToStatus();
        break;
      }
    case eSettingsMenu_PT100_Up: {
        backToStatus();
        break;
      }
    case eSettingsMenu_PT100_Down: {
        backToStatus();
        break;
João Lino's avatar
João Lino committed
1402
      }
João Lino's avatar
João Lino committed
1403 1404 1405
    case eSettingsMenu_Back: {
      resetMenu( true );
      break;
1406
    }
João Lino's avatar
João Lino committed
1407
    default: {}
João Lino's avatar
João Lino committed
1408
  }
João Lino's avatar
João Lino committed
1409
  mdSettingsMenu._selection = eSettingsMenu_NULL;
João Lino's avatar
Rel.3  
João Lino committed
1410 1411
}

João Lino's avatar
João Lino committed
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
void runMaltSelection() {
  switch (mdMaltMenu._selection) {
    case eMaltMenu_CastleMalting_Chteau_Pilsen_2RS: {
        backToStatus();
        break;
    }
    case eMaltMenu_CastleMalting_Wheat_Blanc: {
        backToStatus();
        break;
    }
    case eMaltMenu_Back: {
      resetMenu( true );
      break;
    }
    default: {}
João Lino's avatar
Rel.3  
João Lino committed
1427
  }
João Lino's avatar
João Lino committed
1428
  mdMaltMenu._selection = eMaltMenu_NULL;
1429 1430
}

João Lino's avatar
João Lino committed
1431 1432 1433
// ************************ MENU HELPERS ******************************
void runMenuProcessor( MenuData *data ) {
  data->_position = rotaryEncoderVirtualPosition;         // Read position
1434

João Lino's avatar
João Lino committed
1435 1436
  data->_repaint = repaint;                               // Request repaint
  repaint = displayGenericMenu( &lcd, data );             // Display menu
João Lino's avatar
Rel.3  
João Lino committed
1437

João Lino's avatar
João Lino committed
1438
  if ( checkForEncoderSwitchPush( false ) ) {             // Read selection
João Lino's avatar
João Lino committed
1439
    data->_selection = data->_position;
1440
  }
João Lino's avatar
João Lino committed
1441
  
João Lino's avatar
João Lino committed
1442
  (data->_selectionFunction)();                           // Run selection function
1443 1444
}

João Lino's avatar
João Lino committed
1445
void runStageSelection_Generic( unsigned long * selectedStageTime, int *selectedStageTemperature) {
João Lino's avatar
João Lino committed
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
  unsigned long selectedStageTimeStorage = *selectedStageTime;
  int selectedStageTemperatureStorage = *selectedStageTemperature;
  
  *selectedStageTime = getTimer( *selectedStageTime );
  if( cancel ) {
    *selectedStageTime = selectedStageTimeStorage;
    cancel = false;
    return;
  }
  *selectedStageTemperature = getTemperature( *selectedStageTemperature );
  if( cancel ) {
    *selectedStageTime = selectedStageTimeStorage;
    *selectedStageTemperature = selectedStageTemperatureStorage;
    cancel = false;
    return;
  }
João Lino's avatar
João Lino committed
1462
  backToStatus();
1463 1464
}

João Lino's avatar
João Lino committed
1465 1466
void xStartStageHeadless( eCookingStages nextStage, bool bPurgePump ) {
  xStartStage( NULL, NULL, nextStage, bPurgePump, false, false, false );
João Lino's avatar
Rel.3  
João Lino committed
1467 1468
}

João Lino's avatar
João Lino committed
1469 1470
void xStartStageInteractive( unsigned long *stageTime, int *stageTemperature, eCookingStages nextStage ) {
  xStartStage( stageTime, stageTemperature, nextStage, true, true, true, true );
1471 1472
}

João Lino's avatar
João Lino committed
1473
void xStartStage( unsigned long *stageTime, int *stageTemperature, eCookingStages nextStage, bool bPurgePump, bool bSetFinalYield, bool bSetTime, bool bSetTemperature ) {
João Lino's avatar
João Lino committed
1474 1475 1476 1477
  int finalYieldStorage = finalYield;
  unsigned long stageTimeStorage = *stageTime;
  int stageTemperatureStorage = *stageTemperature;
  
João Lino's avatar
João Lino committed
1478
  if (bSetFinalYield) {
João Lino's avatar
João Lino committed
1479 1480 1481 1482 1483 1484
    finalYield = getFinalYield( finalYield, SETTING_MACHINE_YIELD_DEFAULT );
    if( cancel ) {
      finalYield = finalYieldStorage;
      cancel = false;
      return;
    }
João Lino's avatar
Rel.3  
João Lino committed
1485
  }
João Lino's avatar
João Lino committed
1486
  if (bSetTime) {
João Lino's avatar
João Lino committed
1487 1488 1489 1490 1491 1492 1493
    (*stageTime) = getTimer( clockCounter / 1000, *stageTime );
    if( cancel ) {
      finalYield = finalYieldStorage;
      *stageTime = stageTimeStorage;
      cancel = false;
      return;
    }
João Lino's avatar
Rel.3  
João Lino committed
1494
  }
João Lino's avatar
João Lino committed
1495
  if (bSetTemperature) {
João Lino's avatar
João Lino committed
1496 1497 1498 1499 1500 1501 1502 1503
    (*stageTemperature) = getTemperature( cookTemperature, *stageTemperature );
    if( cancel ) {
      finalYield = finalYieldStorage;
      *stageTime = stageTimeStorage;
      *stageTemperature = stageTemperatureStorage;
      cancel = false;
      return;
    }
João Lino's avatar
Rel.3  
João Lino committed
1504
  }
João Lino's avatar
João Lino committed
1505
  xSafeHardwarePowerOff();                      // Stop anything that might be still going on
João Lino's avatar
João Lino committed
1506 1507
  if (bPurgePump) {
    xPurgePump();
1508
  }
1509

João Lino's avatar
João Lino committed
1510 1511 1512
  startBrewing();
  xSetupStage( nextStage );
  backToStatus();
1513
}
João Lino's avatar
João Lino committed
1514
// ##################################################### Menus ###################################################################
1515 1516 1517 1518

// #################################################### Helpers ##################################################################

void startBrewing() {
1519 1520
  //sing(MELODY_SUPER_MARIO, PIEZO_PIN);

1521 1522 1523 1524 1525 1526 1527
  cooking = true;
}

void stopBrewing() {
  cooking = false;
}

João Lino's avatar
João Lino committed
1528 1529 1530
void resetMenu( boolean requestRepaintPaint ) {
  eMenuType = eMenuType_Main;

1531
  if ( requestRepaintPaint ) {
João Lino's avatar
João Lino committed
1532 1533
    repaint = true;
  }
1534

João Lino's avatar
João Lino committed
1535
  xSetupRotaryEncoder( eRotaryEncoderMode_Menu, mdMainMenu._position, MENU_SIZE_MAIN_MENU - 1, 1, 1, 0 );       // reset operation state
João Lino's avatar
João Lino committed
1536 1537
}

1538 1539
void backToStatus() {
  lastInterruptTime = millis() - SETTING_MAX_INACTIVITY_TIME - 1;
João Lino's avatar
João Lino committed
1540
  resetMenu(true);
1541 1542 1543 1544
}
// #################################################### Helpers ##################################################################

// #################################################### Set Variables ##################################################################
João Lino's avatar
João Lino committed
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

int getTemperature(int initialValue ) { return getTemperature( initialValue, initialValue ); }
int getTemperature(int initialValue, int defaultValue ) { return xSetGenericValue( initialValue, defaultValue, TEMPERATURE_MIN_VALUE, TEMPERATURE_MAX_VALUE, MENU_GLOBAL_STR_TEMPERATURE, MENU_GLOBAL_STR_CELSIUS ); }

int getFinalYield( int initialValue ) { return getFinalYield( initialValue, SETTING_MACHINE_YIELD_DEFAULT ); }
int getFinalYield( int initialValue, int defaultValue ) { return xSetGenericValue( initialValue, defaultValue, SETTING_MACHINE_YIELD_CAPACITY_MIN, SETTING_MACHINE_YIELD_CAPACITY_MAX, "Final Yield", "l" ); }

int xSetGenericValue(int initialValue, int defaultValue, int minimumValue, int maximumValue, const char *valueName, const char *unit) {
  xSetupRotaryEncoder( eRotaryEncoderMode_Generic, initialValue, maximumValue, minimumValue, 1, 5 );

  // initialize variables
  int rotaryEncoderPreviousPosition = 0;

  // Setup Screen
  lcd.clear();
  lcd.home();
  lcd.print( "Set " );
  lcd.print( valueName );
  lcd.print( "(" );
  lcd.print( defaultValue );
  lcd.print( ")" );
  lcd.setCursor ( 0 , LCD_VERTICAL_RESOLUTION - 1 );
  lcd.print( "       0 " );
  lcd.print( unit );

  while (true) {
    if( checkForEncoderSwitchPush( true ) ) {                   // Check if pushbutton is pressed
      if( cancel ) return rotaryEncoderVirtualPosition;
      break;
    }
    else {
      xManageMachineSystems();                            // Don't forget to keep an eye on the cooking
    }

    // Check if there was an update by the rotary encoder
    if ( rotaryEncoderVirtualPosition != rotaryEncoderPreviousPosition ) {
      rotaryEncoderPreviousPosition = rotaryEncoderVirtualPosition;

      lcd.setCursor( 0, LCD_VERTICAL_RESOLUTION - 1 );
      lcd.print( "     " );
      if ( rotaryEncoderVirtualPosition < 10 ) {
        lcd.print( "  " );
      }
      else {
        if ( rotaryEncoderVirtualPosition < 100 ) {
          lcd.print( " " );
        }
      }
      lcd.print( rotaryEncoderVirtualPosition );
      lcd.print( " " );
      lcd.print( unit );
      lcd.println( "                " );
    }
  }

  return rotaryEncoderVirtualPosition;
}

int getTimer( int initialValue ) {
  return getTimer( initialValue, initialValue );
}

João Lino's avatar
João Lino committed
1607
int getTimer( int initialValue, int defaultValue ) {
João Lino's avatar
João Lino committed
1608
  // set operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
João Lino's avatar
João Lino committed
1609
  xSetupRotaryEncoder( eRotaryEncoderMode_Time, initialValue, 7200, 0, 1, 30 );
1610 1611

  // initialize variables
service-config's avatar
Mixer  
service-config committed
1612
  int rotaryEncoderPreviousPosition = 0;
1613 1614
  int minutes = 0;
  int seconds = 0;
1615

1616 1617
  // Setup Screen
  lcd.clear();
1618
  lcd.home();
João Lino's avatar
João Lino committed
1619
  lcd.print("Set Time (");
1620
  minutes = defaultValue / 60;
João Lino's avatar
João Lino committed
1621
  lcd.print(minutes);
1622
  seconds = defaultValue - minutes * 60;
João Lino's avatar
João Lino committed
1623
  lcd.print(":");
1624
  if (seconds < 10) {
João Lino's avatar
João Lino committed
1625 1626 1627 1628
    lcd.print("0");
  }
  lcd.print(seconds);
  lcd.print(")");
1629
  lcd.setCursor (0, LCD_VERTICAL_RESOLUTION - 1);
1630
  lcd.print("      0:00");
1631 1632

  while (true) {
João Lino's avatar
João Lino committed
1633 1634
    if( checkForEncoderSwitchPush( true ) ) {
      if( cancel ) return rotaryEncoderVirtualPosition;
1635
      break;
João Lino's avatar
João Lino committed
1636 1637 1638
    }
    else {
      xManageMachineSystems();                            // Don't forget to keep an eye on the cooking
João Lino's avatar
João Lino committed
1639
    }
1640

1641
    // display current timer
service-config's avatar
Mixer  
service-config committed
1642 1643
    if (rotaryEncoderVirtualPosition != rotaryEncoderPreviousPosition) {
      rotaryEncoderPreviousPosition = rotaryEncoderVirtualPosition;
1644 1645 1646 1647 1648 1649
      minutes = rotaryEncoderVirtualPosition / 60;
      seconds = rotaryEncoderVirtualPosition - minutes * 60;

      lcd.setCursor (0, LCD_VERTICAL_RESOLUTION - 1);

      if (minutes < 100) {
João Lino's avatar
João Lino committed
1650 1651
        lcd.print(" ");
      }
1652
      if (minutes < 10) {
João Lino's avatar
João Lino committed
1653 1654 1655
        lcd.print(" ");
      }
      lcd.print("    ");
1656 1657
      lcd.print(minutes);
      lcd.print(":");
1658
      if (seconds < 10) {
1659 1660 1661 1662 1663 1664
        lcd.print("0");
      }
      lcd.print(seconds);
      lcd.println("                ");
    }
  }
1665

service-config's avatar
Mixer  
service-config committed
1666
  return rotaryEncoderVirtualPosition;
1667 1668
}

João Lino's avatar
João Lino committed
1669 1670 1671 1672 1673 1674 1675 1676 1677
boolean checkForEncoderSwitchPush( bool cancelable ) {
  boolean gotPush = digitalRead(ROTARY_ENCODER_SW_PIN);
  if (gotPush) {           // Check if pushbutton is pressed
    unsigned long cancleTimer = millis();
    while (digitalRead(ROTARY_ENCODER_SW_PIN)) {        // Wait until switch is released
      delay(ROTARY_ENCODER_SW_DEBOUNCE_TIME);           // debounce
      
      if( ((millis() - cancleTimer) >= (SETTING_CANCEL_TIMER/2) ) && cancelable ) {
        sing(BUZZ_1, PIEZO_PIN);
1678 1679
      }
    }
1680

João Lino's avatar
João Lino committed
1681 1682
    if( ((millis() - cancleTimer) >= SETTING_CANCEL_TIMER) && cancelable ) {
      cancel = true;
1683 1684
    }
  }
1685

João Lino's avatar
João Lino committed
1686
  return gotPush;
João Lino's avatar
João Lino committed
1687 1688
}

João Lino's avatar
João Lino committed
1689 1690 1691 1692
unsigned long getInactivityTime() {
  unsigned long now = millis();
  unsigned long rotaryEncoderInactivityTime = now - lastInterruptTime;

1693
  if (rotaryEncoderInactivityTime > SETTING_MAX_INACTIVITY_TIME) {
João Lino's avatar
João Lino committed
1694
    if (checkForEncoderSwitchPush( false )) {
1695 1696 1697 1698 1699 1700
      now = millis();
      rotaryEncoderInactivityTime = now - lastInterruptTime;
      rotarySwDetectTime = now;

      repaint = true;
      refresh = true;
João Lino's avatar
João Lino committed
1701 1702
    }
  }
1703

João Lino's avatar
João Lino committed
1704 1705 1706 1707
  unsigned long switchInactivityTime = now - rotarySwDetectTime;
  return rotaryEncoderInactivityTime > switchInactivityTime ? switchInactivityTime : rotaryEncoderInactivityTime ;
}

1708
// ###################### Set Variables ##################################################
1709

João Lino's avatar
Rel.3  
João Lino committed
1710
void xWaitForAction(String title, String message) {
1711
  while (true) {
João Lino's avatar
João Lino committed
1712
    if( checkForEncoderSwitchPush( false ) ) {                   // Check if pushbutton is pressed
João Lino's avatar
Rel.3  
João Lino committed
1713
      break;
João Lino's avatar
João Lino committed
1714 1715
    }
    else {
João Lino's avatar
Rel.3  
João Lino committed
1716 1717 1718
      sing(BUZZ_1, PIEZO_PIN);

      // Print the message
1719
      if (! lcdPrint(&lcd, title, message)) {
João Lino's avatar
Rel.3  
João Lino committed
1720 1721
        break;
      }
1722 1723 1724
    }
  }
}