brew.ino 43.2 KB
Newer Older
1
#define DEBUG
service-config's avatar
Mixer  
service-config committed
2

3 4 5
// ######################### CONSTANTS #########################

// ######################### SETTINGS #########################
6
// ++++++++++++++++++++++++ Heating Element Relay ++++++++++++++++++++++++
7 8 9 10 11 12 13
#define HEATING_ELEMENT_DEFAULT_WINDOW_SIZE	1000
#define HEATING_ELEMENT_OUTPUT_PIN  		24
#define HEATING_ELEMENT_MAX_HEAT_PWM_INTEGER 	5
#define HEATING_ELEMENT_MAX_HEAT_PWM_FLOAT 	5.0
#define HEATING_ELEMENT_MAX_WATTAGE 3000.0					// Minimum = 2000.0
#define HEATING_ELEMENT_AC_FREQUENCY_HZ 50.0

service-config's avatar
Mixer  
service-config committed
14
// ++++++++++++++++++++++++ Temperature ++++++++++++++++++++++++
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#define PT100_BASE_INPUT_PIN 							A4
#define PT100_BASE_OUTPUT_PIN 						30
#define PT100_BASE_TIME_BETWEEN_READINGS	100
#define PT100_UP_INPUT_PIN 								A5
#define PT100_UP_OUTPUT_PIN 							31
#define PT100_UP_TIME_BETWEEN_READINGS		100
#define PT100_DOWN_INPUT_PIN 							A6
#define PT100_DOWN_OUTPUT_PIN 						32
#define PT100_DOWN_TIME_BETWEEN_READINGS	100

#define PT100_BASE_DEFAULT_ADC_VMAX 							1.081
#define PT100_BASE_DEFAULT_VS 										4.87
#define PT100_BASE_DEFAULT_R1_RESISTENCE 					606.0
#define PT100_BASE_DEFAULT_LINE_RESISTENCE 				0.7
#define PT100_BASE_DEFAULT_OPERATION_RESISTENCE 	0.0
#define PT100_UP_DEFAULT_ADC_VMAX 								1.081
#define PT100_UP_DEFAULT_VS 											4.87
#define PT100_UP_DEFAULT_R1_RESISTENCE 						606.0
#define PT100_UP_DEFAULT_LINE_RESISTENCE 					0.7
#define PT100_UP_DEFAULT_OPERATION_RESISTENCE 		0.0
#define PT100_DOWN_DEFAULT_ADC_VMAX 							1.081
#define PT100_DOWN_DEFAULT_VS 										4.87
#define PT100_DOWN_DEFAULT_R1_RESISTENCE 					606.0
#define PT100_DOWN_DEFAULT_LINE_RESISTENCE 				0.7
#define PT100_DOWN_DEFAULT_OPERATION_RESISTENCE 	0.0

service-config's avatar
Mixer  
service-config committed
41
// ++++++++++++++++++++++++ Mixer ++++++++++++++++++++++++
42 43 44 45 46 47 48 49 50 51
//#define MIXER_PIN 		12
//#define MIXER_MAX_POSITION 	255

// ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
#define ROTARY_ENCODER_INTERRUPT_NUMBER	1		// On Mega2560 boards, interrupt 1 is on pin 3
#define ROTARY_ENCODER_CLK_PIN		3		// Used for generating interrupts using CLK signal
#define ROTARY_ENCODER_DT_PIN		22		// Used for reading DT signal
#define ROTARY_ENCODER_SW_PIN		23		// Used for the push button switch
#define ROTARY_ENCODER_DEBOUNCE_TIME		10		// Number of miliseconds to ignore new signals a signal is received

52
// ++++++++++++++++++++++++ State Machine ++++++++++++++++++++++++
53 54 55 56
#define SETTING_WELCOME_TIMEOUT  		100
#define SETTING_MAX_INACTIVITY_TIME  		3000
#define MENU_MAX_DEPTH 				10
#define MENU_INIT_VALUES 			-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
57
#define MENU_SIZE_MAIN_MENU		17
58 59
#define SETTING_SERIAL_MONITOR_BAUD_RATE	9600
#define SETTING_SERIAL_MONITOR_WELCOME_MESSAGE	"Let's start Brewing!"
60

61 62 63 64 65
// ######################### LIBRARIES #########################
// ++++++++++++++++++++++++ LiquidCrystal_I2C ++++++++++++++++++++++++
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#define LCD_I2C_ADDR			0x27		// <<----- Add your address here.  Find it from I2C Scanner
#define LCD_HORIZONTAL_RESOLUTION   	16
#define LCD_VERTICAL_RESOLUTION   	2
#define LCD_BACKLIGHT_PIN		3
#define LCD_EN_PIN  			2
#define LCD_RW_PIN 		 	1
#define LCD_RS_PIN  			0
#define LCD_D4_PIN  			4
#define LCD_D5_PIN  			5
#define LCD_D6_PIN  			6
#define LCD_D7_PIN  			7

// ++++++++++++++++++++++++ PT100 +++++++++++++++++++++++++++++++++
#include <PT100.h>

82 83
// ++++++++++++++++++++++++ ENUM +++++++++++++++++++++++++++++++++
#include "CustomDataStructures.h"
service-config's avatar
Mixer  
service-config committed
84

85
// ######################### VARIABLES #########################
86
// ++++++++++++++++++++++++ State Machine ++++++++++++++++++++++++
87 88 89 90 91 92 93
eRotaryEncoderMode      rotaryEncoderMode;
eMainMenuOptions        mainMenuOption;
ePresetsMenuOptions     presetsMenuOption;
eMaltMenuOptions        maltMenuOption;
eSettingsMenuOptions    settingsMenuOption;
eCookingStages          cookingStage;

94
// ++++++++++++++++++++++++ Global Variables ++++++++++++++++++++++++
95
boolean         cooking;
96
boolean         bStageFirstRun;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

int             clockStartTime;
int             clockCounter;
int							clockIgnore;
boolean         clockStart;
boolean         clockEnd;

