/*******************************************************************************
  MPLAB Harmony Application Header File

  Company:
    Microchip Technology Inc.

  File Name:
    weller.h

  Summary:
    This header file provides prototypes and definitions for the application.

  Description:
    This header file provides function prototypes and data type definitions for
    the application.  Some of these are required by the system (such as the
    "APP_Initialize" and "APP_Tasks" prototypes) and some of them are only used
    internally by the application (such as the "APP_STATES" definition).  Both
    are defined here for convenience.
*******************************************************************************/

//DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2013-2014 released Microchip Technology Inc.  All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
 *******************************************************************************/
//DOM-IGNORE-END

#define PIC32MZ_PCB 1

#ifndef _WELLER_H
#define _WELLER_H

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include "system_config.h"
#include "system_definitions.h"
#include "driver/tmr/drv_tmr.h"
#include "system/ports/sys_ports.h"
#include "system/system.h"
#include "peripheral/spi/plib_spi.h"
#include "peripheral/ports/plib_ports.h"
#include "peripheral/devcon/plib_devcon.h"
#include "system/devcon/sys_devcon.h"

   
// *****************************************************************************
// *****************************************************************************
//  SPI Stuff
// *****************************************************************************
// *****************************************************************************
#define BAUDRATE_100KHZ 100000
#define BAUDRATE_1000KHZ 1000000
    
    
    
// *****************************************************************************
// *****************************************************************************
// Section: Type Definitions
// Port B
// *****************************************************************************
// *****************************************************************************
/*         Implementation specific Definitions                                */
/* RB2  = Iron Control - Active High output */
#define WELLER_HEAT_ON 2

#ifdef PIC32MX_PCB
/* RB3  = LCD RS - Active Low (output) */
#define KS0108_LCD_RST 8
/* RB4  = LCD Enable (output) */
#define KS0108_LCD_E 16
/* RB5  = LCD Chip Select 1 (output) */
#define KS0108_LCD_CS1 32
#endif

/* RB6 - ADC_0 (input)*/
/* RB7 - ADC_1 (input)*/
#define WELLER_Temp_ADC 7
#define REFLOW_Temp_ADC ADCHS_CHANNEL_2
    

#ifdef PIC32MZ_PCB
/* RB4 = LCD_RS (output)*/
#define KS0108_LCD_RS 16
/* RB5  = LCD Chip Select 1 (output) */
#define KS0108_LCD_CS1 32
/* RB5  = LCD Chip Select 2 (output) */
#define KS0108_LCD_CS0 64
#endif

 /****************************************************************************/   
 // The rest of port B   
 /****************************************************************************/   
/* RB8 - LCD0 (output) */
/* RB9 - LCD1 (output) */
/* RB10 - LCD2 (output) */
/* RB11 - LCD3 (output) */
/* RB12 - LCD4 (output) */
/* RB13 - LCD5 (output) */
/* RB14 - LCD6 (output) */
/* RB15 - LCD7 (output) */
#define KS0108_PortBits 0xFF00
   
    
// *****************************************************************************
// Port D
// you really do have the full set of ways of defining the bit masks for each 
//     port!  Tidy this up sometime!
// *****************************************************************************
/* RD0 SPARE */
/* RD1 = SPI_CS1*/
#define ADAU_CSel_Bit 0x002
/* RD2 = SPI_SCK1*/
/* RD3 = SPI_SDI1 = "0000" = input*/
#define SDI_Out 16
/* RD4 = SDI_SDO1 = "1000"*/
/* RD5 = LCD_RW (output)*/
#define KS0108_LCD_RW 32

#ifdef PIC32MX_PCB
/* RD6 = LCD_RS (output)*/
#define KS0108_LCD_RS 64
/* RD7 = LCD_CS (output)*/
#define KS0108_LCD_CS0 128
#endif

/* RD8 = DSP_RESET*/
#define Reset_DSP       0x0100   /* Bit 8 of port D */
/* RD9 = SPI_SS1 - "0111"*/
/* RD10 = RESET_DAC*/
#define Reset_DAC 	0x0400   /* bit 10 of port D */
/* RD11 = UNUSED (output)*/

