/*********************************************************************

    Microchip USB C18 Firmware Version 1.0

Filename:        user.c
Dependancies:    See "Includes" section, below.
Processor:       PIC32MX
Hardware:        Refer to AN1166 - USB Generic Function on an Embedded 
                 device
Assembler:       pic32-gcc
Linker:          pic32-ld
Company:         Microchip Technology, Inc.

Software License Agreement

The software supplied herewith by Microchip Technology Incorporated
(the “Company”) for its PICmicro® Microcontroller is intended and
supplied to you, the Company’s customer, for use solely and
exclusively on Microchip PICmicro Microcontroller products. The
software is owned by the Company and/or its supplier, and is
protected under applicable copyright laws. All rights are reserved.
Any use in violation of the foregoing restrictions may subject the
user to criminal sanctions under applicable laws, as well as to
civil liability for the breach of the terms and conditions of this
license.

THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*********************************************************************/

/** I N C L U D E S *************************************************/
#include <GenericTypeDefs.h>
#include <plib.h>
#include "HardwareProfile.h"
#include "USB/usb.h"
#include "USB/usb_device_generic.h"
#include "user.h"


/** V A R I A B L E S ********************************************************/
BYTE counter;
BYTE trf_state;
BYTE temp_mode;

// Packet data buffer
DATA_PACKET dataPacket;

// ADC Conversion Variables.
unsigned int channel4;  // conversion result as read from result buffer
unsigned int channel5;  // conversion result as read from result buffer
unsigned int offset;    // buffer offset to point to the base of the idle buffer

// Temperature Log Variables
BYTE pTemp;                     // Pointer to current logging position, will
                                // loop to zero once the max index is reached
BYTE valid_temp;                // Keeps count of the valid data points
WORD temp_data[30];             // 30 points of data

// Calculate the timer tick period
#define SYS_FREQ            GetSystemClock()
#define PB_DIV              1
#define PRESCALE            256
#define TOGGLES_PER_SEC     8
#define T1_TICK             (SYS_FREQ/PB_DIV/PRESCALE/TOGGLES_PER_SEC)
unsigned int timer_count;

// Potentiometer
#define POT_LIMIT_HI    1023
#define POT_LIMIT_LO    0
#define POT_INC         12
WORD pot_val;
BOOL pot_decreasing;


// define setup parameters for OpenADC10
            // Turn module on | ouput in integer | trigger mode auto | enable autosample
#define PARAM1  ADC_MODULE_ON | ADC_FORMAT_INTG | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON 

// ADC ref external    | disable offset test    | disable scan mode | perform 2 samples | use dual buffers | use alternate mode 
#define PARAM2  ADC_VREF_AVDD_AVSS | ADC_OFFSET_CAL_DISABLE | ADC_SCAN_OFF | ADC_SAMPLES_PER_INT_2 | ADC_ALT_BUF_ON | ADC_ALT_INPUT_ON
            // use ADC interanl clock | set sample time

#define PARAM3  ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_15
            // do not assign channels to scan

#define PARAM4  SKIP_SCAN_ALL
            // set AN4 and AN5 as analog inputs

#define PARAM5  ENABLE_AN4_ANA | ENABLE_AN5_ANA 



/** P R I V A T E  P R O T O T Y P E S ***************************************/

void ResetTempLog(void);
void ReadPOT(void);
void ServiceRequests(void);

// For board testing purpose only
void PICDEMFSUSBDemoBoardTest(void);


/** U S E R   F U N C T I O N S **********************************************/

void UserInit(void)
{
    mInitAllLEDs();

    ResetTempLog();
    temp_mode = TEMP_REAL_TIME;
   
    // Init timer 1
    OpenTimer1(T1_ON|T1_PS_1_256, T1_TICK);

    // Configure and enable the ADC:
    
    CloseADC10();                               // ensure the ADC is off before 
                                                // setting the configuration
    
    SetChanADC10( ADC_CH0_NEG_SAMPLEA_NVREF |   // use ground as neg ref for A
                  ADC_CH0_POS_SAMPLEA_AN4   |   // use AN4 for input A
                  ADC_CH0_NEG_SAMPLEB_NVREF |   // use ground as neg ref for A
                  ADC_CH0_POS_SAMPLEB_AN2);     // use AN5 for input B
    
    OpenADC10(    PARAM1,                       // configure ADC...
                  PARAM2, 
                  PARAM3, 
                  PARAM4, 
                  PARAM5 );
    
    EnableADC10();                              // ...and enable it
    
    // Wait for the first conversion to complete so there 
    // will be vaild data in ADC result registers.
    while ( ! mAD1GetIntFlag() );

}//end UserInit


