Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
24
Добавлен:
20.02.2016
Размер:
11.5 Кб
Скачать
/**********************************************************************
*
* FileName:        main.c
* Dependencies:    Header (.h) files if applicable, see below
* Processor:       dsPIC33Fxxxx/PIC24Hxxxx
* Compiler:        MPLAB® C30 v3.00 or higher
*
* SOFTWARE LICENSE AGREEMENT:
* Microchip Technology Incorporated ("Microchip") retains all ownership and 
* intellectual property rights in the code accompanying this message and in all 
* derivatives hereto.  You may use this code, and any derivatives created by 
* any person or entity by or on your behalf, exclusively with Microchip's
* proprietary products.  Your acceptance and/or use of this code constitutes 
* agreement to the terms and conditions of this notice.
*
* CODE ACCOMPANYING THIS MESSAGE IS SUPPLIED BY MICROCHIP "AS IS".  NO 
* WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED 
* TO, IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A 
* PARTICULAR PURPOSE APPLY TO THIS CODE, ITS INTERACTION WITH MICROCHIP'S 
* PRODUCTS, COMBINATION WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION. 
*
* YOU ACKNOWLEDGE AND AGREE THAT, IN NO EVENT, SHALL MICROCHIP BE LIABLE, WHETHER 
* IN CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE OR BREACH OF STATUTORY DUTY), 
* STRICT LIABILITY, INDEMNITY, CONTRIBUTION, OR OTHERWISE, FOR ANY INDIRECT, SPECIAL, 
* PUNITIVE, EXEMPLARY, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, FOR COST OR EXPENSE OF 
* ANY KIND WHATSOEVER RELATED TO THE CODE, HOWSOEVER CAUSED, EVEN IF MICROCHIP HAS BEEN 
* ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE.  TO THE FULLEST EXTENT 
* ALLOWABLE BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO 
* THIS CODE, SHALL NOT EXCEED THE PRICE YOU PAID DIRECTLY TO MICROCHIP SPECIFICALLY TO 
* HAVE THIS CODE DEVELOPED.
*
* You agree that you are solely responsible for testing the code and 
* determining its suitability.  Microchip has no obligation to modify, test, 
* certify, or support the code.
*
* REVISION HISTORY:
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Author            Date      Comments on this revision
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* 	
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~**
*
**********************************************************************
* ADDITIONAL NOTES: 
* //The Processor starts with the External Crystal without PLL enabled and then the Clock is switched to PLL Mode.
*
**********************************************************************/


#define __dsPIC33FJ128GP710__
#include "p33fxxxx.h"

#include "adcDrv1.h"
#include "lcd.h"
#include "commonvars.h"

//Macros for Configuration Fuse Registers:
//Invoke macros to set up  device configuration fuse registers.
//The fuses will select the oscillator source, power-up timers, watch-dog
//timers etc. The macros are defined within the device
//header files. The configuration fuse registers reside in Flash memory.


// External Oscillator
_FOSCSEL(FNOSC_FRC);		
_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF  & POSCMD_XT);  
								// Clock Switching is enabled and Fail Safe Clock Monitor is disabled
								// OSC2 Pin Function: OSC2 is Clock Output
								// Primary Oscillator Mode: XT Crystanl


_FWDT(FWDTEN_OFF);              // Watchdog Timer Enabled/disabled by user software
								// (LPRC can be disabled by clearing SWDTEN bit in RCON register

// Definitions for PGA communications
#define CHANNEL 0x4100
#define GAIN 0x4000

const char mytext0[] =  "SPI Demo Code   ";
const char mytext1[] =  "Press S3 to run ";
char topline[] =  "ADC result= ____";
char botline[] =  "ch= Pot Gain= NA";

volatile unsigned char thousand, hundred, tens, ones;
volatile unsigned char adc_lcd_update;
unsigned char S6_debounce = 0;
unsigned char S3_debounce = 0;
unsigned char S4_debounce = 0;
unsigned char PGA_gain = 0;
unsigned char PGA_chan = 0;