// *****************************************************************************
// Port E
// This is where the buttons live as the user interface    
// *****************************************************************************
/* RE0 = VDD Drive for UI*/
/* RE1 = MODE_SEL (input)*/
/* RE2 = FN_SEL (input)*/
/* RE3 = PHASEA (input)*/
/* RE4 = PHASEB (input)*/
/* RE5 = SPARE*/
/* RE6 - Rotary_Encoder_Select_0 (input)*/
#define Rotary_Encoder_Select_0 64
/* RE7 - Rotary_Encoder_Select_1 (input)*/
#define Rotary_Encoder_Select_1 128
/*****************************************************************************/
//    Pin identifications for rotary coder headers
//      - These define the coding behaviour
//      - you ought to document these better you lazy sod
/*****************************************************************************/
/* Old Rotary Encoder = 00XXXXXX*/
#define Old_Rotary_Encoder 0x0000
/* Type A rotary Encoder = 10XXXXXX*/
#define Type_A_Rotary_Encoder 0x0080
/* Type B Rotary Encoder = 01XXXXXX*/
#define Type_B_Rotary_Encoder 0x0040
#define Port_E_Button_Pressed   (2+4+8+16)

    
    
// *****************************************************************************
// Port F and G
// *****************************************************************************
/* RF0 EEPROM Chip Select_Active Low*/
#define EEPROM_Select 1
/* RF1 EEPROM Chip Hold_Active Low*/
#define EEPROM_Hold 2
/* RF1 SPARE (output)*/

#ifdef PIC32MZ_PCB
/* RF4  = LCD Reset - Active Low (output) */
#define KS0108_LCD_RST 16
/* RF5  = LCD Enable (output) */
#define KS0108_LCD_E 32
#endif

/* RG6 = SPI_SCK2 */
/* RG7 = SPI_SDI2 "0001" */
/* RG8 = SPI_SDO2 = "0110" */
/* RG9 = SPI_SS2 = "0110" */
    
#define APP_HEARTBEAT_PORT PORT_CHANNEL_B
/* test LED on 32MZ board = B8*/
#define APP_HEARTBEAT_PIN PORTS_BIT_POS_8
#define APP_WELLER_HEATER_PORT PORT_CHANNEL_B
#define APP_WELLER_HEATER_PIN 0x0007   

/* LCD Defines */ 
#ifdef PIC32MX_PCB
#define APP_LCD_PORT_CS0 PORT_CHANNEL_D
#define APP_LCD_PORT_CS1 PORT_CHANNEL_B
#define APP_LCD_PORT_RESET PORT_CHANNEL_B
#define APP_LCD_PORT_RW PORT_CHANNEL_D
#define APP_LCD_PORT_RS PORT_CHANNEL_D
#define APP_LCD_PORT_ENABLE PORT_CHANNEL_B
#define ADAU_SPI_Port SPI_ID_1           // EEPROM on SPI 1
#define EEPROM_SPI_Port SPI_ID_1       
#endif


#ifdef PIC32MZ_PCB
#define APP_DSP_RESET_L_PORT PORT_CHANNEL_B
#define APP_DSP_RESET_L_MASK 0x08
#define DSP_SET_RESET   SYS_PORTS_Clear(PORTS_ID_0, APP_DSP_RESET_L_PORT, APP_DSP_RESET_L_MASK)
#define DSP_CLEAR_RESET SYS_PORTS_Set(PORTS_ID_0,   APP_DSP_RESET_L_PORT, APP_DSP_RESET_L_MASK, APP_DSP_RESET_L_MASK)

#define APP_LCD_PORT_CS0 PORT_CHANNEL_B
#define APP_LCD_PORT_CS1 PORT_CHANNEL_B
#define APP_LCD_PORT_RESET PORT_CHANNEL_F
#define APP_LCD_PORT_RW PORT_CHANNEL_D
#define APP_LCD_PORT_RS PORT_CHANNEL_B
#define APP_LCD_PORT_ENABLE PORT_CHANNEL_F
#define ADAU_SPI_Port SPI_ID_2           // EEPROM on SPI 2
#define EEPROM_SPI_Port  SPI_ID_2  // EEPROM SPI port
#define I2S_CH1 SPI_ID_1
#define I2S_CH2 SPI_ID_4
#define I2S_BAUD_RATE 3150000
#define I2S_CLOCK 12600000
#define I2S_CH1_INT  INT_VECTOR_SPI1
#define I2S_DummyDat 0x00000000
#define Sample_Rate 49218  //this is 12600000/64/4
#endif   

#define APP_LCD_PORT_DATA PORT_CHANNEL_B
    