int             cookTime;
int             cookTemperature;
//cook_mode_list  cookMode;
//int             cookMixerSpeed;
int             cookHeatPWM;

int 						startpointTime;
int 						betaGlucanaseTime;
int 						debranchingTime;
int 						proteolyticTime;
int 						betaAmylaseTime;
int 						alphaAmylaseTime;
int 						mashoutTime;
int 						recirculationTime;
int 						spargeTime;
int 						boilTime;
int 						coolingTime;

int 						startpointTemperature;
int 						betaGlucanaseTemperature;
int 						debranchingTemperature;
int 						proteolyticTemperature;
int 						betaAmylaseTemperature;
int 						alphaAmylaseTemperature;
int 						mashoutTemperature;
int 						recirculationTemperature;
int 						spargeTemperature;
int 						boilTemperature;
int 						coolingTemperature;

//int 						menuSize;
int             menu_position[MENU_MAX_DEPTH] = {MENU_INIT_VALUES};

boolean         refresh;
boolean         repaint;

// ++++++++++++++++++++++++ Interrupts ++++++++++++++++++++++++
static unsigned long lastInterruptTime;

143 144 145 146 147 148 149 150 151 152 153 154
// ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
volatile int rotaryEncoderVirtualPosition = 0;
volatile int rotaryEncoderMaxPosition = 1;
volatile int rotaryEncoderMinPosition = 0;
volatile int rotaryEncoderSingleStep = 1;
volatile int rotaryEncoderMultiStep = 1;

// ++++++++++++++++++++++++ Heating Element Relay ++++++++++++++++++++++++
int iWindowSize;             // Time frame to operate in
unsigned long windowStartTime;
double dWattPerPulse;

155
// ######################### INITIALIZE #########################
156 157 158 159 160 161 162
// ++++++++++++++++++++++++ Library - LiquidCrystal_I2C ++++++++++++++++++++++++
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);

// +++++++++++++++++++++++ PT100 +++++++++++++++++++++++
PT100 basePT100(PT100_BASE_OUTPUT_PIN, PT100_BASE_INPUT_PIN, PT100_BASE_TIME_BETWEEN_READINGS, PT100_BASE_DEFAULT_ADC_VMAX, PT100_BASE_DEFAULT_VS, PT100_BASE_DEFAULT_R1_RESISTENCE, PT100_BASE_DEFAULT_LINE_RESISTENCE, PT100_BASE_DEFAULT_OPERATION_RESISTENCE);
PT100 upPT100(PT100_UP_OUTPUT_PIN, PT100_UP_INPUT_PIN, PT100_UP_TIME_BETWEEN_READINGS, PT100_UP_DEFAULT_ADC_VMAX, PT100_UP_DEFAULT_VS, PT100_UP_DEFAULT_R1_RESISTENCE, PT100_UP_DEFAULT_LINE_RESISTENCE, PT100_UP_DEFAULT_OPERATION_RESISTENCE);
PT100 downPT100(PT100_DOWN_OUTPUT_PIN, PT100_DOWN_INPUT_PIN, PT100_DOWN_TIME_BETWEEN_READINGS, PT100_DOWN_DEFAULT_ADC_VMAX, PT100_DOWN_DEFAULT_VS, PT100_DOWN_DEFAULT_R1_RESISTENCE, PT100_DOWN_DEFAULT_LINE_RESISTENCE, PT100_DOWN_DEFAULT_OPERATION_RESISTENCE);
163 164

// ######################### INTERRUPTS #########################
165
void xSetupRotaryEncoder( eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep ) {
166 167 168 169 170 171 172 173 174 175 176 177
	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;
}

void isr ()  {		// Interrupt service routine is executed when a HIGH to LOW transition is detected on CLK
  repaint = true;
  refresh = true;
  unsigned long interruptTime = millis();
178
  
179 180 181
  // If interrupts come faster than [ROTARY_ENCODER_DEBOUNCE_TIME]ms, assume it's a bounce and ignore
  if ((interruptTime - lastInterruptTime) > ROTARY_ENCODER_DEBOUNCE_TIME) {
    switch(rotaryEncoderMode) {
182
  
183 184 185 186
      // Input of rotary encoder controling menus
      case eRotaryEncoderMode_Menu: {
        if (!digitalRead(ROTARY_ENCODER_DT_PIN)) {
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderSingleStep);
187 188
        }
        else {
189
            rotaryEncoderVirtualPosition = rotaryEncoderVirtualPosition - rotaryEncoderSingleStep;
190
        }
191 192
        if (rotaryEncoderVirtualPosition > rotaryEncoderMaxPosition) {
            rotaryEncoderVirtualPosition = rotaryEncoderMinPosition;
193
        }
194 195
        if (rotaryEncoderVirtualPosition < rotaryEncoderMinPosition) {
            rotaryEncoderVirtualPosition = rotaryEncoderMaxPosition;
196 197 198 199
        }
        
        break;
      }
service-config's avatar
Mixer  
service-config committed
200
      
201 202
      // Input of rotary encoder controling time variables
      case eRotaryEncoderMode_Time: {
203
				if (!digitalRead(ROTARY_ENCODER_DT_PIN)) {
service-config's avatar
Mixer  
service-config committed
204
          if(rotaryEncoderVirtualPosition >= 60) {
205
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderMultiStep);
206 207
          }
          else {
208
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderSingleStep);
209 210 211
          }
        }
        else {
212
          if(rotaryEncoderVirtualPosition == rotaryEncoderMinPosition) {
service-config's avatar
Mixer  
service-config committed
213
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + 60);
214 215
          }
          else {
216 217
            if(rotaryEncoderVirtualPosition >= (60 + rotaryEncoderMultiStep)) {
              rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition - rotaryEncoderMultiStep);
218 219
            }
            else {
220
              rotaryEncoderVirtualPosition = rotaryEncoderVirtualPosition - rotaryEncoderSingleStep;
221 222 223
            }
          }
        }