/*=============================================================================  
Timer1 INTERRUPT SERVICE ROUTINE
=============================================================================*/
unsigned int LED_Shadow;
void __attribute__((interrupt, no_auto_psv)) _T1Interrupt(void) {
	unsigned int tempVar;
	LED_Shadow++;
	LATA = LED_Shadow;
	IFS0bits.T1IF = 0;
	tempVar++;
	if( tempVar > 2 ) {
		tempVar = 0;
		adc_lcd_update = 1;
	}
}

/*=============================================================================  
Write to SPI (PGA)
=============================================================================*/

void Write_To_PGA(unsigned int Command, unsigned char Value) {
		PORTBbits.RB2 = 0;	// Had to use a GPIO as Chip Select.  Make mental note of this
		SPI1BUF = Command + Value;	// Use a C Library function to alert PGA new gain setting forthcoming
		Delay_Us(1);
		PORTBbits.RB2 = 1;	// Deselect the Chip Select line.
}


/*=============================================================================  
Switch Check (Cause processor moves so fast, we need to detect rising edge only
=============================================================================*/
unsigned char debounce_check_S6() {
	if( PORTDbits.RD7 == 0 ) {	// is button currently pressed?
		if( S6_debounce == 0 ) {	// was it pushed last time we were here?
			S6_debounce = 1;	// set our debounce flag
			return 1;	// unique state, send positive
		}
		else {
			return 0;
		}
	}
	else {
		S6_debounce = 0;	// button is NOT being pushed, so reset everything
	}
	return 0;
}
unsigned char debounce_check_S4() {
	if( PORTDbits.RD13 == 0 ) {	// is button currently pressed?
		if( S4_debounce == 0 ) {	// was it pushed last time we were here?
			S4_debounce = 1;	// set our debounce flag
			return 1;	// unique state, send positive
		}
		else {
			return 0;
		}
	}
	else {
		S4_debounce = 0;	// button is NOT being pushed, so reset everything
	}
	return 0;
}unsigned char debounce_check_S3() {
	if( PORTDbits.RD6 == 0 ) {	// is button currently pressed?
		if( S3_debounce == 0 ) {	// was it pushed last time we were here?
			S3_debounce = 1;	// set our debounce flag
			return 1;	// unique state, send positive
		}
		else {
			return 0;
		}
	}
	else {
		S3_debounce = 0;	// button is NOT being pushed, so reset everything
	}
	return 0;
}

/*=============================================================================  
Convert Hex to ASCII Decimal values
=============================================================================*/

void hex2asciidec( unsigned int hexnum ) {
	thousand = 0;
	hundred = 0;
	tens = 0;
	ones = 0;
 
	while ( hexnum >= 1000 ) {	//check thousands
	  hexnum -= 1000;		    //subtract 1K
	  thousand++;				//increment thousand register
	}
	thousand = thousand + 0x30;	// convert to ASCII for serial display
	while (hexnum >= 100) {		//check hundreds
	  hexnum -= 100;		    //subtract 100
	  hundred++;				//increment hundred register
	}
	hundred = hundred + 0x30;
	while (hexnum >= 10 ) {		//check tens
	  hexnum -= 10;		    	//subtract 10
	  tens++;					//increment tens
	}
	tens = tens + 0x30;
	ones = hexnum + 0x30;				//remaining count equals ones
}

/*=============================================================================  
Main Loop
=============================================================================*/