// USER INTERFACE PORT STUFF
#define APP_UI_PORT PORT_CHANNEL_E
#define APP_UI_PORT_DRIVE 0x0001
#define APP_ENCODER_TYPE_PORT PORT_CHANNEL_E
#define APP_UI_COUNT_MAX 999     //This is arbitrary
#define APP_UI_TMR DRV_TMR_INDEX_1
#define APP_UI_TMR_PERIOD 0x01FF
#define APP_UI_TMR_IS_PERIODIC true


//SPI EEPROM Stuff
#define EEPROM_CHIPSEL_PORT PORT_CHANNEL_F
#define EEPROM_CHIPSEL_BIT 0x0001
#define EEPROM_HOLD_PORT PORT_CHANNEL_F
#define EEPROM_HOLD_BIT 0x0002
#define EEPROM_Disable_Hold SYS_PORTS_Set(PORTS_ID_0, EEPROM_HOLD_PORT, EEPROM_HOLD_BIT, EEPROM_HOLD_BIT)


/***************************************************/
/* Storage related in the hardware implementation  */
/* Stuff to allow memory bank in use to be tracked */
/***************************************************/
#define Mem_Banks_Do_Not_Erase      3
#define Mem_Banks_Erase             4
#define Max_Mem_Banks_With_Erase    4
#define Max_Mem_Banks               2
#define Default_Mem_Bank            0
#define Clear_Buffers_SPI_Time      3
#define Default_Mem_Bank            0
/* How big is each set of data in ROM?*/
#define ParmSet_Array_Size          64
#define Channel_Set_Array_Size      16
/* data locations */
#define Temp_Offset                 0
#define Snooze_Time_Offset          4
#define Tempco_Offset               8
#define Offset_Offset               12
#define P_Offset                    16
#define I_Offset                    20
#define D_Offset                    24
#define Preheat_Offset              28
#define Reflow_Offset               32

/* Approx EEPROM write delay in mS */
#define EEPROM_WR_Delay             10   



/******************************************************************************/
// Hard Coded Defines
// Should not need user change 
/******************************************************************************/    
#define Temp_Start_Max      60 /* Degrees C - at least you can touch this!*/
#define Display_Start_Screen_ms 500 /* once settle temp is ok, display screen */
#define Start_Settle_Timeout 20 /* Seconds - throw error message after this*/
#define Preheat_Time        120 /* Seconds */
#define Preheat_Timeout     30 /* seconds */
#define Soak_Time           90 /* Seconds */
#define Soak_Timeout        30 /* seconds */
#define Reflow_Time         60 /* seconds */
#define Reflow_Hold        45 /* seconds -  accounts for thermal delat in the oven*/
#define Reflow_Temp_Kick   66 /* This is used to drive the PID controller 
                                to be hard on for the reflow period */
#define Reflow_Timeout      30 /* seconds */
#define Ambient             21 /* assume this for target plot */
#define Cool_Time           60 /* seconds */

/******************************************************************************/
// HEater Output Control
/******************************************************************************/
#define Number_Of_Slices    10 /* Slices time into this number of one second slots*/
#define ut_Min              0
#define ut_Max              2000 /* MAximum allowed process drive */
#define Low_Temp_P_Scale    0.3  /* at low temperatures we want to slow the PID open loop heat */
#define Low_Temp_D_Scale    10    /* at low temperatures we want to slow the PID open loop heat */
#define Low_Temp_For_PID    100  /* this is the temperature below which we will reduce P*/

/******************************************************************************/
// Display Graph Constants
/******************************************************************************/
#define Display_Origin_X    18 /* runs from 18 to 128 */
#define Display_Origin_Y    54 /* Runs 54 down to 0 */
#define Display_Scale_X     4  /* seconds per pixel */
#define Display_Scale_Y     5  /* degrees per pixel */