224 225
        if (rotaryEncoderVirtualPosition > rotaryEncoderMaxPosition) {
            rotaryEncoderVirtualPosition = rotaryEncoderMaxPosition;
226
        }
227 228
        if (rotaryEncoderVirtualPosition < rotaryEncoderMinPosition) {
            rotaryEncoderVirtualPosition = rotaryEncoderMinPosition;
229 230 231 232
        }
        
        break;
      }
service-config's avatar
Mixer  
service-config committed
233
      
234 235 236 237 238
      // Input of rotary encoder controling generic integer variables within a range between rotaryEncoderMinPosition and rotaryEncoderMaxPosition
      case eRotaryEncoderMode_Generic: {
        if (!digitalRead(ROTARY_ENCODER_DT_PIN)) {
          if ((interruptTime - lastInterruptTime) < ROTARY_ENCODER_DEBOUNCE_TIME) {
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderMultiStep);
239 240
          }
          else {
241
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition + rotaryEncoderSingleStep);
242 243 244
          }
        }
        else {
245 246
          if ((interruptTime - lastInterruptTime) < ROTARY_ENCODER_DEBOUNCE_TIME) {
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition - rotaryEncoderMultiStep);
247 248
          }
          else {
249
            rotaryEncoderVirtualPosition = (rotaryEncoderVirtualPosition - rotaryEncoderSingleStep);
250 251
          }
        }
service-config's avatar
Mixer  
service-config committed
252 253
        if (rotaryEncoderVirtualPosition > rotaryEncoderMaxPosition) {
            rotaryEncoderVirtualPosition = rotaryEncoderMaxPosition;
254
        }
255 256
        if (rotaryEncoderVirtualPosition < rotaryEncoderMinPosition) {
            rotaryEncoderVirtualPosition = rotaryEncoderMinPosition;
service-config's avatar
Mixer  
service-config committed
257 258 259 260
        }
       
        break;
      }
261 262 263 264 265 266 267 268 269 270
      default: {
        
      }
    }
  }
  
  lastInterruptTime = interruptTime;
}

// ######################### START #########################
271 272 273 274 275 276 277 278 279 280 281
void xSafeHardwarePowerOff() {
//  analogWrite(MIXER_PIN, 0);				// Turn mixer OFF for safety
  digitalWrite(HEATING_ELEMENT_OUTPUT_PIN, LOW);	// Turn heading element OFF for safety
	//basePT100.xSafeHardwarePowerOff();									// Turn temperature sensor OFF for safety
}

void displayWelcome() {
  lcdPrint("  Let's start", "    Brewing!");		// Write welcome
  delay(SETTING_WELCOME_TIMEOUT);			// pause for effect
}

282
void setup() {
283 284 285 286 287
	// ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
  pinMode		(ROTARY_ENCODER_CLK_PIN,INPUT);
  pinMode		(ROTARY_ENCODER_DT_PIN, INPUT);
  pinMode		(ROTARY_ENCODER_SW_PIN, INPUT);
  attachInterrupt	(ROTARY_ENCODER_INTERRUPT_NUMBER, isr, FALLING);
288

289 290 291 292 293
	// ++++++++++++++++++++++++ Heating Element Relay ++++++++++++++++++++++++
  pinMode		(HEATING_ELEMENT_OUTPUT_PIN, OUTPUT);
  digitalWrite		(HEATING_ELEMENT_OUTPUT_PIN, LOW);
  windowStartTime = 	millis();
	dWattPerPulse = HEATING_ELEMENT_MAX_WATTAGE / HEATING_ELEMENT_AC_FREQUENCY_HZ;
294

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
	// ++++++++++++++++++++++++ Mixer ++++++++++++++++++++++++
	//  pinMode		(MIXER_PIN, OUTPUT);
	//  analogWrite		(MIXER_PIN, 0);

	// ++++++++++++++++++++++++ Temperature Sensor PT100 ++++++++++++++++++++++++
	//basePT100.setup();
/*
  analogReference	(INTERNAL1V1);					// EXTERNAL && INTERNAL2V56 && INTERNAL1V1
  pinMode		(PT100_OUTPUT_PIN, OUTPUT);	// setup temperature sensor input pin
  digitalWrite		(PT100_OUTPUT_PIN, LOW);		// initialize sensor off
*/
	// ++++++++++++++++++++++++ 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 ++++++++++++++++++++++++
  lcd.begin (LCD_HORIZONTAL_RESOLUTION,LCD_VERTICAL_RESOLUTION);		//  <<----- My LCD was 16x2
  lcd.setBacklightPin(LCD_BACKLIGHT_PIN,POSITIVE);				// Setup backlight pin
  lcd.setBacklight(HIGH);							// Switch on the backlight

	// ######################### INITIALIZE #########################
	// ++++++++++++++++++++++++ Rotary Encoder ++++++++++++++++++++++++
317
	// set operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
318 319 320 321 322 323 324 325 326
	xSetupRotaryEncoder( eRotaryEncoderMode_Disabled, 0, 0, 0, 0, 0 );

	// ++++++++++++++++++++++++ State Machine ++++++++++++++++++++++++
	presetsMenuOption 					=   ePresetsMenu_Trigo;
	maltMenuOption 							=		eMaltMenu_CastleMalting_Chteau_Pilsen_2RS;
	settingsMenuOption 					=		eSettingsMenu_PT100_Element;
	cookingStage 								=		eCookingStage_Startpoint;
	// ++++++++++++++++++++++++ Global Variables ++++++++++++++++++++++++
	cooking                     =   false;
327
  bStageFirstRun              =   true;
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

	clockStartTime              =   0;
	clockCounter                =   0;
	clockIgnore									=		0;
	clockStart                  =   false;
	clockEnd                    =   false;
												
	cookTime                    =   3600;
	cookTemperature             =   25;
	//cookMode                    =   quick_start;
	//cookMixerSpeed              =   120;
	cookHeatPWM                 =   5;

	startpointTime 							=   120;
	betaGlucanaseTime 					=   0;
	debranchingTime 						=   0;
	proteolyticTime 						=   0;
	betaAmylaseTime 						=   3600;
	alphaAmylaseTime 						=   1800;
	mashoutTime 								=   300;
	recirculationTime 					=   1200;
	spargeTime 									=   1200;
	boilTime 										=   5400;
	coolingTime 								=   120;

	startpointTemperature 			=   45;
	betaGlucanaseTemperature 		=   40;
	debranchingTemperature 			=   40;
	proteolyticTemperature 			=   50;
	betaAmylaseTemperature 			=   60;
	alphaAmylaseTemperature 		=   70;
	mashoutTemperature 					=   80;
	recirculationTemperature 		=   80;
	spargeTemperature 					=   80;
	boilTemperature 						=   100;
	coolingTemperature 					=   25;

	refresh                     =   true;
	repaint                     =   true;

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

	// ++++++++++++++++++++++++ PID  ++++++++++++++++++++++++
372
	iWindowSize 									= 	HEATING_ELEMENT_DEFAULT_WINDOW_SIZE;		// Time frame to operate in
373 374 375 376 377 378

// ######################### Code - Run Once #########################
  xSafeHardwarePowerOff();
  displayWelcome();
	
	xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_GO, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
379
}
380