int main (void) {
	unsigned char ADC_Input = 0;	// a variable to move state machine for ADC input choice
	unsigned char Disp1 = ' ', Disp2 = ' ';			

// Configure Oscillator to operate the device at 40Mhz
// Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
// Fosc= 8M*40/(2*2)=80Mhz for 8M input clock
	PLLFBD=38;					// M=40
	CLKDIVbits.PLLPOST=0;		// N1=2
	CLKDIVbits.PLLPRE=0;		// N2=2
	OSCTUN=0;					// Tune FRC oscillator, if FRC is used
// Disable Watch Dog Timer
	RCONbits.SWDTEN=0;

// Clock switch to incorporate PLL
	__builtin_write_OSCCONH(0x03);		// Initiate Clock Switch to Primary
													// Oscillator with PLL (NOSC=0b011)
	__builtin_write_OSCCONL(0x01);		// Start clock switching
	while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur	

// Wait for PLL to lock
	while(OSCCONbits.LOCK!=1) {};

// Peripheral Initialization
	initPortA();
   	initAdc1();             	// Initialize ADC
	initTmr1();
	Init_LCD();
	Init_SPI1();

// Configure PGA for initial State
	Write_To_PGA(CHANNEL, 0);
	Write_To_PGA(GAIN, PGA_gain);

// Lets put some text on the screen
	home_clr();
	puts_lcd( (unsigned char*) &mytext0[0], sizeof(mytext0) - 1 );
	line_2();
	puts_lcd( (unsigned char*) &mytext1[0], sizeof(mytext1) - 1 );
// Now, lets leave our splash-screen on until user presses a button
	while ( PORTDbits.RD6 == 1 ) ;	// just stay here until a button is pressed.
// Background Loop
    while (1) {
		// update the screen with ADC results
		// but only once in a while due to fading with fast refresh
		if ( adc_lcd_update == 1 ) { // we need to update the screen
			hex2asciidec(ADC_Result);	// get the latest ADC results
			topline[12] = thousand;
			topline[13] = hundred;
			topline[14] = tens;
			topline[15] = ones;
			home_clr();
			puts_lcd( (unsigned char*) &topline[0], sizeof(topline) - 1 );
			line_2();
			puts_lcd( (unsigned char*) &botline[0], sizeof(botline) - 1 );
			adc_lcd_update = 0;	// and reset to get back in.
		}

		// lets monitor the S6 button, and move the ADC as a result             
		if ( debounce_check_S6() ) {
			// then use a state machine to toggle to new ADC
			switch( ADC_Input) {
			case 0:	// transition ADC input from AN5 (pot) to AN4 (temp)
				ADC_Input = 1;	// advance to next stage, anticipate next press
				AD1CHS0 = 0x0004;
				botline[3] = ' ';
				botline[4] = 'T';
				botline[5] = 'm';
				botline[6] = 'p';
				botline[14] = 'N';
				botline[15] = 'A';
				break;
			case 1:	// transition ADC input from AN4 (temp) to AN8 (AGC)
				ADC_Input = 2;
				AD1CHS0 = 0x0008;
				botline[3] = 'P';
				botline[4] = 'G';
				botline[5] = 'A';
				botline[6] = (PGA_chan & 0x01) + 0x30;
				botline[14] = Disp1;
				botline[15] = Disp2;

				break;
			default:	// AGC _and_ catchall
				ADC_Input = 0;
				AD1CHS0 = 0x0005;
				botline[3] = ' ';
				botline[4] = 'P';
				botline[5] = 'o';
				botline[6] = 't';
				botline[14] = 'N';
				botline[15] = 'A';
			}
		}
		if ( (ADC_Input == 2) && debounce_check_S3() ) {
			PGA_chan++;
			if( PGA_chan > 1 ) {
				PGA_chan = 0;
			}
			Write_To_PGA(CHANNEL, PGA_chan);
			botline[6] = (PGA_chan & 0x01) + 0x30;
		}
		if ( (ADC_Input == 2) && debounce_check_S4() ) {
			PGA_gain++;
			if( PGA_gain > 7) {
				PGA_gain = 0;
			}
			switch( PGA_gain) {
			case 0:
				Disp1 = ' ';
				Disp2 = '1';
				break;
			case 1:
				Disp1 = ' ';
				Disp2 = '2';
				break;
			case 2:
				Disp1 = ' ';
				Disp2 = '4';
				break;
			case 3:
				Disp1 = ' ';
				Disp2 = '5';
				break;
			case 4:
				Disp1 = ' ';
				Disp2 = '8';
				break;
			case 5:
				Disp1 = '1';
				Disp2 = '0';
				break;
			case 6:
				Disp1 = '1';
				Disp2 = '6';
				break;
			case 7:
				Disp1 = '3';
				Disp2 = '2';
				break;
			default:
				Disp1 = 'E';
				Disp2 = 'R';
				break;
			}
			Write_To_PGA(GAIN, PGA_gain);
			botline[14] = Disp1;
			botline[15] = Disp2;
		}
	}
}
Соседние файлы в папке CE135_SPI_Demo