/******************************************************************************/
// Values and limits for the application  
// THESE WILL BE IN DEGREES CELSIUS FOR TEMP     
// THESE WILL BE IN SECONDS FOR TIME     
/******************************************************************************/    
#define	Temp_Step           Temp_Scale    /* Seems like a sensible number = 1 degree*/
#define	Temp_Normal_Speed   1     /* Seems like a sensible number*/
#define	Temp_Speed          10     /* Seems like a sensible number*/
#define	Temp_Min            (20 * Temp_Scale)    /* Seems like a sensible number*/
#define	Temp_Max            (260 * Temp_Scale)  /* Seems like a sensible number*/
#define Temp_Preheat_Max    200    /* needs checking */
#define Temp_Preheat_Default 150  /* This is a guess */
#define Temp_Preheat_Min    20    /* needs checking */
#define Temp_Reflow_Max     260    /* needs checking */
#define Temp_Reflow_Default 200  /* This is a guess */
#define Temp_Reflow_Min     20    /* needs checking */
#define	Temp_Hysteresis     (2 * 256)  /* Seems like a sensible number*/
#define Temp_Default        (21 * 256)
#define Temp_Snooze         (21*256)
#define	Revert_To_Idle      (45 * Snooze_Counts_PerSec)   /* Seems like a sensible number*/
#define	Snooze_Min          (30 * Snooze_Counts_PerSec)   /* Seems like a sensible number*/
#define	Snooze_Max          (3600 * Snooze_Counts_PerSec) /* An hour Seems like a sensible number*/
#define	Snooze_Default      (600  * Snooze_Counts_PerSec) 
#define Snooze_Counts_PerSec 2   /* This should be defined by the ISR Call Rate */
#define P_Normal_Speed      65536
#define P_Speed             655360
#define PID_SCALING         65536 /* scale the integer to float */
#define P_Max               1000 /* needs to be set! */
#define P_Min               10 /* needs to be set! */
#define P_Default           150 /* this needs to ne defined! */
#define I_Normal_Speed      6553
#define I_Speed             65536
#define I_Max               20 /* needs to be set! */
#define I_Min               0.0 /* needs to be set! */
#define I_Default           2 /* this needs to ne defined! */
#define Integral_Max        (500 * Temp_Scale)  /* a big number */
#define Integral_Min        (-500 * Temp_Scale) /* a big number */
#define D_Normal_Speed      65536
#define D_Speed             655360
#define D_Max               1000 /* needs to be set! */
#define D_Min               0.1 /* needs to be set! */
#define D_Default           2 /* this needs to ne defined! */
#define Tempco_Normal_Speed 1
#define Tempco_Speed        8
#define TempOffset_Normal_Speed 1
#define TempOffset_Speed    48
#define Tempco_Scale        1024
#define Temp_Scale          256
#define	Tempco_Min          (-10*Tempco_Scale) /* (This is in LSB --> Degc) scaled by 256*/
#define	Tempco_Max          (10*Tempco_Scale) /* (This is in LSB --> Degc) scaled by 256*/
#define Tempco_Default      ((Tempco_Scale*3300)/(4096*5))    /* (This is in LSB --> Degc) scaled by 256*/
#define	Temp_Offset_Min     (-600 * Temp_Scale) /* This is in Degrees * 256*/
#define	Temp_Offset_Max     ( 6000 * Temp_Scale) /* This is in Degrees * 256*/
#define	Temp_Offset_Default   -500 /* This is the offset for 2.5V offset on the input*/
#define Snooze_Normal_Speed (5 * Snooze_Counts_PerSec)
#define Snooze_Speed        (60 * Snooze_Counts_PerSec)
#define Error_Msg_Time      2000 /* ms */


#define ADC_Filter_Coeff    26 /* ADC_Filter_Coeff/256 of new data added to
                                 (256-ADC_Filter_Coeff)/256 of old data */  
#define ADC_Filter_Scale    256 /* max filter scale */
    
/*****************************************************************************/
// EEPROM Hardware Related Definitions
/*****************************************************************************/
#define CselEEPROM DelayUs(1); SYS_PORTS_Set(PORTS_ID_0, APP_EEPROM_PORT, EEPROM_Select, EEPROM_Select); DelayUs(1);
#define CselClearEEPROM DelayUs(1); SYS_PORTS_Clear(PORTS_ID_0, APP_EEPROM_PORT, EEPROM_Select, EEPROM_Select); DelayUs(1);
#define HoldClearEEPROM DelayUs(1); SYS_PORTS_Set(PORTS_ID_0, APP_EEPROM_PORT, EEPROM_Hold, EEPROM_Hold); DelayUs(1);
#define HoldEEPROM DelayUs(1); SYS_PORTS_Clear(PORTS_ID_0, APP_EEPROM_PORT, EEPROM_Hold, EEPROM_Hold); DelayUs(1);
#define EEPROM_INIT_DELAY 10
#define EEPROM_Sel_Delay 2
    