381 382 383
// ######################### START #########################

void loop() {
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  unsigned long inactivityTime = millis() - lastInterruptTime;

  if(inactivityTime > SETTING_MAX_INACTIVITY_TIME) {		// Inactivity check
    if(refresh) {
      repaint = true;
      refresh = false;
    }
    displayStatus();
  }
  else {
    displayMainMenu();
  }
  
  operateMachine();
}

void xPaintStatusTemplate() {
	// Clear LCD
	lcd.clear();      	

	// Position the cursor at the begining of where the temperature template goes onto the screen
	lcd.home();		

	// Print the target and measured temperature template
	if(cooking) {
		lcd.print("ON : 000*C/000*C");
	}
	else {
		lcd.print("OFF: 000*C/000*C");
	}

	// Position the cursor at the begining of where the mode and time template goes onto the screen
	lcd.setCursor (0,LCD_VERTICAL_RESOLUTION-1);

	lcd.print("****       00:00");
}

void displayStatus() {

  // Check whether a template repaint is required
  if(repaint) {
		// Repaint the LCD template
		xPaintStatusTemplate();
    
    // Reset the repaint flag after the repaint has been done
    repaint = false;
  }
  
  // Print positions with no numbers, before the measured temperature value
  lcd.setCursor (3,0);
  if (basePT100.getCurrentTemperature() < 10) {
    lcd.print("  ");
  }
  else {
    if (basePT100.getCurrentTemperature() < 100) {
      lcd.print(" ");
    }
  }

  // Print measured temperature value onto the LCD
  lcd.print(basePT100.getCurrentTemperature(), 1);

  // Print positions with no numbers, before the target temperature value
  lcd.setCursor (11,0);
  if (cookTemperature < 10) {
    lcd.print("  ");
  }
  else {
    if (cookTemperature < 100) {
      lcd.print(" ");
    }
  }

  // Print target temperature value onto the LCD
  lcd.print(cookTemperature);
  
  // Calculate the numbers on the timer clock
  int minutes = (clockCounter - clockIgnore) / 60;
  int seconds = (clockCounter - clockIgnore) - minutes * 60;

  // Position the cursor at the begining of where the timer goes onto the screen
  lcd.setCursor (10, 1);
  
  // Print the timer values onto the LCD
  if (minutes < 10) {
    lcd.print(" 0");
  }
  else {
    if (minutes < 100) {
      lcd.print(" ");
    }
  }
  lcd.print(minutes);
  lcd.print(":");
  if(seconds<10) {
    lcd.print("0");
  }
  lcd.print(seconds);
}

