/* ========================================
 *
 * Copyright YOUR COMPANY, THE YEAR
 * All Rights Reserved
 * UNPUBLISHED, LICENSED SOFTWARE.
 *
 * CONFIDENTIAL AND PROPRIETARY INFORMATION
 * WHICH IS THE PROPERTY OF your company.
 *
 * ========================================
*/

#include "project.h"
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "stdbool.h"

uint16 ms_count = 0;
uint16 ms_count_boot = 0;
uint16 subcount = 0;
bool buttonFlag;

//#define OMEGA \u03a9;

/*****************************************************************************
* Function Name: FiltInt_ISR()
******************************************************************************
* Summary:
*   An interrupt service routine that is called on a filtered press or release
*	event of a switch.  Each time it is called it clears the interrupt source
*	then increments a filtered count variable.
*
* Parameters:
*   none
*
* Return:
*   None.  Filtered count is incremented.
*
*****************************************************************************/
CY_ISR(FiltInt_ISR)
{
	FiltReset_Write(1); /* clear interrupt source */
    if (buttonFlag == 0) {
        buttonFlag = 1;
        // Do some LED blinking to show the board's "mode" without having to look at the computer screen. Blue blinking light.
        PWM_BLUE_Start();
        PWM_RED_Sleep();
        ms_count = 0;
    } else if (buttonFlag == 1) { 
        buttonFlag = 0;
        // Do some LED blinking to show the board's "mode" without having to look at the computer screen. Red blinking light.
        PWM_RED_Start();
        PWM_BLUE_Sleep();
    } else {
        PWM_RED_Sleep();
        PWM_BLUE_Sleep();
    }
} /* end of FiltInt_ISR() */

// This interrupt is meant to increment a counter every Timer period. 
// When the ADC data is printed to screen, I send the counter value to screen as well.

CY_ISR(MY_ISR) {
    ms_count ++;
    ms_count_boot ++;
}

/*******************************************************************************
* Function Name: main()
********************************************************************************
* Summary:
*   Contains initialization for different components, and a main loop to
*   continually display the value in a global count variable.
*
* Parameters:
*   none
*
* Return:
*   none
*
*****************************************************************************/