/******************************************************************************/
/* Deal with SPI Write for Harmony which does not include a blocking write    */
/******************************************************************************/
#define PLIB_SPI_WRITE_C(_CHOSEN_SPI_Port, _CHOSEN_WREN) PLIB_SPI_BufferWrite(_CHOSEN_SPI_Port, _CHOSEN_WREN); while (!PLIB_SPI_ReceiverBufferIsFull(_CHOSEN_SPI_Port))


/* more stuff Use this bitfield to watch what buttons are happening... */
#define HMI_Port SYS_PORTS_Read( PORTS_ID_0, APP_UI_PORT )
#define  Exit (unsigned char) 2         // bit 1 of port E
#define  Sel (unsigned char)  4         // bit 2 of port E
#define  Vals_0 (unsigned char) 8       // bit 3 of port E
#define  Vals_1 (unsigned char) 16      // bit 4 of port E

/***************************************************/
//  User interface behaviour control
// These define how long before increments on the rotary encoder go from
// "slow increments" to fast increments
// then how lond before "fast" reverts to "slow" again
/***************************************************/
#define Speed_Init     1
#define Auto_Revert_Init_Val 400000
#define Key_Press_Delay_Us 150
#define Slow_Counter_Init 50000
#define Fast_Counter_Init 7
    
/***************************************************/
/* Behaviour of the Rotary Encoder                 */
/***************************************************/
#define Phase_0 (unsigned char) 0
#define Phase_1 Vals_0
#define Phase_2 Vals_0 + Vals_1
#define Phase_3 Vals_1
#define Rot_Up Vals_1
#define Rot_Down Vals_0 + Vals_1
/* Old Rotary Encoder = 00XXXXXX*/
#define Encoder_Type_Is_Old (!(SYS_PORTS_Read( PORTS_ID_0, APP_ENCODER_TYPE_PORT ) & (Type_A_Rotary_Encoder + Type_B_Rotary_Encoder)))
/* Type A rotary Encoder = 10XXXXXX*/
#define Encoder_Type_Is_TypeA (SYS_PORTS_Read( PORTS_ID_0, APP_ENCODER_TYPE_PORT ) & Type_A_Rotary_Encoder)
/* Type B Rotary Encoder = 01XXXXXX*/
#define Encoder_Type_Is_TypeB (SYS_PORTS_Read( PORTS_ID_0, APP_ENCODER_TYPE_PORT ) & Type_B_Rotary_Encoder)
#define Drive_PortE_Out SYS_PORTS_Set(PORTS_ID_0, APP_UI_PORT, APP_UI_PORT_DRIVE, APP_UI_PORT_DRIVE)
    
/***************************************************/
//  User input
/***************************************************/
#define Up_Keys (Keypress_Read == Vals_1)
#define Down_Keys (Keypress_Read == (Vals_0 + Vals_1))
#define Sel_Key (Keypress_Read == Sel)
#define Exit_Key (Keypress_Read == Exit)

    
// *****************************************************************************
// *****************************************************************************
/* Application states
  Summary:
   he first set are Application states enumeration
  Description:
    This enumeration defines the valid application states.  These states
    determine the behavior of the application at various times.
*/
// *****************************************************************************
// *****************************************************************************
typedef enum
{
	/* Application's state machine's initial state. */
	WELLER_STATE_INIT=0,
	WELLER_STATE_LCDINIT,
	WELLER_STATE_IDLE,
	WELLER_STATE_SERVICE_TASKS,
    WELLER_STATE_CHOOSING,
    WELLER_STATE_OPERATIONAL,
	WELLER_STATE_TEMP_SET,
	WELLER_STATE_SENSOR_OFFSET,
	WELLER_STATE_SENSOR_OFFSET_CHANGE,
    WELLER_STATE_SENSOR_COEFF,
	WELLER_STATE_SENSOR_TEMPCO,
    WELLER_STATE_SETPOINTS,
    WELLER_STATE_PREHEAT,
    WELLER_STATE_REFLOW,
    WELLER_STATE_SENSOR_COEFF_CHANGE,
    WELLER_STATE_PID,
    WELLER_STATE_PID_P,
    WELLER_STATE_PID_I,
    WELLER_STATE_PID_D,
    WELLER_STATE_SAVE,
    WELLER_STATE_START,
    WELLER_STATE_PLOT,
            
	/* TODO: Define states used by the application state machine. */
} WELLER_STATES;