/******************************************************************************
 * Function:        void ProcessIO(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is a place holder for other user routines.
 *                  It is a mixture of both USB and non-USB tasks.
 *
 * Note:            None
 *****************************************************************************/
void ProcessIO(void)
{
    // Get the ADC Conversion Results:

    // determine which buffer is idle and create an offset 
    offset = 8 * (((~ReadActiveBufferADC10()) & 0x01));

    // read the result of channel 4 conversion from the idle buffer
    channel4 = ReadADC10(offset);

    // read the result of channel 2 conversion from the idle buffer
    channel5 = ReadADC10(offset + 1);

    // Service the requests from the host
    ServiceRequests();

    // Manage temperature logging.
    if(temp_mode == TEMP_LOGGING)
    {
        // Watch for timer interrupt flag
        if(IFS0bits.T1IF == 1)
        {
            IFS0CLR = IFS0_T1_BIT;          // Clear flag

            timer_count++;

            // Every TOGGLES_PER_SEC timer interrupts = 1 second
            if ( (timer_count % TOGGLES_PER_SEC) == 0)
            {
                temp_data[pTemp] = (channel4*41-6400);

                // First update valid_temp
                if(valid_temp < 30)         // 30 data points max
                    valid_temp++;

                // Next update pTemp
                if(pTemp >= 29)
                    pTemp = 0;
                else
                    pTemp++;
            }
        }
    }

} // ProcessIO


void ResetTempLog(void)
{
    pTemp = 0;
    valid_temp = 0;

}


void ReadPOT(void)
{
    pot_val = channel5;

}


void ServiceRequests(void)
{
    BYTE index;
    
    if(USBGenRead((BYTE*)&dataPacket, sizeof(dataPacket)))
    {
        counter = 0;
        switch(dataPacket.CMD)
        {
            case READ_VERSION:
                //dataPacket._byte[1] is len
                dataPacket._byte[3] = MAJOR_VERSION;
                dataPacket._byte[2] = MINOR_VERSION;
                counter=0x04;
                break;

            case UPDATE_LED:
                // LED1 & LED2 are used as USB event indicators.
                if(dataPacket.len == 3)
                {
                    mLED_9 = dataPacket._byte[2];
                    counter = 0x01;
                }//end if
                else if(dataPacket.len == 4)
                {
                    mLED_10 = dataPacket._byte[2];
                    counter = 0x01;
                }//end if else
                break;
                
            case SET_TEMP_REAL:
                temp_mode = TEMP_REAL_TIME;
                ResetTempLog();
                counter = 0x01;
                break;

            case RD_TEMP:
                // Read temperature from ADC Ch4 variable (scale it for the app)
                dataPacket.word_data = (WORD)(channel4*41-6400);
                counter=0x03;
                break;

            case SET_TEMP_LOGGING:
                temp_mode = TEMP_LOGGING;
                ResetTempLog();
                counter=0x01;
                break;

            case RD_TEMP_LOGGING:
                counter = (valid_temp<<1)+2;  // Update count in byte
                dataPacket.len = (valid_temp<<1);

                for(index = valid_temp; index > 0; index--)
                {
                    if(pTemp == 0)
                        pTemp = 29;
                    else
                        pTemp--;
                    dataPacket._word[index] = temp_data[pTemp];
                }//end for
                
                ResetTempLog(); // Once read, log will restart
                break;

            case RD_POT:
                ReadPOT();
                // To Do: Fix this (if needed). 3/9/07 -Bud
                dataPacket._byte[1] = (BYTE)(pot_val &  0xFF);
                dataPacket._byte[2] = (BYTE)(pot_val >> 8);
                counter=0x03;
                break;
                
            case RESET:
                break;
                
            default:
                break;
        }//end switch()

        if(counter != 0)
        {
            if(!mUSBGenTxIsBusy())
                USBGenWrite((BYTE*)&dataPacket,counter);
        }//end if

    }//end if

}//end ServiceRequests

/** EOF user.c ***************************************************************/
