/** Header Files ***************************************************/
#include <p18f4520.h>
#include <stdio.h>
#include <adc.h>
#include "LCD Module.h"

/** Configuration Bits *********************************************/
#pragma config OSC = INTIO67
#pragma config WDT = OFF
#pragma config LVP = OFF
#pragma config BOREN = OFF
#pragma config XINST = OFF

/** Define Constants Here ******************************************/

/** Local Function Prototypes **************************************/

/** Global Variables ***********************************************/
char line1[17];                         // LCD variables
char line2[17];
unsigned int RA2result = 0;                      // ADC variables
unsigned int RA3result = 0;                      // ADC variables
unsigned int scaledRA2 = 0;
unsigned int scaledRA3 = 0;
unsigned int product;

/*******************************************************************
 * Function:        void main(void)
 ********************************************************************/
#pragma code

void main(void) {
    // Set the clock to 4 MHz
    OSCCONbits.IRCF2 = 1;
    OSCCONbits.IRCF1 = 1;
    OSCCONbits.IRCF0 = 0;

    // Pin IO Setup
    OpenADC(ADC_FOSC_8 & ADC_RIGHT_JUST & ADC_12_TAD,
            ADC_CH0 & ADC_INT_OFF & ADC_REF_VDD_VSS,
            0x0B); // Four analog pins
    TRISA = 0xFF; // All of PORTA input
    TRISB = 0xFF; // All of PORTB input
    TRISC = 0x00; // All of PORTC output
    TRISD = 0x00; // All of PORTD output
    PORTC = 0x00; // Turn off all 8 Port C outputs

    XLCDInit();
    XLCDClear();
    
    XLCDL1home();
    XLCDPutRomString("JOYSTICK");

    sprintf(line2,"RA2/ 5 =%6d", 123456);  // Part A
    XLCDL2home();
    XLCDPutRamString(line2);

    while (1) {
        SetChanADC(ADC_CH2);	// Select the pin
        ConvertADC(); 			// Start conversion
        while( BusyADC() ); 	// Wait for completion
        RA2result = ReadADC(); 	// Read result
        scaledRA2 = RA2result / 5;
        
        SetChanADC(ADC_CH3);	// Select the pin
        ConvertADC(); 			// Start conversion
        while( BusyADC() ); 	// Wait for completion
        RA3result = ReadADC(); 	// Read result
        scaledRA3 = RA3result / 5;
        
        product = scaledRA2 * scaledRA3;
        sprintf(line2,"RA2*RA3=%6u", product);
        XLCDL2home();
        XLCDPutRamString(line2);
    }
}