typedef enum
{
	/* Application's state machine's initial state. */
	WELLER_ACTION_INIT=0,
	WELLER_ACTION_SENSOR_OFFSET,
    WELLER_ACTION_SENSOR_COEFF,
    WELLER_ACTION_TEMPCO,
    WELLER_ACTION_SLEEP,
    WELLER_ACTION_SETPOINTS,
    WELLER_ACTION_PID,
    WELLER_ACTION_SAVE,  /* Though not used in this application */
    WELLER_ACTION_START,
    WELLER_ACTION_YES,
    WELLER_ACTION_NO
            
	/* TODO: Define states used by the application state machine. */
} WELLER_ACTIONS;


//****************************************************************************//
/* This lot are state machine dat for the user interface                      */
//****************************************************************************//

/* Auto Repeat Counts - how long to wait before starting to Auto Repeat*/
#define Auto_Repeat_Count 6

/* Stuff to allow modes to be tracked Use these to control the state machine  */
#define Choosing_Fn     0
#define Set_Mode        1
#define Save_Mode       2
#define Load_Mode       3

/* Stuff to allow functions to be tracked in Set mode */
#define Temperature_Set 10
#define Sleep_Time_Set  11
#define Sensor_Tempco   12
#define Sensor_Offset   13


/*Stuff to allow functions to be tracked in Save mode */
#define Save_Sel_Fn 	20

/* Stuff to allow functions to be tracked in Load mode */
#define Load_Sel_Fn 	30

/*  Frequency Speed Function */
#define Freq_Speed_Counter_1_fn 	666


/*****************************************************************************/
/*****************************************************************************/
/*                     DISPLAY RELATED DATA                                  */
/*****************************************************************************/
/*****************************************************************************/
/* Display Strings */
#define UI_DIV 2500    // divider for UI ISR to display update
#define Update_UI_Timer (wellerData.UI_Update_Counter > UI_DIV)
#define Reset_UI_Timer wellerData.UI_Update_Counter = 0
#define Blank_Char_Init 	0x20
#define Line1_Init      	"  Reflow Oven   "
#define Line2_Init          "Reflow V1.3 2019"
#define ClearScreen  GLCD_ClearScreen_buff(ScreenBuff);  Buffer_Refresh(ScreenBuff, 0, 0, 128, 64);
#define APP_LCD_DATA_LOC 0xFF00 
#define UI_Temp_Meas_Update_Threshold Temp_Scale
// Graphics Macros
#define Refresh_LCD GLCD_WriteBuf(ScreenBuff, 0, 0, KS0108_SCREEN_WIDTH, KS0108_SCREEN_HEIGHT);
#define UI_Set_X 54
#define UI_Set_Y 26 
#define UI_Meas_X 54
#define UI_Meas_Y 48
#define UI_BootClr_X1 0
#define UI_BootClr_Y1 26 
#define UI_BootClr_X2 128
#define UI_BootClr_Y2 64
#define UI_BootVer_X 0
#define UI_BootVer_Y 26 
#define UI_BootMod_X 0
#define UI_BootMod_Y 48
#define Zap_X        111
#define Zap_Y        24
#define Zap_X_Reflow 111
#define Zap_Y_Reflow 0
#define Saved_X      58
#define Saved_Y      48
#define Plot_L1x    52
#define Plot_L1y    36
#define Plot_L2x    52
#define Plot_L2y    2
#define Plot_L3x    52
#define Plot_L3y    45
#define Plot_L4x    52
#define Plot_L4y    28
#define Temoco_L1x    0
#define Temoco_L1y    0
#define Temoco_L2y    14
#define Temoco_L3y    28
#define Temoco_L4y    42
#define Start_L1y    0
#define Start_L2y    14
#define Start_L3y    37
#define Start_L4y    51
#define Q4_Graphic_x    64
#define Q4_Graphic_y    32
#define Snooze_Line1_x    0
#define Snooze_Line1_y    40
#define Snooze_Bar_Max KS0108_SCREEN_WIDTH
#define Snooze_Bar_Row KS0108_SCREEN_HEIGHT

// *****************************************************************************
// *****************************************************************************
/* Application Data

  Summary:
    Holds application data

  Description:
    This structure holds the application's data.

  Remarks:
    Application strings and buffers are be defined outside this structure.
 */
// *****************************************************************************
// *****************************************************************************