void displayMainMenu() {
  switch(menu_position[0]) {
    case eMainMenu_GO: {
      MainMenu_GO();
      
      menu_position[0] = -1;
			
491
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
492
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_GO, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
493 494 495
      
      break;
    }
496 497 498 499 500
    case eMainMenu_Presets: {
      MainMenu_Presets();
      
      menu_position[0] = -1;
			
501
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
502
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Presets, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
503 504 505
      
      break;
    }
506 507 508 509 510
    case eMainMenu_Malt: {
      MainMenu_Malt();
      
      menu_position[0] = -1;
			
511
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
512
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Malt, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
513 514 515
      
      break;
    }
516 517 518 519 520
    case eMainMenu_Startpoint: {
      MainMenu_Startpoint();
      
      menu_position[0] = -1;
			
521
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
522
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Startpoint, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
523 524 525
      
      break;
    }
526 527 528 529 530
    case eMainMenu_BetaGlucanase: {
      MainMenu_BetaGlucanase();
      
      menu_position[0] = -1;
			
531
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
532
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_BetaGlucanase, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
service-config's avatar
Mixer  
service-config committed
533 534
      
      break;
535 536 537 538 539 540
    }
    case eMainMenu_Debranching: {
      MainMenu_Debranching();
      
      menu_position[0] = -1;
			
541
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
542
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Settings, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
543 544 545
      
      break;
    }
546 547 548 549 550
    case eMainMenu_Proteolytic: {
      MainMenu_Proteolytic();
      
      menu_position[0] = -1;
			
551
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
552 553 554
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Proteolytic, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
555
    }
556 557 558 559 560
    case eMainMenu_BetaAmylase: {
      MainMenu_BetaAmylase();
      
      menu_position[0] = -1;
			
561
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
562 563
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_BetaAmylase, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
564 565
      break;
    }
566 567 568 569 570
    case eMainMenu_AlphaAmylase: {
      MainMenu_AlphaAmylase();
      
      menu_position[0] = -1;
			
571
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
572 573
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_AlphaAmylase, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
574 575
      break;
    }
576 577 578 579 580
    case eMainMenu_Mashout: {
      MainMenu_Mashout();
      
      menu_position[0] = -1;
			
581
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
582 583 584 585 586 587 588 589 590
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Mashout, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
    }
    case eMainMenu_Recirculation: {
      MainMenu_Recirculation();
      
      menu_position[0] = -1;
			
591
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
592
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Recirculation, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
593
      
594 595 596 597
      break;
    }
    case eMainMenu_Sparge: {
      MainMenu_Sparge();
598
      
599 600
      menu_position[0] = -1;
			
601
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
602 603 604 605 606 607 608 609 610
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Sparge, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
    }
    case eMainMenu_Boil: {
      MainMenu_Boil();
      
      menu_position[0] = -1;
			
611
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
612 613 614 615 616 617 618 619 620
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Boil, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
    }
    case eMainMenu_Hops: {
      MainMenu_Hops();
      
      menu_position[0] = -1;
			
621
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
622 623 624 625 626 627 628 629 630
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Hops, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
    }
    case eMainMenu_Cooling: {
      MainMenu_Cooling();
      
      menu_position[0] = -1;
			
631
			// reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
632 633 634 635 636 637 638 639
			xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Cooling, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
    }
    case eMainMenu_Settings: {
      MainMenu_Settings();
      
      menu_position[0] = -1;
640 641 642 643 644 645 646 647 648 649 650 651 652
      
      // reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
      xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Settings, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
      
      break;
    }
    case eMainMenu_Back: {
      MainMenu_Back();
      
      menu_position[0] = -1;
      
      // reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
      xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_Settings, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
653 654 655 656 657 658 659 660 661 662 663
      
      break;
    }
    default: {
      if(repaint) {

        // display menu
        lcd.clear();
        lcd.home (); // go home
        lcd.print("Brewery Menu");
        
service-config's avatar
Mixer  
service-config committed
664
        switch(rotaryEncoderVirtualPosition) {
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
          case eMainMenu_GO: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> GO           ");
            break;
          }
          case eMainMenu_Presets: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Presets      ");
            break;
          }
          case eMainMenu_Malt: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Malt         ");
            break;
          }
          case eMainMenu_Startpoint: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Startpoint   ");
            break;
          }
          case eMainMenu_BetaGlucanase: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> BetaGlucanase");
            break;
          }
          case eMainMenu_Debranching: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Debranching  ");
            break;
          }
          case eMainMenu_Proteolytic: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Proteolytic  ");
            break;
          }
          case eMainMenu_BetaAmylase: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Beta Amylase ");
            break;
          }
          case eMainMenu_AlphaAmylase: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Alpha Amylase");
            break;
          }
          case eMainMenu_Mashout: {
711
            lcd.setCursor (0,1);        // go to start of 2nd line
712
            lcd.print("-> Mashout      ");
713 714
            break;
          }
715
          case eMainMenu_Recirculation: {
716
            lcd.setCursor (0,1);        // go to start of 2nd line
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
            lcd.print("-> Recirculation");
            break;
          }
          case eMainMenu_Sparge: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Sparge       ");
            break;
          }
          case eMainMenu_Boil: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Boil         ");
            break;
          }
          case eMainMenu_Hops: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Hops         ");
            break;
          }
          case eMainMenu_Cooling: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Cooling      ");
            break;
          }
          case eMainMenu_Settings: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Settings     ");
743 744
            break;
          }
745 746 747 748 749
          case eMainMenu_Back: {
            lcd.setCursor (0,1);        // go to start of 2nd line
            lcd.print("-> Back         ");
            break;
          }
750
          default: {
751
            // reset operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
752
						xSetupRotaryEncoder( eRotaryEncoderMode_Menu, eMainMenu_GO, MENU_SIZE_MAIN_MENU - 1, 0, 1, 1 );
753 754 755
          } 
        }
        
756 757 758 759 760 761 762 763
        repaint = false;
      }
      
      if ((digitalRead(ROTARY_ENCODER_SW_PIN))) {		// check if pushbutton is pressed
        menu_position[0] = rotaryEncoderVirtualPosition;
        while (digitalRead(ROTARY_ENCODER_SW_PIN)) {}		// wait til switch is released
        delay(10);                      			// debounce
        break;
764 765 766 767 768
      }
    } 
  }
}

769 770 771 772 773 774 775
void MainMenu_GO() {
	startBrewing();

  backToStatus();
}

void MainMenu_Presets() {
776 777

  backToStatus();
778 779 780 781
	
}

void MainMenu_Malt() {
782 783

  backToStatus();
784 785 786 787 788 789 790
	
}

void MainMenu_Startpoint() {
	startpointTime = getTimer( startpointTime );
	
	startpointTemperature = xSetGenericValue( startpointTemperature, 0, 120, "temperature", "*C" );
791 792

  backToStatus();
793 794 795 796 797 798
}

void MainMenu_BetaGlucanase() {
	betaGlucanaseTime = getTimer( betaGlucanaseTime );
	
	betaGlucanaseTemperature = xSetGenericValue( betaGlucanaseTemperature, 0, 120, "temperature", "*C" );
799 800

  backToStatus();
801 802 803 804 805 806
}

void MainMenu_Debranching() {
	debranchingTime = getTimer( debranchingTime );
	
	debranchingTemperature = xSetGenericValue( debranchingTemperature, 0, 120, "temperature", "*C" );
807 808

  backToStatus();
809 810 811 812 813 814
}

void MainMenu_Proteolytic() {
	proteolyticTime = getTimer( proteolyticTime );
	
	proteolyticTemperature = xSetGenericValue( proteolyticTemperature, 0, 120, "temperature", "*C" );
815 816

  backToStatus();
817 818 819 820 821 822
}

void MainMenu_BetaAmylase() {
	betaAmylaseTime = getTimer( betaAmylaseTime );
	
	betaAmylaseTemperature = xSetGenericValue( betaAmylaseTemperature, 0, 120, "temperature", "*C" );
823 824

  backToStatus();
825 826 827 828 829 830
}

