/*******************************************************************************
 *	TestLed.c		Greenpower CarComputer Test Program
 *				T.Barnaby,	BEAM Ltd,	2008-02-28
 *
 *	Copyright (c) Beam Ltd and Chipping Sodbury School
 *******************************************************************************
 *
 * Function:	To flash the 4 LED's
 * Version:	1.0
 */
#include <pic18f2520.h>

#define	CLOCK		4000000		// Clock frequency

typedef unsigned char	uchar;
typedef unsigned short	ushort;
typedef unsigned long	ulong;

/*******************************************************************************
 *	PIC Configuration. Ignored when using serial boot loader
 *******************************************************************************
 */
code char at __CONFIG1H _conf0	= _OSC_HS_1H;
code char at __CONFIG2L _conf1	= _PWRT_OFF_2L & _BOREN_OFF_2L;
code char at __CONFIG2H _conf2	= _WDTPS_512_2H & _WDT_OFF_2H;
code char at __CONFIG3H _conf3	= _MCLRE_ON_3H & _PBADEN_OFF_3H & _CCP2MX_PORTC_3H;
code char at __CONFIG4L _conf4	= _STVREN_ON_4L & _LVP_OFF_4L & _XINST_OFF_4L & _DEBUG_OFF_4L;

code char at __CONFIG5L _conf5	= _CP0_OFF_5L & _CP1_OFF_5L & _CP2_OFF_5L & _CP3_OFF_5L;
code char at __CONFIG5H _conf6	= _CPB_OFF_5H & _CPD_OFF_5H;
code char at __CONFIG6L _conf7	= _WRT0_OFF_6L & _WRT1_OFF_6L & _WRT2_OFF_6L & _WRT3_OFF_6L;
code char at __CONFIG6H _conf8	= _WRTB_OFF_6H & _WRTC_OFF_6H & _WRTD_OFF_6H;
code char at __CONFIG7L _conf9	= _EBTR0_OFF_7L & _EBTR1_OFF_7L & _EBTR2_OFF_7L & _EBTR3_OFF_7L;
code char at __CONFIG7H _conf10	= _EBTRB_OFF_7H;

/*******************************************************************************
 *	Misc functions
 *******************************************************************************
 */

// Millisecond delay based on 4MHz Clock
void delayMs(unsigned int n){
	unsigned char	c;

	while(n--){
		for(c = 0; c < 250; c++){
			_asm nop _endasm;
		}
	}
}

void main(void) {
	uchar	v;
	
	// Set up Oscillator
	OSCCON = 0x62;				// Internal 4MHZ

	TRISB = 0x0F;           		// PORTB top 4 bits Output
	PORTB = 0;

	// Do this forever
	while(1){
		// Increments the top 4 bits from 0 - 15 to flash the LEDS in a count
		for(v = 0; v < 16; v++){
			PORTB = v << 4;
			delayMs(100);
		}
	}
}