typedef struct
{
    /* The application's current state */
    WELLER_STATES       state;
    /* UI driver timer handle. */
    DRV_HANDLE          UI_Timer;
    /* UI timer timeout count. */
    int                 UI_Count;
    /* UI fast count. */
    int                 UI_Fast_Count;
    /* UI slow count. */
    int                 UI_Slow_Count;
    /* UI update count. */
    int                 UI_Update_Counter;
    /* UI speed - change rate per click. */
    unsigned int        UI_Speed;
    /* UI needs update */
    bool                UI_Update_Display;
    /* UI needs update */
    bool                UI_Display_Lockout;
    /* Flag to say a key has been pressed */
    bool                UI_Keypressed;
    /* UI action */
    WELLER_ACTIONS      UI_Action;
    /* Heartbeat driver timer handle. */
    DRV_HANDLE          heartbeatTimer;
    /* Heartbeat timer timeout count. */
    unsigned int        heartbeatCount;
    /* Heartbeat LED toggle flag. */
    bool                heartbeatToggle;
    unsigned int        MemoryBankSelected;
    /* desired temp in degrees C time 256 */
    int                 Temp_Set;
    /* measured Temp in Degrees time 256 C*/
    int                 Temp_Meas;
    /* Previous measured Temp in Degrees time 256 C*/
    int                 Prev_Temp_Meas;
    /* Last Updated Temp in Degrees time 256 C*/
    int                 Temp_Last_Update;
    /* Offset Temp in Degrees C times 256*/
    int                 Temp_Sensor_Offset;
    /* Offset Temp in Degrees C times 256*/
    int                 Temp_Sensor_Offset_Old;
    /* Tempco scaling factor times 256*/
    int                 Temp_Coeff;
    /* Tempco scaling factor times 256*/
    int                 Temp_Coeff_Old;
    /* PID Proportional value*/
    float               PID_P;
    /* PID Integral value*/
    float               PID_I;
    /* PID Differential value*/
    float               PID_D;
    /* Old PID Proportional value*/
    float               PID_P_Old;
    /* Old PID Integral value*/
    float               PID_I_Old;
    /* Old PID Differential value*/
    float               PID_D_Old;
    /* Soak Temperature */
    int                 Temp_Preheat;
    /* Soak Temperature old*/
    int                 Temp_Preheat_Old;
    /* Reflow Temp*/    
    int                 Temp_Reflow;
    /* Reflow Temperature old*/
    int                 Temp_Reflow_Old;
    /* Snoose Counter*/    
    int                 Snooze_Counter;
    /* Snoose Flag*/
    bool                Snooze_Flag;
    /* Snoose Value*/
    int                 Snooze;    
    /* Counter for Revert to Idle */
    int                 Revert_To_Idle_Counter;
    /* Used to hold Temp value if changing */
    int                 Temp_Set_Backup;
    /* heater On */
    unsigned int        Heater_On;
    /* Timer for process */
    int                 Process_Time;
    /* Previous Value of Timer for process */
    int                 Process_Time_Previous;
    /* Time at end of start cooldown */
    int                 Start_Time_End;
    /* Time at end of Preheat */
    int                 Preheat_Time_End;
    /* Time at end of Soak */
    int                 Soak_Time_End;
    /* Time at end of Reflow */
    int                 Reflow_Time_End;
    /* Process Done */
    bool                Done;
    /* Stare Process Done */
    bool                Start_Settle_Done;
    /* Preheat Process Done */
    bool                Preheat_Done;
    /* Soak Process Done */
    bool                Soak_Done;
    /* Reflow Process Done */
    bool                Reflow_Done;
    /* Float u(t) the PID PRocess Drive*/
    float               ut;
    /* Previous Error */
    float               Error_Prev;
    /* Integral */
    float               Integral;
    /* Differential */
    float               Differential;
 
} WELLER_DATA;

/**************************************************************************/
// It would be perfectly reasonable to absorb this into WELLER_DATA
/**************************************************************************/
typedef struct{
		int Temperature;     /* Temperature is in Degrees C*/
		int Snooze_Time;     /* Time is in seconds*/
		int Sensor_Tempco_Val;     /* Tempco of iron's temp sensor*/
		int Sensor_Offset_Val;     /* Offset of iron's temp sensor*/
}  data_val_struct ;

/* Can't believe I have to define this!!! */
#define Pi (double) 3.141592653590
#define sqrt2 (double) 1.414213562373
#define SpeedOfSound 341210   /* millimetres per second */