int main(void)
{
    uint i = 0u;
	uint32 resultsCounts[9] = {0};
    double resultsV[9] = {0};
    char uartLine[300];
    unsigned int IDAC_setCurrent = 0xFF; 

    double setCurrent[9] = {0}; // = IDAC_setCurrent * 1.2 /(1e6); // Current through DAQ in Amps.
    double resultsOhms[9] = {0};
    double results[9] = {0};
    
    bool currentCheck = 0;
    
    /* Components should be initialized in the following order:
    *   1. interrupts
    *   2. sources of interrupts (clocks are auto-intialized).
    *   3. global interrupt enable
    */
    	
    Timer_1_Start(); //Configure and enable timer
    isr_1_StartEx(MY_ISR); // Point to MY_ISR to carry out interrupt sub-routine

   	FiltInt_StartEx(FiltInt_ISR); /* start filtered interrupt and set ISR function */
   	FiltReset_Write(1); /* source of interrupt (reset) */
	FiltInt_ClearPending(); /* in case an interrupt is still pending */
	CyGlobalIntEnable; /* Enable global interrupts. */

    /* Place your initialization/startup code here (e.g. MyInst_Start()) */
    AMux_Init();
    
	//Make sure you start all the hardware blocks, these functions take all the settings from the configuration GUIs and puts them into the SFRs
	ADC_Start();
	IDAC_Start();
    AMux_Start();
    
    /* Start SCB (UART mode) operation */
    UART_Start();
    UART_UartPutString("\r\n");
    
    for(;;)
    {
        /* Place your application code here. */
        
        CyGlobalIntDisable; /* macro */
        CyGlobalIntEnable; /* macro */
        subcount++;
        i = 0;
        AMux_FastSelect(i);
        for (i=0;i<AMux_CHANNELS;i++) {
			currentCheck = 0;
            
            while (currentCheck == 0) {
                AMux_FastSelect(i);
                IDAC_SetValue(IDAC_setCurrent); 	//Set current dac to the desired current (could be unique per sensor)
			    ADC_StartConvert(); //Start the conversion
            
                while ((ADC_IsEndConversion(ADC_WAIT_FOR_RESULT)) == 0)
                {};	//Stall until complete
			
                resultsCounts[i] = ADC_GetResult16(0);
                
                if ((resultsCounts[i] >= 8000) && (IDAC_setCurrent > 0x01)) {
                    IDAC_setCurrent = IDAC_setCurrent / 2; // Halve the current flowing from the pin to ground (results in a lower V = IR voltage, which gives more
                    setCurrent[i] = IDAC_setCurrent * 1.2/(1e6);
                } else if ((resultsCounts[i] < 8000) && (IDAC_setCurrent == 0x01)) {
                    IDAC_setCurrent = 0x01;
                    setCurrent[i] = IDAC_setCurrent * 1.2/(1e6);
                    currentCheck = 1;
                } else {
                    setCurrent[i] = IDAC_setCurrent * 1.2/(1e6);
                    currentCheck = 1;
                }
            
            }
            
            resultsV[i] = ADC_CountsTo_Volts(0, resultsCounts[i]);
            resultsOhms[i] = resultsV[i] / setCurrent[i];
            
            IDAC_setCurrent = 0xFF;
            
            // Display Results in Counts (Comment out the other two parts about Volts and kOHMS)
            
                        
            /* tmpSign[i] = (resultsCounts[i] < 0) ? "-" : "";
            results[i] = resultsCounts[i];
            */
            
             // Display Results in Volts (Comment out the other two parts about COUNTS and kOHMS)
            
            /*
            results[i] = resultV[i];
            */
            
            // Display Results in kOhms (Comment out the other two parts about COUNTS and Volts)
            
            results[i] = resultsOhms[i];            
		}
        
        if (buttonFlag == 1) {
            sprintf(uartLine, "%08d, %08d, 1 %8.6f %010.2f, 2 %8.6f %010.2f, 3 %8.6f %010.2f, 4 %8.6f %010.2f, 5 %8.6f %010.2f, 6 %8.6f %010.2f, 7 %8.6f %010.2f, 8 %8.6f %010.2f, 9 %8.6f %010.2f", \
                ms_count_boot, ms_count, setCurrent[0], results[0], \
                                         setCurrent[1], results[1], \
                                         setCurrent[2], results[2], \
                                         setCurrent[3], results[3], \
                                         setCurrent[4], results[4], \
                                         setCurrent[5], results[5], \
                                         setCurrent[6], results[6], \
                                         setCurrent[7], results[7], \
                                         setCurrent[8], results[8]);
            //sprintf(uartLine, "%d, %d, %s%d.%04d, %s%d.%0.4d, %s%d.%0.4d, %s%d.%0.4d, %s%d.%0.4d, %s%d.%0.4d, %s%d.%0.4d, %s%d.%0.4d, %s%d.%0.4d, ", \
            //        ms_count_boot, ms_count, tmpSign[0], tmpInt1[0], tmpInt2[0], tmpSign[1], tmpInt1[1], tmpInt2[1], \
            //                                 tmpSign[2], tmpInt1[2], tmpInt2[2], tmpSign[3], tmpInt1[3], tmpInt2[3], \
            //                                 tmpSign[4], tmpInt1[4], tmpInt2[4], tmpSign[5], tmpInt1[5], tmpInt2[5], \
            //                                 tmpSign[6], tmpInt1[6], tmpInt2[6], tmpSign[7], tmpInt1[7], tmpInt2[7], \
            //                                 tmpSign[8], tmpInt1[8], tmpInt2[8]);
        } else {
        
            sprintf(uartLine, "Press button to collect data.");
        }
        
        // Send the text line out of UART.
        UART_UartPutString(uartLine);
        UART_UartPutString("\r\n");
		
		//Lots of conditioning you can do next: 
		
		//You can check to see if the ADC is railed out and then reduce the current to get the voltage accross the sensor to be within ADC range
		
		//You can convert the result (which is voltage) into resistance by dividing the current value (Ohm's Law)
		
		//You can send the data to a UART or other communication block
        
    }
}

/* [] END OF FILE */
 