void MainMenu_AlphaAmylase() {
	alphaAmylaseTime = getTimer( alphaAmylaseTime );
	
	alphaAmylaseTemperature = xSetGenericValue( alphaAmylaseTemperature, 0, 120, "temperature", "*C" );
831 832

  backToStatus();
833 834 835 836 837 838
}

void MainMenu_Mashout() {
	mashoutTime = getTimer( mashoutTime );
	
	mashoutTemperature = xSetGenericValue( mashoutTemperature, 0, 120, "temperature", "*C" );
839 840

  backToStatus();
841 842 843 844 845 846
}

void MainMenu_Recirculation() {
	recirculationTime = getTimer( recirculationTime );
	
	recirculationTemperature = xSetGenericValue( recirculationTemperature, 0, 120, "temperature", "*C" );
847 848

  backToStatus();
849 850 851 852 853 854
}

void MainMenu_Sparge() {
	spargeTime = getTimer( spargeTime );
	
	spargeTemperature = xSetGenericValue( spargeTemperature, 0, 120, "temperature", "*C" );
855 856

  backToStatus();
857 858 859 860 861 862
}

void MainMenu_Boil() {
	boilTime = getTimer( boilTime );
	
	boilTemperature = xSetGenericValue( boilTemperature, 0, 120, "temperature", "*C" );
863 864

  backToStatus();
865 866 867
}

void MainMenu_Hops() {
868 869

  backToStatus();
870 871 872
	
}

873
void MainMenu_Cooling() {
874 875 876
	coolingTime = getTimer( coolingTime );
	
	coolingTemperature = xSetGenericValue( coolingTemperature, 0, 120, "temperature", "*C" );
877 878

  backToStatus();
879 880 881
}

void MainMenu_Settings() {
882 883 884

  backToStatus();
  
885 886
}

887 888 889
void MainMenu_Back() {
  backToStatus();
}
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

void xCountTheTime( int temperatureRange ) {
	// Check if the machine is in the right temperature range, for the current mode,
	if(!(basePT100.getCurrentTemperature() > (cookTemperature - temperatureRange) && basePT100.getCurrentTemperature() < (cookTemperature + temperatureRange))) {
		clockIgnore += millis() - clockStartTime - clockCounter;
	}
	
	// Calculate the remaining time on the clock
	clockCounter = cookTime - ((millis() - clockStartTime - clockIgnore) / 1000);
}

bool isTimeLeft() {
	if( clockCounter >= cookTime ) {
		return false;
	}
	return true;
}

908 909 910
double ulWattToWindowTime( double ulAppliedWatts ) {
  double ulPulsesRequired = ulAppliedWatts / dWattPerPulse;
	return (double)iWindowSize / 1000.0 * ulPulsesRequired;
911 912 913
}

bool xRegulateTemperature() {
914
	double difference = basePT100.getCurrentTemperature() - cookTemperature;
915
	bool overTemperature = false;
916
	double wattage = 0.0;
917 918
	
	// Deviation between the cook temperature set and the cook temperature measured
919 920
	if( difference < 0.0 ) {
		difference = difference * (-1.0);
921 922 923 924 925 926 927 928
		overTemperature = true;
	}
	
	// Calculate applied wattage, based on the distance from the target temperature
	if( overTemperature ) {
		// turn it off
		wattage = 0.0;
	} else {
929
		if(difference <= 1) {
930 931 932
			// turn it off
			wattage = 0.0;
		} else {
933
			if(difference <= 3) {
934 935 936
				// pulse lightly at 500 watt
				wattage = 500.0;
			} else {
937
				if(difference <= 6) {
938 939 940
					// pulse moderately at 1000 watt
					wattage = 1000.0;
				} else {
941
					if(difference <= 9) {
942 943 944 945 946 947 948 949 950 951 952 953
						// pulse hardly at 2000 watt
					wattage = 2000.0;
					} else {
						//pulse constantly at HEATING_ELEMENT_MAX_WATTAGE watt
						wattage = HEATING_ELEMENT_MAX_WATTAGE;
					}
				}
			}
		}
	}
	
	// Update the recorded time for the begining of the window, if the previous window has passed
954 955
  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;
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 981 982 983
  }
	
	// Apply wattage to the element at the right time
	if( ulWattToWindowTime( wattage ) > (millis() - windowStartTime)) {
		digitalWrite(HEATING_ELEMENT_OUTPUT_PIN,HIGH);
	} else {
		digitalWrite(HEATING_ELEMENT_OUTPUT_PIN,LOW);
	}
}

void xWarnClockEnded() {
  /// TODO
}

void xStageFirstRun( int stageTime, int stageTemperature ) {
	// Set the clock
	cookTime = stageTime;
	
	// Set the target temperature
	cookTemperature = stageTemperature;
	
	// Reset the clock
	clockStartTime = millis();
	clockIgnore = 0;
}

void xTransitionIntoStage_GlobalVariables(eCookingStages nextStage) {
	// Reset global stage variables
984
	bStageFirstRun = true;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
	cookingStage = nextStage;
}

void xTransitionIntoStage(eCookingStages nextStage) {
	
	// Turn off all hardware that can damage itself if the machine is not cooking
	xSafeHardwarePowerOff();		
	
	// Warn the user a stage has ended
	xWarnClockEnded();
	
	// Reset global stage variables
	xTransitionIntoStage_GlobalVariables( nextStage );
}