// *****************************************************************************
// *****************************************************************************
// Section: Application Implementation Specific Definitions
// *****************************************************************************
// *****************************************************************************
/*** Application Defined Pins ***/
// TIMER STUFF
#define APP_HEARTBEAT_TMR DRV_TMR_INDEX_0
#define APP_HEARTBEAT_TMR_IS_PERIODIC true
#define APP_HEARTBEAT_TMR_PERIOD 0x4A5C
#define APP_HEARTBEAT_COUNT_MAX 13



// LCD PORT STUFF
#ifdef PIC32MX_PCB
#define APP_LCD_PORT_CS0 PORT_CHANNEL_D
#define APP_LCD_PORT_CS1 PORT_CHANNEL_B
#define APP_LCD_PORT_RESET PORT_CHANNEL_B
#define APP_LCD_PORT_RW PORT_CHANNEL_D
#define APP_LCD_PORT_RS PORT_CHANNEL_D
#define APP_LCD_PORT_ENABLE PORT_CHANNEL_B
#define ADAU_SPI_Port SPI_ID_1           // EEPROM on SPI 1
#define EEPROM_SPI_Port SPI_ID_1       
#endif

#ifdef PIC32MZ_PCB
#define APP_DSP_RESET_L_PORT PORT_CHANNEL_B
#define APP_DSP_RESET_L_MASK 0x08
#define DSP_SET_RESET   SYS_PORTS_Clear(PORTS_ID_0, APP_DSP_RESET_L_PORT, APP_DSP_RESET_L_MASK)
#define DSP_CLEAR_RESET SYS_PORTS_Set(PORTS_ID_0,   APP_DSP_RESET_L_PORT, APP_DSP_RESET_L_MASK, APP_DSP_RESET_L_MASK)

#define APP_LCD_PORT_CS0 PORT_CHANNEL_B
#define APP_LCD_PORT_CS1 PORT_CHANNEL_B
#define APP_LCD_PORT_RESET PORT_CHANNEL_F
#define APP_LCD_PORT_RW PORT_CHANNEL_D
#define APP_LCD_PORT_RS PORT_CHANNEL_B
#define APP_LCD_PORT_ENABLE PORT_CHANNEL_F
#define ADAU_SPI_Port SPI_ID_2           // EEPROM on SPI 2
#define EEPROM_SPI_Port  SPI_ID_2  // EEPROM SPI port
#define I2S_CH1 SPI_ID_1
#define I2S_CH2 SPI_ID_4
#define I2S_BAUD_RATE 3150000
#define I2S_CLOCK 12600000
#define I2S_CH1_INT  INT_VECTOR_SPI1
#define I2S_DummyDat 0x00000000
#define Sample_Rate 49218  //this is 12600000/64/4
#endif


#define APP_LCD_PORT_DATA PORT_CHANNEL_B




// *****************************************************************************
// *****************************************************************************
// Section: Application Callback Routines
// *****************************************************************************
// *****************************************************************************
/* These routines are called by drivers when certain events occur.
*/
	
// *****************************************************************************
// *****************************************************************************
// Section: Application Initialization and State Machine Functions
// *****************************************************************************
// *****************************************************************************

/*******************************************************************************
  Function:
    void WELLER_Initialize ( void )

  Summary:
     MPLAB Harmony application initialization routine.

  Description:
    This function initializes the Harmony application.  It places the 
    application in its initial state and prepares it to run so that its 
    APP_Tasks function can be called.

  Precondition:
    All other system initialization routines should be called before calling
    this routine (in "SYS_Initialize").

  Parameters:
    None.

  Returns:
    None.

  Example:
    <code>
    WELLER_Initialize();
    </code>

  Remarks:
    This routine must be called from the SYS_Initialize function.
*/

void WELLER_Initialize ( void );


/*******************************************************************************
  Function:
    void WELLER_Tasks ( void )

  Summary:
    MPLAB Harmony Demo application tasks function

  Description:
    This routine is the Harmony Demo application's tasks function.  It
    defines the application's state machine and core logic.

  Precondition:
    The system and application initialization ("SYS_Initialize") should be
    called before calling this.

  Parameters:
    None.

  Returns:
    None.

  Example:
    <code>
    WELLER_Tasks();
    </code>

  Remarks:
    This routine must be called from SYS_Tasks() routine.
 */

void WELLER_Tasks( void );


#endif /* _WELLER_H */

//DOM-IGNORE-BEGIN
#ifdef __cplusplus
}
#endif
//DOM-IGNORE-END

/*******************************************************************************
 End of File
 */

void Idle_Screen(void);

void Update_Temp_Meas(int);

void WELLER_EEPROM_Initialize(void);