void xBasicStageOperation( int iStageTime, int iStageTemperature, int iStageTemperatureRange, eCookingStages nextStage ) {
1001
	if(bStageFirstRun) {
1002
		// Don't run this again
1003
		bStageFirstRun = false;
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 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 1108 1109 1110 1111 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
		
		// When the stage should be skipped
		if( iStageTime == 0) {
			// Continue to the next stage
			xTransitionIntoStage_GlobalVariables( nextStage );
			
			// There is nothing to do, in this stage
			return;
		} else {
			// Set the clock, target temperature and Reset the clock
			xStageFirstRun( iStageTime, iStageTemperature );
		}
	} else {
		// Account for time spent at the target temperature | Input 1: range in ºC within which the target temperature is considered to be reached
		xCountTheTime( iStageTemperatureRange );
		
		if( isTimeLeft() ) {
			// Do temperature control
			xRegulateTemperature();
			
		} else {
			// Continue to the next stage
			xTransitionIntoStage( nextStage );
			
			// There is nothing to do, in this stage
			return;
		}
	}
	// There is nothing to do, in this iteration
	return;
}

void xWarnCookEnded() {
  /// TODO
}

void operateMachine() {

  // Measure temperature, for effect
  basePT100.measure();
	upPT100.measure();
	downPT100.measure();

  // 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();
		
    return;
  }
	
	// Operate the machine according to the current mode
	switch(cookingStage) {
		case eCookingStage_Startpoint: {
			// A basic operation for a basic stage
			xBasicStageOperation( startpointTime, startpointTemperature, 1, eCookingStage_BetaGlucanase );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_BetaGlucanase: {
			// A basic operation for a basic stage
			xBasicStageOperation( betaGlucanaseTime, betaGlucanaseTemperature, 1, eCookingStage_Debranching );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Debranching: {
			// A basic operation for a basic stage
			xBasicStageOperation( debranchingTime, debranchingTemperature, 1, eCookingStage_Proteolytic );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Proteolytic: {
			// A basic operation for a basic stage
			xBasicStageOperation( proteolyticTime, proteolyticTemperature, 1, eCookingStage_BetaAmylase );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_BetaAmylase: {
			// A basic operation for a basic stage
			xBasicStageOperation( betaAmylaseTime, betaAmylaseTemperature, 1, eCookingStage_AlphaAmylase );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_AlphaAmylase: {
			// A basic operation for a basic stage
			xBasicStageOperation( alphaAmylaseTime, alphaAmylaseTemperature, 1, eCookingStage_Mashout );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Mashout: {
			// A basic operation for a basic stage
			xBasicStageOperation( mashoutTime, mashoutTemperature, 1, eCookingStage_Recirculation );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Recirculation: {
			// A basic operation for a basic stage
			xBasicStageOperation( recirculationTime, recirculationTemperature, 1, eCookingStage_Sparge );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Sparge: {
			// A basic operation for a basic stage
			xBasicStageOperation( spargeTime, spargeTemperature, 1, eCookingStage_Boil );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Boil: {
			// A basic operation for a basic stage
			xBasicStageOperation( boilTime, boilTemperature, 1, eCookingStage_Cooling );
			
			// There is nothing to do, in this iteration
			break;
		}
		case eCookingStage_Cooling: {
			// A basic operation for a basic stage
			xBasicStageOperation( coolingTime, coolingTemperature, 1, eCookingStage_Done );
			
			// There is nothing to do, in this iteration
			break;
		}
		default : {
			// Update state
			cooking = false;
			
			// Warn the user that the cooking is done
			xWarnCookEnded();
		}
	}
}

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

void startBrewing() {
  cooking = true;
}

void stopBrewing() {
  cooking = false;
}

void backToStatus() {
  lastInterruptTime = millis() - SETTING_MAX_INACTIVITY_TIME - 1;
}
// #################################################### Helpers ##################################################################

// #################################################### Set Variables ##################################################################
1159
int getTimer(int init) {
1160
	// set operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
1161
	xSetupRotaryEncoder( eRotaryEncoderMode_Time, init, 7200, 0, 1, 30 );
1162 1163

  // initialize variables
service-config's avatar
Mixer  
service-config committed
1164
  int rotaryEncoderPreviousPosition = 0;
1165 1166 1167 1168 1169 1170 1171
  int minutes = 0;
  int seconds = 0;
  
  // Setup Screen
  lcd.clear();
  lcd.home();        
  lcd.print("Set Time");
1172
  lcd.setCursor (0,LCD_VERTICAL_RESOLUTION-1);
1173 1174 1175
  lcd.print("      0:00");
  
  while(true) {
1176 1177 1178 1179 1180 1181 1182 1183 1184
    // Check if pushbutton is pressed
    if ((digitalRead(ROTARY_ENCODER_SW_PIN))) {	
      // Wait until switch is released
			while (digitalRead(ROTARY_ENCODER_SW_PIN)) {}	
      
			// debounce
			delay(10);

			// Job is done, break the circle
1185
      break;
1186 1187 1188 1189
    } else {
			// Don't forget to keep an eye on the cooking
			operateMachine();
		}
1190 1191
    
    // display current timer
service-config's avatar
Mixer  
service-config committed
1192 1193 1194 1195
    if (rotaryEncoderVirtualPosition != rotaryEncoderPreviousPosition) {
      rotaryEncoderPreviousPosition = rotaryEncoderVirtualPosition;
      minutes = rotaryEncoderVirtualPosition/60;
      seconds = rotaryEncoderVirtualPosition-minutes*60;
1196
      
1197
      lcd.setCursor (0,LCD_VERTICAL_RESOLUTION-1);
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
      lcd.print("      ");
      lcd.print(minutes);
      lcd.print(":");
      if(seconds<10) {
        lcd.print("0");
      }
      lcd.print(seconds);
      lcd.println("                ");
    }
  }
  
service-config's avatar
Mixer  
service-config committed
1209
  return rotaryEncoderVirtualPosition;
1210 1211 1212 1213 1214
}

int getTemperature(int init) {
  
  // set operation state
1215
  rotaryEncoderMode = eRotaryEncoderMode_Generic;
service-config's avatar
Mixer  
service-config committed
1216
  rotaryEncoderVirtualPosition = init;  
1217 1218

  // initialize variables
service-config's avatar
Mixer  
service-config committed
1219
  int rotaryEncoderPreviousPosition = 0;
1220 1221 1222 1223 1224
  
  // Setup Screen
  lcd.clear();
  lcd.home();        
  lcd.print("Set Temperature");
1225
  lcd.setCursor (0,LCD_VERTICAL_RESOLUTION-1);
1226 1227
  lcd.print("       0 *C");
  
1228
  rotaryEncoderMaxPosition = TEMPERATURE_SETTING_MAX_VALUE;
service-config's avatar
Mixer  
service-config committed
1229
  
1230
  while(true) {
1231 1232 1233 1234 1235 1236 1237 1238 1239
    // Check if pushbutton is pressed
    if ((digitalRead(ROTARY_ENCODER_SW_PIN))) {	
      // Wait until switch is released
			while (digitalRead(ROTARY_ENCODER_SW_PIN)) {}	
      
			// debounce
			delay(10);

			// Job is done, break the circle
1240
      break;
1241 1242 1243 1244
    } else {
			// Don't forget to keep an eye on the cooking
			operateMachine();
		}
1245 1246
    
    // display current timer
service-config's avatar
Mixer  
service-config committed
1247 1248
    if (rotaryEncoderVirtualPosition != rotaryEncoderPreviousPosition) {
      rotaryEncoderPreviousPosition = rotaryEncoderVirtualPosition;
1249
      
1250
      lcd.setCursor (0,LCD_VERTICAL_RESOLUTION-1);
1251
      lcd.print("     ");
service-config's avatar
Mixer  
service-config committed
1252
      if(rotaryEncoderVirtualPosition<10) {
1253 1254 1255
        lcd.print("  ");
      }
      else {
service-config's avatar
Mixer  
service-config committed
1256
        if(rotaryEncoderVirtualPosition<100) {
1257 1258 1259
          lcd.print(" ");
        }
      }
service-config's avatar
Mixer  
service-config committed
1260
      lcd.print(rotaryEncoderVirtualPosition);
1261 1262 1263 1264 1265
      lcd.print(" *C");
      lcd.println("                ");
    }
  }
  
service-config's avatar
Mixer  
service-config committed
1266
  return rotaryEncoderVirtualPosition;
1267 1268
}

1269
int xSetGenericValue(int init, int min, int max, char *valueName, char *unit) {	
1270
	// set operation state | INPUT : eRotaryEncoderMode newMode, int newPosition, int newMaxPosition, int newMinPosition, int newSingleStep, int newMultiStep
1271
	xSetupRotaryEncoder( eRotaryEncoderMode_Generic, init, max, min, 1, 5 );
1272 1273

  // initialize variables
service-config's avatar
Mixer  
service-config committed
1274
  int rotaryEncoderPreviousPosition = 0;
1275 1276 1277
  
  // Setup Screen
  lcd.clear();
1278 1279 1280 1281 1282 1283 1284 1285
  lcd.home();
  lcd.print( "Set " );
  lcd.print( valueName );
  lcd.setCursor ( 0 , LCD_VERTICAL_RESOLUTION - 1 );
  lcd.print( "       0 " );
	lcd.print( unit );
  
  rotaryEncoderMaxPosition = TEMPERATURE_SETTING_MAX_VALUE;
1286 1287
  
  while(true) {
1288 1289 1290 1291
    // Check if pushbutton is pressed
    if ( digitalRead(ROTARY_ENCODER_SW_PIN) ) {
      // Wait until switch is released
			while ( digitalRead(ROTARY_ENCODER_SW_PIN) ) {}	
1292
      
1293 1294
			// debounce
			delay( 10 );
service-config's avatar
Mixer  
service-config committed
1295

1296
			// Job is done, break the circle
service-config's avatar
Mixer  
service-config committed
1297
      break;
1298 1299 1300 1301
    } else {
			// Don't forget to keep an eye on the cooking
			operateMachine();
		}
service-config's avatar
Mixer  
service-config committed
1302
    
1303 1304
    // Check if there was an update by the rotary encoder
    if( rotaryEncoderVirtualPosition != rotaryEncoderPreviousPosition ) {
service-config's avatar
Mixer  
service-config committed
1305 1306
      rotaryEncoderPreviousPosition = rotaryEncoderVirtualPosition;
      
1307 1308 1309 1310
      lcd.setCursor( 0, LCD_VERTICAL_RESOLUTION - 1 );
      lcd.print( "     " );
      if( rotaryEncoderVirtualPosition < 10 ) {
        lcd.print( "  " );
1311 1312
      }
      else {
1313 1314
        if( rotaryEncoderVirtualPosition < 100 ) {
          lcd.print( " " );
1315 1316
        }
      }
1317 1318 1319
      lcd.print( rotaryEncoderVirtualPosition );
      lcd.print( " *C" );
      lcd.println( "                " );
1320 1321
    }
  }
1322 1323
  
  return rotaryEncoderVirtualPosition;
1324 1325
}

1326
// ###################### Set Variables ##################################################
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337

void lcdPrint(String title, String message) {
  int messageLength = message.length();
  
  lcd.clear();
    
  // print title
  lcd.home();
  lcd.print(title);
    
  // print message
1338 1339
  if(messageLength <= LCD_HORIZONTAL_RESOLUTION) {
    lcd.setCursor(0,LCD_VERTICAL_RESOLUTION-1);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    lcd.print(message);
    delay(1000);
  }
  // print scrolling message
  else {
    String output_message = "                ";
    output_message += message;
    messageLength = output_message.length();
    
    // Adjust the message size for proper printing
    if ( messageLength & 1 == 1 ) {
      output_message+=" ";
      messageLength+=2;
    }
    
    // print scrolling message
1356 1357
    for (int cursor = 0; cursor < messageLength - LCD_HORIZONTAL_RESOLUTION; cursor+=2) {
      lcd.setCursor(0,LCD_VERTICAL_RESOLUTION-1);
1358 1359 1360 1361 1362 1363
      lcd.print(output_message.substring(cursor, cursor+16));
      delay(500);
    }
  }
}