int main (void)
{

    FSFILE * pointer;
    char path[30];
    char count = 30;
    char * pointer2;
    int gh;
    BYTE write_array[512];
    for(gh=0; gh<512; gh++)
        if(gh%8)
            write_array[gh]='a';
        else
            write_array[gh]='b';
    DWORD first_sector;
    BYTE test_array[512];
    /* OFB_init();
     OFB_push(write_array);
     calc_checksum(write_array);
     while(1);*/
    SearchRec rec;
    pointer=NULL;
    unsigned char attributes;
    unsigned char size = 0, i;
    PLLFBD =38;
    CLKDIVbits.PLLPOST=0;
    CLKDIVbits.PLLPRE=0;
    __builtin_write_OSCCONH(0b011);
    __builtin_write_OSCCONL(0b01);
    while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur
    while(OSCCONbits.LOCK != 1) {};
    UART2Init();
    //printf("stuipd thing");
    //TRISD=0x0FF;
    //setting up pins to show on usb debugger
    TRISDbits.TRISD6=1;
    TRISAbits.TRISA7=0;
    TRISAbits.TRISA6=0;
    TRISAbits.TRISA5=0;
    TRISAbits.TRISA4=0;
    //LATA=1;
    //_LATA4=1;
    //_RA7=1;
    //_LATA6=1;

    //_LATA5=1;
    //_LATA7=1;

    //printf("they should be on now");
    //while(1);
    //LATAbits.LATA7=0;
    //TRISB=0xFFFF;
    //AD1PCFGLbits.PCFG1=1;

#ifdef TESTOVERFLOWBUFFER
#ifdef __DEBUG
    printf("Starting test of overflow buffer");

    unsigned char ofbtestin[SECTORSIZE];
    unsigned char ofbtestout[SECTORSIZE];
    OFB_init();
    int ofbi,ofbj,ofbk,result;
    char num=0;
    printf("Starting insertion test\r\n");
    for(ofbj=0; ofbj<=OVERFLOWBUFFERDEPTH; ofbj++)
    {
        for(ofbi=0; ofbi<SECTORSIZE; ofbi++)
            ofbtestin[ofbi]=num+48;
        printf("Size of Buffer: %d\r\n",OFB_getSize());
        printf("Result of Insertion: %d\r\n",OFB_push(ofbtestin));
        printf("New Size: %d\r\n",OFB_getSize());
        num++;
    }
    printf("Starting retrieval test\r\n");
    for(ofbj=0; ofbj<=OVERFLOWBUFFERDEPTH; ofbj++)
    {
        printf("Size of Buffer: %d\r\n",OFB_getSize());
        result=OFB_read_tail(ofbtestout);
        printf("result of read: %d\r\n",result);
        printf("343rd entry in array: %c\r\n",ofbtestout[342]);
        /*for(i=0;i<SECTORSIZE;i++)
        {
        	printf("%d",ofbtestout[i]);
        	while(UART2IsEmpty());
        }*/
        //printf("\r\n");
        result=OFB_pop();
        printf("Result of Pop: %d\r\n",result);
    }
    while(1);
#endif
#endif

    //Service_Spi();
#ifdef __DEBUG
    printf("Clock Switch Complete, Waiting For Media\r\n");
#endif
    //waits for a card to be inserted
    while (!MDD_MediaDetect());


#ifdef __DEBUG
    printf("Media Found, Waiting for FSinit\r\n");
#endif
    // Initialize the library
    while (!FSInit());
    char temp;
    int character_count,remove_success;
    character_count=0;
    // Create a file
    printf("starting up\r\n");
    remove_success=FSremove("WRITE.TXT");
    printf("Removal of prev: %d\r\n",remove_success);
    pointer = FSfopen ("WRITE.TXT", "w");

    if (pointer == NULL)
    {
#ifdef __DEBUG
        printf("File open failed\r\n");
#endif
        while(1);
    }
    //FSfseek(pointer,0,SEEK_SET);
    //set_First_Sector(first_sector);
    //FSfwrite("greetings",1,9,pointer);
    printf("waiting for operation\r\n");
    //FSfwrite("greetings",1,9,pointer);
    //allocate_size(38769,pointer);
    DWORD sizeinbytes;
    //need to convert from number of sectors to number of bytes and allocate that much space
    sizeinbytes=(DWORD)FILESIZE*(DWORD)512;
    //sizeinbytes=3774873*(DWORD)512;
    allocate_size(sizeinbytes,pointer,FALSE);
    FSfseek(pointer,0,SEEK_SET);
    first_sector=get_First_Sector(pointer);
    set_First_Sector(first_sector);
    DWORD erasure;
    OFB_init();
    for(erasure=0; erasure<FILESIZE; erasure++)
    {
        MDD_SDSPI_SectorWrite(first_sector, write_array,FALSE);
        first_sector++;
        if(erasure%100==0)
            printf("%lu\r",erasure);
    }
    int bleh;

    FSfclose(pointer);
    //MDD_ShutdownMedia();
    printf("done with file allocation\r\n");
#ifdef DMAON
#else
#endif

    //while(UART2IsEmpty());
    //temp=UART2GetChar();
    //write_array[character_count]=temp;
    //character_count++;
    while(1)
    {
        Service_Spi();
    }
    /*while(temp!='+')
    {
    	if(character_count<512)
    	{
    		if(!UART2IsEmpty())
    		{
    			temp=UART2GetChar();
    			write_array[character_count]=temp;
    			character_count++;
    			//printf("%08d\r",character_count);
    		}
    	}
    	else
    	{
    	FSfwrite(write_array,1,character_count, pointer);
    	character_count=0;
    	}
    }*/
    //FSfwrite(write_array,1,character_count, pointer);
    //FSfwrite(sendBuffer,1,21, pointer);
    unsigned int buffer[512];
    char buffersign;
    //bufferreturn(buffer);
    while(1)
    {
        /*buffersign=bufferreturn(buffer);
        if(buffersign==1)
        {
         //FSfwrite(buffer,1,512,pointer);
        }*/
        if(!PORTDbits.RD6)
        {
            DMA0CONbits.CHEN=0;
            //FSfclose(pointer);
            DMA0CONbits.CHEN=0;
            printf("done with operations\r\n");
            MDD_ShutdownMedia();
            while(1) {}
        }
    }
    while(1);
}
int main(void)
{
	long address = 0;
	int record = 0;
	int selector_efecto = 0;
    ///tremolo2
	double trem_triangular = -0.5;
	int trem_subida = 1;
	///tremolo2
	///wahwah
	double wah_triangular = 500;
	int wah_subida = 1;
    double last_wah_wah_yb, last_wah_wah_yh, last_wah_wah_yl;
    int first_time_wah_wah_function = 1;
	///wahwah
    ///phaser
	double phaser_triangular = 500;
    int phaser_subida = 1;
    int first_time_phaser_function = 1;
    double last_phaser_yb, last_phaser_yh, last_phaser_yl;
    //Phaser
	/* Configure Oscillator to operate the device at 40MHz.
	 * Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
	 * Fosc= 700Mhz for 7.37M input clock */

	PLLFBD=41;				/* M=39	*/
	CLKDIVbits.PLLPOST=0;		/* N1=2	*/
	CLKDIVbits.PLLPRE=0;		/* N2=2	*/
	OSCTUN=0;

	__builtin_write_OSCCONH(0x01);		/*	Initiate Clock Switch to FRC with PLL*/
	__builtin_write_OSCCONL(0x01);
	while (OSCCONbits.COSC != 0b01);	/*	Wait for Clock switch to occur	*/
	while(!OSCCONbits.LOCK);

	/* Intialize the board and the drivers	*/
	SASKInit();
	WM8510Init(codecHandle,codecBuffer);

	/* Start Audio input and output function	*/
	WM8510Start(codecHandle);

	/* Configure codec for 8K operation	*/
	WM8510SampleRate8KConfig(codecHandle);

	/* Main processing loop. Executed for every input and
	 * output frame	*/

	while(1) {
        /*Obtain Audio Samples	*/
        while(WM8510IsReadBusy(codecHandle));
        WM8510Read(codecHandle,samples,FRAME_SIZE);

        G711Lin2Ulaw(samples,encodedSamples,FRAME_SIZE);

        /* Decode the samples	*/
        G711Ulaw2Lin (encodedSamples,decodedSamples, FRAME_SIZE);

        /* Wait till the codec is available for a new  frame	*/
        while(WM8510IsWriteBusy(codecHandle));

        switch(selector_efecto) {
            case 0:
                // prenden los leds
                RED_LED=SASK_LED_OFF;
                YELLOW_LED=SASK_LED_OFF;
                GREEN_LED=SASK_LED_OFF;
                // se activa el clean
                break;

            case 1:
                // prenden los leds
                RED_LED=SASK_LED_OFF;
                YELLOW_LED=SASK_LED_OFF;
                GREEN_LED=SASK_LED_ON;
                // Se activa el efecto de tremolo
                tremolo_effect(decodedSamples);
                break;

            case 2:
                // prenden los leds
                RED_LED=SASK_LED_OFF;
                YELLOW_LED=SASK_LED_ON;
                GREEN_LED=SASK_LED_OFF;
                // Se activa el efecto de tremolo2
                 trem_triangular = tremolo_effect2(trem_triangular, &trem_subida, decodedSamples);
                break;
            case 3:
                // prenden los leds
                RED_LED=SASK_LED_OFF;
                YELLOW_LED=SASK_LED_ON;
                GREEN_LED=SASK_LED_ON;
                // Se activa el efecto de fuzz
                fuzz_effect(decodedSamples);
                break;
            case 4:
                // prenden los leds
                RED_LED=SASK_LED_ON;
                YELLOW_LED=SASK_LED_OFF;
                GREEN_LED=SASK_LED_OFF;
                // Se activa el efecto de wah wah
                wah_triangular = wah_wah_effect(wah_triangular, &wah_subida, decodedSamples, &last_wah_wah_yb, &last_wah_wah_yh, &last_wah_wah_yl, &first_time_wah_wah_function);
                break;
            case 5:
                // prenden los leds
                RED_LED=SASK_LED_ON;
                YELLOW_LED=SASK_LED_OFF;
                GREEN_LED=SASK_LED_ON;
		        phaser_triangular = phaser_effect(phaser_triangular, &phaser_subida, decodedSamples, &last_phaser_yb, &last_phaser_yh, &last_phaser_yl, &first_time_phaser_function);
                                
// Se activa el efecto de wah wah
                break;
            case 6:
                // prenden los leds
                RED_LED=SASK_LED_ON;
                YELLOW_LED=SASK_LED_ON;
                GREEN_LED=SASK_LED_OFF;
                // Se activa el efecto de wah wah
                break;
            case 7:
                // prenden los leds
                RED_LED=SASK_LED_ON;
                YELLOW_LED=SASK_LED_ON;
                GREEN_LED=SASK_LED_ON;
                // Se activa el efecto de wah wah
                break;
            default:
                break;

        }
        /* Write the frame to the output	*/
        WM8510Write (codecHandle,decodedSamples,FRAME_SIZE);

        if(CheckSwitchS1()){
            selector_efecto--;
        }

        if(CheckSwitchS2()){
            selector_efecto++;
        }
        // rango de 0-7 para selector de efectos
        if (selector_efecto < 0 ) {
            selector_efecto = 7;
        }
        if (selector_efecto > 7  ) {
            selector_efecto = 0;
        }
	}
}
Exemple #3
0
/*****************************************
 * void InitializeHardware(void)	
 *****************************************/
void InitializeHardware(void)	
{
	#if defined(__dsPIC33F__) || defined(__PIC24H__)

    // 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 switching 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)
    { };
    
    #elif defined(__PIC32MX__)
    SYSTEMConfig(GetSystemClock(), SYS_CFG_ALL);
    #ifdef MEB_BOARD
    CPLDInitialize();
    CPLDSetGraphicsConfiguration(GRAPHICS_HW_CONFIG);
    CPLDSetSPIFlashConfiguration(SPI_FLASH_CHANNEL);
    #endif
    #endif

    #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)
    AD1PCFGL = 0xffff;
    #endif
    
    #if defined (__PIC24FJ256GB210__)        
    // Map UART2
    __builtin_write_OSCCONL(OSCCON & 0xbf);    
	// Configure Input Functions (Table 10-2))
	// Assign U2RX To Pin RP10
	RPINR19bits.U2RXR = 10;	

	// Assign U2CTS To Pin RP32
	RPINR19bits.U2CTSR = 32;

	// Configure Output Functions (Table 10-4)
	// Assign U2TX To Pin RP17
	RPOR8bits.RP17R = 5;
	
	// Assign U2RTS To Pin RP31
	RPOR15bits.RP31R = 6;
    __builtin_write_OSCCONL (OSCCON | 0x40);
    #endif


	#if ( USE_SPI_CHANNEL == 1 )
		#if defined (__PIC24FJ256GB210__)
			__builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS
			// Configure SPI1 PPS pins (ENC28J60/ENCX24J600/MRF24WB0M or other PICtail Plus cards)
			RPOR0bits.RP0R = 8;		// Assign RP0 to SCK1 (output)
			RPOR7bits.RP15R = 7;	// Assign RP15 to SDO1 (output)
			//RPOR6bits.RP13R = 9;	// Assign RP15 to SDO1 (output)
			RPINR20bits.SDI1R = 23;	// Assign RP23 to SDI1 (input)
			__builtin_write_OSCCONL(OSCCON | 0x40); // lock   PP
		#endif
	#endif 
	
    /////////////////////////////////////////////////////////////////////////////
    // ADC Explorer 16 Development Board Errata (work around 2)
    // RB15 should be output
    /////////////////////////////////////////////////////////////////////////////
    #ifndef MEB_BOARD
        LATBbits.LATB15 = 0;
        TRISBbits.TRISB15 = 0;
    #endif


    #if defined (EXPLORER_16)
/************************************************************************
* For Explorer 16 RD12 is connected to EEPROM chip select.
* To prevent a conflict between this EEPROM and SST25 flash
* the chip select of the EEPROM SPI should be pulled up.
************************************************************************/
        // Set IOs directions for EEPROM SPI
        MCHP25LC256_CS_LAT = 1;			    // set initial CS value to 1 (not asserted)
    	MCHP25LC256_CS_TRIS = 0;			// set CS pin to output
	#endif // #if defined (EXPLORER_16)


    //The following are PIC device specific settings for the SPI channel
    //used. 
    
    //Set IOs directions for SST25 SPI
	#if defined (USE_SST25VF064)	    
        SST25_CS_LAT = 1;
        SST25_CS_TRIS = 0;
  
        #ifndef __PIC32MX__
            SST25_SCK_TRIS = 0;
            SST25_SDO_TRIS = 0;
            SST25_SDI_TRIS = 1;
            #if defined(__PIC24FJ256GB210__) || defined(__dsPIC33E__) || defined(__PIC24E__)
            	SST25_SDI_ANS = 0;
    	    #endif
        #endif
	#endif

    // set the peripheral pin select for the SPI channel used
    #if defined(__PIC24FJ256GB110__) || defined(__PIC24FJ256GA110__) || defined (__PIC24FJ256GB210__)
        __builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS
        RPOR10bits.RP21R = 11;                  // assign RP21 for SCK2
        RPOR9bits.RP19R = 10;                   // assign RP19 for SDO2
        RPINR22bits.SDI2R = 26;                 // assign RP26 for SDI2
        __builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS
    #endif

	#if defined (USE_SST25VF064)
    	SST25Init((DRV_SPI_INIT_DATA *)&SPI_Init_Data);
    #endif
}
Exemple #4
0
/****************************************************************************
  Function:
    int main(void)

  Summary:
    main function

  Description:
    main function

  Precondition:
    None

  Parameters:
    None

  Return Values:
    int - exit code for main function

  Remarks:
    None
  ***************************************************************************/
int main(void)
{
    DWORD size = 0;
    BOOL responseNeeded;

    BYTE mode = 0;

    BYTE wasMode = 0;
    BYTE pushButtonValues = 0xFF;
    BYTE potPercentage = 0xFF;
    BOOL buttonsNeedUpdate = FALSE;
    BOOL potNeedsUpdate = FALSE;
    BOOL motorON = FALSE;
    BOOL readyToRead = TRUE;
    BOOL writeInProgress = FALSE;
    BYTE tempValue = 0xFF;
    BYTE errorCode;
    ACCESSORY_APP_PACKET* command_packet = NULL;

    CLKDIV =  0; /* set for default clock operations Fcyc = 4MHz */
    AD1PCFGL = 0xffff;
    AD1PCFGH = 0x0003;

    BOOL connected_to_app = FALSE;
    BOOL need_to_disconnect_from_app = FALSE;

    #if defined(__PIC32MX__)
        InitPIC32();
    #endif

  #if defined(__dsPIC33EP512MU810__) || defined (__PIC24EP512GU810__)

    // Configure the device PLL to obtain 60 MIPS operation. The crystal
    // frequency is 8MHz. Divide 8MHz by 2, multiply by 60 and divide by
    // 2. This results in Fosc of 120MHz. The CPU clock frequency is
    // Fcy = Fosc/2 = 60MHz. Wait for the Primary PLL to lock and then
    // configure the auxilliary PLL to provide 48MHz needed for USB
    // Operation.

	PLLFBD = 38;				/* M  = 60	*/
	CLKDIVbits.PLLPOST = 0;		/* N1 = 2	*/
	CLKDIVbits.PLLPRE = 0;		/* N2 = 2	*/
	OSCTUN = 0;

    /*	Initiate Clock Switch to Primary
     *	Oscillator with PLL (NOSC= 0x3)*/

    __builtin_write_OSCCONH(0x03);
	__builtin_write_OSCCONL(0x01);
	while (OSCCONbits.COSC != 0x3);

    // Configuring the auxiliary PLL, since the primary
    // oscillator provides the source clock to the auxiliary
    // PLL, the auxiliary oscillator is disabled. Note that
    // the AUX PLL is enabled. The input 8MHz clock is divided
    // by 2, multiplied by 24 and then divided by 2. Wait till
    // the AUX PLL locks.

    ACLKCON3 = 0x24C1;
    ACLKDIV3 = 0x7;
    ACLKCON3bits.ENAPLL = 1;
    while(ACLKCON3bits.APLLCK != 1);

    TRISBbits.TRISB5 = 0;
    LATBbits.LATB5 = 1;

    #endif

    USBInitialize(0);
    AndroidAppStart(&myDeviceInfo);

    responseNeeded = FALSE;
    mInitPOT();
    InitializeTimer2For_PWM();
    PwmInit();

    //InitMOTOR();

    DEBUG_Init(0);

    InitAllLEDs();

    while(1)
    {
        //Keep the USB stack running
        USBTasks();



        //If the device isn't attached yet,
        if(device_attached == FALSE || mode == 1)
        {
            buttonsNeedUpdate = TRUE;
            potNeedsUpdate = TRUE;
            need_to_disconnect_from_app = FALSE;
            connected_to_app = FALSE;
            size = 0;

            /**/
            BYTE curPush = GetPushbuttons();

            if ((curPush == 0x8) || (mode == 1)) {
                LED0_On();

                mode = 1;
                if (wasMode == 0) {

                    pot2LEDs();
                    PwmInit();


                }

                tempValue = ReadPOT();


                wasMode = 1;

                //If it is different than the last time we read the pot, then we need
                //  to send it to the Android device

                if(tempValue != potPercentage) {
                    potNeedsUpdate = TRUE;
                    //setRPM(tempValue);

                    setPWM();
                }
            }
            if ((curPush == 0x4)  || (mode == 0)) {
                    mode = 0;
                    //LED0_Off();

                    if (wasMode == 1) {
                        SetLEDs(0b00000000);
                        wasMode = 0;
                        setRPM(0);
                    }
                    //Reset the accessory state variables
                    InitAllLEDs();

                    //Continue to the top of the while loop to start the check over again.
                    continue;
                }
               /* //Reset the accessory state variables
                InitAllLEDs();

                //Continue to the top of the while loop to start the check over again.
                continue;
            }*/
            //}






        }

        //If the accessory is ready, then this is where we run all of the demo code

        if(readyToRead == TRUE && mode == 0)
        {
            errorCode = AndroidAppRead(device_handle, (BYTE*)&read_buffer, (DWORD)sizeof(read_buffer));
            //If the device is attached, then lets wait for a command from the application
            if( errorCode != USB_SUCCESS)
            {
                //Error
                DEBUG_PrintString("Error trying to start read");
            }
            else
            {
                readyToRead = FALSE;
            }
        }

        size = 0;

        if(AndroidAppIsReadComplete(device_handle, &errorCode, &size) == TRUE)
        {
            //We've received a command over the USB from the Android device.
            if(errorCode == USB_SUCCESS)
            {
                //Maybe process the data here.  Maybe process it somewhere else.
                command_packet = (ACCESSORY_APP_PACKET*)&read_buffer[0];
            }
            else
            {
                //Error
                DEBUG_PrintString("Error trying to complete read request");
            }

        }

        while(size > 0)
        {
            if(connected_to_app == FALSE)
            {
                if(command_packet->command == COMMAND_APP_CONNECT)
                {
                    connected_to_app = TRUE;
                    need_to_disconnect_from_app = FALSE;
                }
            }
            else
            {
                switch(command_packet->command)
                {
                    case COMMAND_SET_LEDS:
                        SetLEDs(command_packet->data);
                        break;

                    case COMMAND_APP_DISCONNECT:
                        need_to_disconnect_from_app = TRUE;
                        break;

                    case COMMAND_SET_PWM:
                        setRPM(command_packet->data);
                        break;

                    default:
                        //Error, unknown command
                        DEBUG_PrintString("Error: unknown command received");
                        break;
                }
            }
            //All commands in this example are two bytes, so remove that from the queue
            size -= 2;
            //And move the pointer to the next packet (this works because
            //  all command packets are 2 bytes.  If variable packet size
            //  then need to handle moving the pointer by the size of the
            //  command type that arrived.
            command_packet++;

            if(need_to_disconnect_from_app == TRUE)
            {
                break;
            }
        }

        if(size == 0)
        {
            readyToRead = TRUE;
        }

        //Get the current pushbutton settings
        tempValue = GetPushbuttons();

        //If the current button settings are different than the last time
        //  we read the button values, then we need to send an update to the
        //  attached Android device
        if(tempValue != pushButtonValues)
        {
            buttonsNeedUpdate = TRUE;
            pushButtonValues = tempValue;
        }

        //Get the current potentiometer setting
        tempValue = ReadPOT();

        //If it is different than the last time we read the pot, then we need
        //  to send it to the Android device
        if(tempValue != potPercentage)
        {
            potNeedsUpdate = TRUE;
            potPercentage = tempValue;
        }

        //If there is a write already in progress, we need to check its status
        if( writeInProgress == TRUE )
        {
            if(AndroidAppIsWriteComplete(device_handle, &errorCode, &size) == TRUE)
            {
                writeInProgress = FALSE;
                if(need_to_disconnect_from_app == TRUE)
                {
                    connected_to_app = FALSE;
                    need_to_disconnect_from_app = FALSE;
                }

                if(errorCode != USB_SUCCESS)
                {
                    //Error
                    DEBUG_PrintString("Error trying to complete write");
                }
            }
        }

        if((need_to_disconnect_from_app == TRUE) && (writeInProgress == FALSE))
        {
            outgoing_packet.command = COMMAND_APP_DISCONNECT;
            outgoing_packet.data = 0;
            writeInProgress = TRUE;

            errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2);
            if( errorCode != USB_SUCCESS )
            {
                DEBUG_PrintString("Error trying to send button update");
            }
        }

        if(connected_to_app == FALSE)
        {
            //If the app hasn't told us to start sending data, let's not do anything else.
            continue;
        }

        //If we need up update the button status on the Android device and we aren't
        //  already busy in a write, then we can send the new button data.
        if((buttonsNeedUpdate == TRUE) && (writeInProgress == FALSE))
        {
            outgoing_packet.command = COMMAND_UPDATE_PUSHBUTTONS;
            outgoing_packet.data = pushButtonValues;



            errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2);
            if( errorCode != USB_SUCCESS )
            {
                DEBUG_PrintString("Error trying to send button update");
            }

            buttonsNeedUpdate = FALSE;
            writeInProgress = TRUE;
        }

        //If we need up update the pot status on the Android device and we aren't
        //  already busy in a write, then we can send the new pot data.
        if((potNeedsUpdate == TRUE) && (writeInProgress == FALSE))
        {
            outgoing_packet.command = COMMAND_UPDATE_POT;
            outgoing_packet.data = potPercentage;

            errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2);
            if( errorCode != USB_SUCCESS )
            {
                DEBUG_PrintString("Error trying to send pot update");
            }

            potNeedsUpdate = FALSE;
            writeInProgress = TRUE;
        }
    } //while(1) main loop
}
Exemple #5
0
int main(int argc, char** argv) {

    /*Configuring POSC with PLL, with goal FOSC = 80 MHZ */
    // Configure PLL prescaler, PLL postscaler, PLL divisor
    // Fin = 8 Mhz, 8  * (40/2/2) = 80
    PLLFBD = 18; // M=40          // change to 38 for POSC 80 Mhz - this worked only on a single MCU for uknown reason
    CLKDIVbits.PLLPOST = 0; // N2=2
    CLKDIVbits.PLLPRE = 0; // N1=2

    // Initiate Clock Switch to Primary Oscillator with PLL (NOSC=0b011)
    //__builtin_write_OSCCONH(0x03);

    // tune FRC
    OSCTUN = 23;  // 23 * 0.375 = 8.625 % -> 7.37 Mhz * 1.08625 = 8.005Mhz
    // Initiate Clock Switch to external oscillator NOSC=0b011 (alternative use FRC with PLL (NOSC=0b01)
    __builtin_write_OSCCONH(0b011);
    __builtin_write_OSCCONL(OSCCON | 0x01);

    // Wait for Clock switch to occur
    while (OSCCONbits.COSC!= 0b011);
    // Wait for PLL to lock
    while (OSCCONbits.LOCK!= 1);

     // local variables in main function
    int status = 0;
    int i = 0;
    int ax = 0, ay = 0, az = 0;
    int statusProxi[8];
    int slowLoopControl = 0;
    UINT16 timerVal = 0;
    float timeElapsed = 0.0;
    //extern UINT8 pwmMotor;
    extern UINT16 speakerAmp_ref;
    extern UINT16 speakerFreq_ref;
    extern UINT8 proxyStandby;
    UINT16 dummy = 0x0000;

    setUpPorts();
    delay_t1(50);

    PWMInit();
    delay_t1(50);

    ctlPeltier = 0;
    PeltierVoltageSet(ctlPeltier);
    FanCooler(0);
    diagLED_r[0] = 100;
    diagLED_r[1] = 0;
    diagLED_r[2] = 0;
    LedUser(diagLED_r[0], diagLED_r[1],diagLED_r[2]);

    // Speaker initialization - set to 0,1
    spi1Init(2, 0);
    speakerAmp_ref = 0;
    speakerAmp_ref_old = 10;
    speakerFreq_ref = 1;
    speakerFreq_ref_old = 10;
    int count = 0;
    UINT16 inBuff[2] = {0};
    UINT16 outBuff[2] = {0};

    while (speakerAmp_ref != speakerAmp_ref_old) {
        if (count > 5 ) {
            // Error !
            //LedUser(100, 0, 0);
            break;
        }

        inBuff[0] = (speakerAmp_ref & 0x0FFF) | 0x1000;

        chipSelect(slaveVib);
        status = spi1TransferWord(inBuff[0], outBuff);
        chipDeselect(slaveVib);

        chipSelect(slaveVib);
        status = spi1TransferWord(inBuff[0], &speakerAmp_ref_old);
        chipDeselect(slaveVib);

        count++;
    }

    count = 0;

    while (speakerFreq_ref != speakerFreq_ref_old) {
        if (count > 5 ) {
            // Error !
            //LedUser(0, 100, 0);
            break;
        }

        inBuff[0] = (speakerFreq_ref & 0x0FFF) | 0x2000;

        chipSelect(slaveVib);
        status = spi1TransferWord(inBuff[0], outBuff);
        chipDeselect(slaveVib);

        chipSelect(slaveVib);
        status = spi1TransferWord(inBuff[0], &speakerFreq_ref_old);
        chipDeselect(slaveVib);

        count++;
    }

    accPin = aSlaveR;
    accPeriod = 1.0 / ACC_RATE * 1000000.0;  // in us; for ACC_RATE = 3200 Hz it should equal 312.5 us
    status = adxl345Init(accPin);
    ax = status;
    delay_t1(5);

    /* Init FFT coefficients */
    TwidFactorInit(LOG2_FFT_BUFF, &Twiddles_array[0],0);
    delta_freq = (float)ACC_RATE / FFT_BUFF;

    // read 100 values to calculate bias
    int m;
    int n = 0;
    for (m = 0; m < 100; m++) {

        status = readAccXYZ(accPin, &ax, &ay, &az);
        if (status <= 0) {
            //
        }
        else {
            ax_b_l += ax;
            ay_b_l += ay;
            az_b_l += az;
            n++;
        }
        delay_t1(1);
    }

    ax_b_l /= n;
    ay_b_l /= n;
    az_b_l /= n;

    _SI2C2IE = 0;
    _SI2C2IF = 0;

    // Proximity sensors initalization
    I2C1MasterInit();
    status = VCNL4000Init();

    // Cooler temperature sensors initalization
    status = adt7420Init(0, ADT74_I2C_ADD_mainBoard);
    delay_t1(1);
    muxCh = I2C1ChSelect(1, 6);
    status = adt7420Init(0, ADT74_I2C_ADD_flexPCB);

    // Temperature sensors initialization
    statusTemp[0] = adt7320Init(tSlaveF, ADT_CONT_MODE | ADT_16_BIT);
    delay_t1(5);
    statusTemp[1] = adt7320Init(tSlaveR, ADT_CONT_MODE | ADT_16_BIT);
    delay_t1(5);
    statusTemp[2] = adt7320Init(tSlaveB, ADT_CONT_MODE | ADT_16_BIT);
    delay_t1(5);
    statusTemp[3] = adt7320Init(tSlaveL, ADT_CONT_MODE | ADT_16_BIT);
    delay_t1(5);

    // Temperature estimation initialization
    for (i = 0; i < 50; i++) {
        adt7320ReadTemp(tSlaveF, &temp_f);
        delay_t1(1);
        adt7320ReadTemp(tSlaveL, &temp_l);
        delay_t1(1);
        adt7320ReadTemp(tSlaveB, &temp_b);
        delay_t1(1);
        adt7320ReadTemp(tSlaveR, &temp_r);
        delay_t1(1);
    }

    tempBridge[0] = temp_f;
    tempBridge[1] = temp_r;
    tempBridge[2] = temp_b;
    tempBridge[3] = temp_l;

    if (statusTemp[0] != 1)
        temp_f = -1;
    if (statusTemp[1] != 1)
        temp_r = -1;
    if (statusTemp[2] != 1)
        temp_b = -1;
    if (statusTemp[3] != 1)
        temp_l = -1;

    // CASU ring average temperature
    temp_casu = 0;
    tempNum = 0;
    tempSensors = 0;

    for (i = 0; i < 4; i++) {
        if (statusTemp[i] == 1 && tempBridge[i] > 20 && tempBridge[i] < 60) {
            tempNum++;
            temp_casu += tempBridge[i];
            tempSensors++;
        }
    }

    if (tempNum > 0)
        temp_casu /= tempNum;
    else
        temp_casu = -1;

    temp_casu1 = temp_casu;
    temp_wax = temp_casu;
    temp_wax1 = temp_casu;
    temp_model = temp_wax;

    temp_old[0] = temp_f;
    temp_old[1] = temp_r;
    temp_old[2] = temp_b;
    temp_old[3] = temp_l;
    temp_old[4] = temp_flexPCB;
    temp_old[5] = temp_pcb;
    temp_old[6] = temp_casu;
    temp_old[7] = temp_wax;

    for (i = 0; i < 4; i++) {
        uref_m[i] = temp_wax;
    }

    // Configure i2c2 as a slave device and interrupt priority 5
    I2C2SlaveInit(I2C2_CASU_ADD, BB_I2C_INT_PRIORITY);

    // delay for 2 sec
    for(i = 0; i < 4; i ++) {
        delay_t1(500);
        ClrWdt();
    }

    while (i2cStarted == 0) {
        delay_t1(200);
        ClrWdt();
    }

    dma0Init();
    dma1Init();

    CloseTimer4();
    ConfigIntTimer4(T4_INT_ON | TEMP_LOOP_PRIORITY);
    OpenTimer4(T4_ON | T4_PS_1_256, ticks_from_ms(2000, 256));

    CloseTimer5();
    ConfigIntTimer5(T5_INT_ON | FFT_LOOP_PRIORITY);
    OpenTimer5(T5_ON | T5_PS_1_256, ticks_from_ms(1000, 256));

    diagLED_r[0] = 0;
    diagLED_r[1] = 0;
    diagLED_r[2] = 0;
    LedUser(diagLED_r[0], diagLED_r[1],diagLED_r[2]);

    start_acc_acquisition();

    while(1) {

        ConfigIntTimer2(T2_INT_OFF);    // Disable timer interrupt
        IFS0bits.T2IF = 0;              // Clear interrupt flag
        OpenTimer2(T2_ON | T2_PS_1_256, 65535); // Configure timer

        if (!proxyStandby) {
            statusProxi[0] = I2C1ChSelect(1, 2);            // Front
            proxy_f = VCNL4000ReadProxi();
            delay_t1(1);
            statusProxi[1] = I2C1ChSelect(1, 4);            // Back right
            proxy_br = VCNL4000ReadProxi();
            delay_t1(1);
            statusProxi[2] = I2C1ChSelect(1, 3);            // Front right
            proxy_fr = VCNL4000ReadProxi();
            delay_t1(1);
            statusProxi[3] = I2C1ChSelect(1, 5);            // Back
            proxy_b = VCNL4000ReadProxi();
            delay_t1(1);
            statusProxi[4] = I2C1ChSelect(1, 0);            // Back left
            proxy_bl = VCNL4000ReadProxi();
            delay_t1(1);
            statusProxi[5] = I2C1ChSelect(1, 1);            // Front left
            proxy_fl = VCNL4000ReadProxi();
            delay_t1(1);
        }
        else {
            proxy_f = 0;            // Front
            proxy_br = 0;            // Back right
            proxy_fr = 0;            // Front right
            proxy_b = 0;            // Back
            proxy_bl = 0;            // Back left
            proxy_fl = 0;            // Front left
        }

        if (timer4_flag == 1) {
            // every 2 seconds
            CloseTimer4();
            ConfigIntTimer4(T4_INT_ON | TEMP_LOOP_PRIORITY);
            timer4_flag = 0;

            if (dma_spi2_started == 0) {
                OpenTimer4(T4_ON | T4_PS_1_256, ticks_from_ms(2000, 256));
                skip_temp_filter++;
                tempLoop();
            }
            else {
                OpenTimer4(T4_ON | T4_PS_1_256, ticks_from_ms(50, 256));
            }
        }

        if (dma_spi2_done == 1) {
            fftLoop();
            dma_spi2_done = 0;
        }
        if ((timer5_flag == 1) || (new_vibration_reference == 1)) {
            // every 1 seconds
            CloseTimer5();
            ConfigIntTimer5(T5_INT_ON | FFT_LOOP_PRIORITY);
            OpenTimer5(T5_ON | T5_PS_1_256, ticks_from_ms(1000, 256));

            timer5_flag = 0;
            if (new_vibration_reference == 1) {
            //if(1){
                CloseTimer3();
                dma0Stop();
                dma1Stop();
                spi2Init(2, 0);
                dma0Init();
                dma1Init();
                chipDeselect(aSlaveR);
                IFS0bits.DMA0IF = 0;
                delay_t1(30); // transient response
            }
            new_vibration_reference = 0;

            start_acc_acquisition();
        }

        // Cooler fan control
        if (fanCtlOn == 1) {
            if (temp_pcb >= 25 && fanCooler == FAN_COOLER_OFF)
                fanCooler = FAN_COOLER_ON;
            else if (temp_pcb <= 24 && fanCooler == FAN_COOLER_ON)
                fanCooler = FAN_COOLER_OFF;
            // In case of I2C1 fail turn on the fan
            if ((proxy_f == 0xFFFF) && (proxy_fr == 0xFFFF) && (proxy_br == 0xFFFF) && (proxy_b == 0xFFFF) && (proxy_bl == 0xFFFF) && (proxy_fl == 0xFFFF))
                fanCooler = FAN_COOLER_ON;
        }
        else if (fanCtlOn == 2)
            fanCooler = FAN_COOLER_ON;
        else
            fanCooler = FAN_COOLER_OFF;

        //TEST
//        temp_f = temp_model;
//        if (temp_ref < 30) {
//            temp_r = smc_parameters[0] * 10;
//        }
//        else {
//            temp_r = smc_parameters[0] / 2.0 * 10.0;
//        }
//        temp_r = alpha*10;
//        temp_b = sigma_m * 10;
//        temp_l = sigma * 10;
        //temp_flexPCB = temp_ref_ramp;
/*
        proxy_f = dma_spi2_started;
        proxy_fl = dma_spi2_done;
        proxy_bl = new_vibration_reference;
        proxy_b = timer5_flag;
        proxy_br = timer4_flag;
*/
        int dummy_filt = 0;
        for (i = 0; i < 8; i++) {
            if (index_filter[i] > 0){
                dummy_filt++;
            }
        }

        if (dummy_filt > 0) {
            filtered_glitch = dummy_filt;
            //for (i = 0; i< 8; index_filter[i++] = 0);
        }
        else {
            filtered_glitch = 0;
        }

        updateMeasurements();

        timerVal = ReadTimer2();
        CloseTimer2();
        timeElapsed = ms_from_ticks(timerVal, 256);
        //if (timeElapsed < MAIN_LOOP_DUR)
        //    delay_t1(MAIN_LOOP_DUR - timeElapsed);

        ClrWdt(); //Clear watchdog timer

    } // end while(1)
    return (EXIT_SUCCESS);
}
Exemple #6
0
// *****************************************************************************
void SYSTEM_InitializeBoard(void)
{

    const DRV_SPI_INIT_DATA SPI_Init_Data = {2, 3, 7, 0, SPI_BUS_MODE_3, 0};

    // ---------------------------------------------------------
    // Make sure the display DO NOT flicker at start up
    // ---------------------------------------------------------
    DisplayBacklightConfig();
    DisplayPowerConfig();
    DisplayBacklightOff();
	
    // ---------------------------------------------------------
    // ADC Explorer 16 Development Board Errata (work around 2)
    // RB15 should be output
    // ---------------------------------------------------------
    LATBbits.LATB15 = 0;
    TRISBbits.TRISB15 = 0;

    // ---------------------------------------------------------
    // Explorer 16 Development Board MCHP25LC256 chip select signal,
    // even if not used must be driven to high so it does not
    // interfere with other SPI peripherals that uses the same SPI signals.
    // ---------------------------------------------------------
    TRISDbits.TRISD12 = 0;
    LATDbits.LATD12 = 1;
    
    // ---------------------------------------------------------
    // Graphics LCD Controller PICtail Plus SSD1926 Board
    // SPI-Flash Device pins 
    // ---------------------------------------------------------
    // chip select pin
    TRISDbits.TRISD1 = 0;
    LATDbits.LATD1   = 1;
    // spi-clock pin
    TRISGbits.TRISG6 = 0;
    // spi-output pin
    TRISGbits.TRISG8 = 0;
    // spi-intput pin
    TRISGbits.TRISG7 = 1;

    // ---------------------------------------------------------
    // UART pins
    // ---------------------------------------------------------
    // initialize the UART pins
    TRISFbits.TRISF5 = 0;
    TRISFbits.TRISF4 = 1;

    // unlock PPS
    __builtin_write_OSCCONL(OSCCON & 0xbf);

    // set UART pins
    RPINR19bits.U2RXR = 10; 	// assign RP10 to RX
    RPOR8bits.RP17R = 5;    	// assign RP17 to TX

    // set SPI pins
    RPOR10bits.RP21R = 11;      // assign RP21 for SCK2
    RPOR9bits.RP19R = 10;       // assign RP19 for SDO2
    RPINR22bits.SDI2R = 26;     // assign RP26 for SDI2

    // lock   PPS
    __builtin_write_OSCCONL(OSCCON | 0x40);

    // ---------------------------------------------------------
    // Initialize the Display Driver
    // ---------------------------------------------------------
    DRV_GFX_Initialize();

    DRV_NVM_SST25VF016_Initialize((DRV_SPI_INIT_DATA*)&SPI_Init_Data);

    // initialize system tick counter
    SYSTEM_TickInit();

    // initialize the components for Resistive Touch Screen
    TouchInit(NVMWrite, NVMRead, NVMSectorErase, NULL);

    
}
/**
 * Initializes the specified pin with the desired function. Remappable pins allows the user to set the pin not only like input or output, but also with advanced functionalities, like UART or SPI.
 * \param io Specifies the pin.
 * \param putval Specifies how the pin must be initialized. The valid parameters are the following:
 <UL>
	<LI><B>in (or IN)</B> input pin.</LI>
	<LI><B>inup (or INUP)</B> input pin with pullup resistor (about 5 KOhm).</LI>	
	<LI><B>indown (or INDOWN)</B> input pin with pulldown resistor (about 5 Kohm).</LI>
	<LI><B>out (or OUT)</B> output pin.</LI>
	<LI><B>UART1RX</B> UART1 RX input pin.</LI>
	<LI><B>UART1CTS</B> UART1 CTS input pin.</LI>
	<LI><B>UART2RX</B> UART2 RX input pin.</LI>
	<LI><B>UART2CTS</B> UART2 CTS input pin.</LI>
	<LI><B>UART3RX</B> UART3 RX input pin.</LI>
	<LI><B>UART3CTS</B> UART3 CTS input pin.</LI>
	<LI><B>UART4RX</B> UART4 RX input pin. <B><I>Note:</B>not available for Flyport GPRS</I></LI>
	<LI><B>UART4CTS</B> UART4 CTS input pin. <B><I>Note:</B>not available for Flyport GPRS</I></LI>
	<LI><B>EXT_INT2</B> External Interrupt 2 input pin.</LI>
	<LI><B>EXT_INT3</B> External Interrupt 3 input pin.</LI>
	<LI><B>EXT_INT4</B> External Interrupt 4 input pin.</LI>
	<LI><B>SPICLKIN</B> SPI clock input pin (only in slave mode).</LI>
	<LI><B>SPI_IN</B> SPI data input pin.</LI>
	<LI><B>SPI_SS</B> SPI slave select input pin (only in slave mode).</LI>
	<LI><B>TIM_4_CLK</B> External Timer 4 input pin.</LI>
	<LI><B>UART1TX</B> UART1 TX output pin.</LI>
	<LI><B>UART1RTS</B> UART1 RTS output pin.</LI>
	<LI><B>UART2TX</B> UART2 TX output pin.</LI>
	<LI><B>UART2RTS</B> UART2 RTS output pin.</LI>
	<LI><B>UART3TX</B> UART3 TX output pin.</LI>
	<LI><B>UART3RTS</B> UART3 RTS output pin.</LI>
	<LI><B>UART4TX</B> UART4 TX output pin. <B><I>Note:</B>not available for Flyport GPRS</I></LI>
	<LI><B>UART4RTS</B> UART4 RTS output pin. <B><I>Note:</B>not available for Flyport GPRS</I></LI>
	<LI><B>SPICLKOUT</B> SPI clock output pin (only in master mode).</LI>
	<LI><B>SPI_OUT</B> SPI data output pin.</LI>
	<LI><B>SPI_SS_OUT</B> SPI slave select output pin (only in master mode).</LI>
	<LI><B>RESET_PPS</B> Removes previously selected PPS output function.</LI>
</UL>
 * \return None
 */ 
void IOInit(int io, int putval) 
{
	io--;
	WORD addval = 0;
	if (putval < 5)
	{
		switch (putval)
		{
		//	Pin set as OUPUT first disables pull-up and pull-down, then set pin 
		//	as output
		case 0:
			addval = 1 << CNPos[io];
			addval = ~addval;
			*CNPDs[io] = *CNPDs[io] & addval;
			*CNPUs[io] = *CNPUs[io] & addval;
			addval = 0;
			addval = 1 << IOPos[io];
			addval = ~addval;
			*TRISs[io] = *TRISs[io] & addval;
			IOMode[io] = 0;
			break;
			
		//	Pin set as INPUT - first sets the pin as input, then disables pull-up 
		//	and pull-down
		case 1:
			addval = 1 << IOPos[io];
			*TRISs[io] = *TRISs[io] | addval;	
			addval = 0;	
			addval = 1 << CNPos[io];
			addval = ~addval;
			*CNPDs[io] = *CNPDs[io] & addval;
			*CNPUs[io] = *CNPUs[io] & addval;	
			IOMode[io] = 1;
			break;
			
		//	Pin set as INPUT with Pull-up - First disables pull-down, then sets 
		//	pin as input and enables pull-up
		case 2:
			addval = 1 << CNPos[io];
			addval = ~addval;
			*CNPDs[io] = *CNPDs[io] & addval;
			addval = ~addval;
			*CNPUs[io] = *CNPUs[io] | addval;
			addval = 0;
			addval = 1 << IOPos[io];
			*TRISs[io] = *TRISs[io] | addval;
			IOMode[io] = 2;
			break;
			
		//	Pin set as INPUT with Pull-down - First disables pull-up, then sets
		//	pin as input and enables pull-down
		case 3:
			addval = 1 << CNPos[io];
			addval = ~addval;
			*CNPUs[io] = *CNPUs[io] & addval;
			addval = ~addval;
			*CNPDs[io] = *CNPDs[io] | addval;	
			addval = 0;
			addval = 1 << IOPos[io];
			*TRISs[io] = *TRISs[io] | addval;
			IOMode[io] = 3;		
		}
	}
	else if (putval < 31)
	{
		if (RPIORPin[io] != 0)
		{
			if ( (putval < 13) || (putval > 15) )
			{
				addval = 1 << IOPos[io];
				*TRISs[io] = *TRISs[io] | addval;	
				addval = 0;	
				addval = 1 << CNPos[io];
				addval = ~addval;
				*CNPDs[io] = *CNPDs[io] & addval;
				*CNPUs[io] = *CNPUs[io] & addval;	
				IOMode[io] = 1;
			}
			
			int rpdummy;
			if (RPIORPin[io] < 0)
				rpdummy = -RPIORPin[io];
			else 
				rpdummy = RPIORPin[io];
			int reg_val;
			if (RPIRPos[putval-5])
			{
				reg_val = 0x00FF & (*RPIRs[putval-5]);
				reg_val = reg_val | ( rpdummy << 8);
			}
			else
			{
				reg_val = 0xFF00 & (*RPIRs[putval-5]);
				reg_val = reg_val | rpdummy;
			}
			__builtin_write_OSCCONL(OSCCON & 0xBF);						// Unlock registers	
			(*RPIRs[putval-5]) = reg_val;
			__builtin_write_OSCCONL(OSCCON | 0x40);						// Lock register
		}
	}
	else if (putval == RESET_PPS)
	{
		__builtin_write_OSCCONL(OSCCON & 0xBF);							// Unlock registers
		if (RPIORPin[io]%2==0)
		{					  											// Tests which pin is remapped
			*RPORs[io] =  (*RPORs[io]&0xFFC0); 							// Write on RPOR from 0 to 5th bit
		}
		else
		{
			*RPORs[io] = (*RPORs[io]&0xC0FF);							// Write on RPOR from 8th to 13th bit
		}
		__builtin_write_OSCCONL(OSCCON | 0x40);	
	}
	else if (putval > 30)
	{
		__builtin_write_OSCCONL(OSCCON & 0xBF);							// Unlock registers
		if (RPIORPin[io]%2==0)
		{					  											// Tests which pin is remapped
			*RPORs[io] =  (*RPORs[io]&0x3F00)|(RPFunc[putval-31]);		// Write on RPOR from 0 to 5th bit
		}
		else
		{
			*RPORs[io] = (*RPORs[io]&0x3F)|(RPFunc[putval-31]<<8);		// Write on RPOR from 8th to 13th bit
		}
		__builtin_write_OSCCONL(OSCCON | 0x40);	
	}

}		
int main()
{
   // Initialize the LIN interface
    if (l_sys_init())
        return -1;

    // Initialize the interface
    if (l_ifc_init_UART1())
        return -1;

    // Set UART TX to interrupt level 5
    // Set UART RX to interrupt level 5
    struct l_irqmask irqmask = { 6, 6 };
    l_sys_irq_restore(irqmask);
    
    l_bool configuration_ok = false;
    l_u16 configuration_timeout = 1000;
    do {
        if (l_ifc_read_status_UART1() & (1 << 6)) {
            configuration_ok = true;
            break;
        }
        __delay_ms(5);
        configuration_timeout--;
    } while (configuration_timeout || !configuration_ok);
    
    if (!configuration_ok) {
        // Master did not configure this node.
        return -1;
    }
    
    TRISBbits.TRISB8 = 1;
    __builtin_write_OSCCONL(OSCCON & ~(1<<6));
    RPINR7bits.IC1R = 8;
    __builtin_write_OSCCONL(OSCCON | (1<<6));
    
     // Setup a 125ms timer
    T1CONbits.TON = 1;
    T1CONbits.TSIDL = 0;
    T1CONbits.TGATE = 0;
    T1CONbits.TCKPS = 2;
    T1CONbits.TSYNC = 0;
    T1CONbits.TCS = 0;
    PR1 = FCY / 64ul / 8ul;
    
    IEC0bits.T1IE = 1;
    IPC0bits.T1IP = 4;
    
    IC1CON2bits.SYNCSEL = 0b10100;
    IC1CON1bits.ICTSEL  = 0b111;
    IC1CON1bits.ICI     = 0x00;
    IC1CON2bits.ICTRIG  = 0x00;
    IC1CON1bits.ICM     = 0x03;
    IEC0bits.IC1IE = 1;
    IPC0bits.IC1IP = 3;
    
    while (1) {
        main_task();
    }

    return -1;
}
Exemple #9
0
/////////////////////////////////////////////////////////////////////////////
// Function: InitializeBoard()
// Input: none
// Output: none
// Overview: Initializes the hardware components including the PIC device
//           used.
/////////////////////////////////////////////////////////////////////////////
void InitializeBoard(void)
{
        /////////////////////////////////////////////////////////////////////////////
        // ADC Explorer 16 Development Board Errata (work around 2)
        // RB15 should be output
        /////////////////////////////////////////////////////////////////////////////
            LATBbits.LATB15 = 0;
            TRISBbits.TRISB15 = 0;

    #if defined(__dsPIC33F__) || defined(__PIC24H__)

        // 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 switching 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)
        { };
        
        // Set PMD0 pin functionality to digital
        AD1PCFGL = AD1PCFGL | 0x1000;

        #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)
            AD1PCFGLbits.PCFG6 = 1;
            AD1PCFGLbits.PCFG7 = 1;
            AD1PCFGLbits.PCFG8 = 1;
        #endif
        
    #elif defined(__PIC32MX__)
        INTEnableSystemMultiVectoredInt();
        SYSTEMConfigPerformance(GetSystemClock());
    #endif // #if defined(__dsPIC33F__) || defined(__PIC24H__)
    

    #if defined (EXPLORER_16)
/************************************************************************
* For Explorer 16 RD12 is connected to EEPROM chip select.
* To prevent a conflict between this EEPROM and SST25 flash
* the chip select of the EEPROM SPI should be pulled up.
************************************************************************/
        // Set IOs directions for EEPROM SPI
        MCHP25LC256_CS_LAT = 1;			    // set initial CS value to 1 (not asserted)
    	MCHP25LC256_CS_TRIS = 0;			// set CS pin to output
	#endif // #if defined (EXPLORER_16)


     //The following are PIC device specific settings for the SPI channel
     //used. 
    
     //Set IOs directions for SST25 SPI   
        SST25_CS_LAT = 1;
        SST25_CS_TRIS = 0;
 
       #ifndef __PIC32MX__
            SST25_SCK_TRIS = 0;
            SST25_SDO_TRIS = 0;
            SST25_SDI_TRIS = 1;
            #if defined(__PIC24FJ256GB210__)
            	SST25_SDI_ANS = 0;
    	    #endif
       #endif
    // set the peripheral pin select for the PSI channel used
    #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)
        AD1PCFGL = 0xFFFF;
        RPOR9bits.RP18R = 11;                   // assign RP18 for SCK2
        RPOR8bits.RP16R = 10;                   // assign RP16 for SDO2
        RPINR22bits.SDI2R = 17;                 // assign RP17 for SDI2	
    #elif defined(__PIC24FJ256GB110__) || defined(__PIC24FJ256GA110__) || defined (__PIC24FJ256GB210__)
        __builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS
        RPOR10bits.RP21R = 11;                  // assign RP21 for SCK2
        RPOR9bits.RP19R = 10;                   // assign RP19 for SDO2
        RPINR22bits.SDI2R = 26;                 // assign RP26 for SDI2
        __builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS
    #elif defined(__PIC24FJ256DA210__)

        __builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS

    	#if (SST25_SPI_CHANNEL == 1)
    	    RPOR1bits.RP2R = 8;                 // assign RP2 for SCK1
    	    RPOR0bits.RP1R = 7;                 // assign RP1 for SDO1
    	    RPINR20bits.SDI1R = 0;              // assign RP0 for SDI1
        #elif (SST25_SPI_CHANNEL == 2)
            RPOR1bits.RP2R = 11;                // assign RP2 for SCK2
    	    RPOR0bits.RP1R = 10;                // assign RP1 for SDO2
    	    RPINR22bits.SDI2R = 0;              // assign RP0 for SDI2
    	#endif

        __builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS

    #endif

    /////////////////////////////////////////////////////////////////////////////
    //                  DRIVER SPECIFIC INITIALIZATION DATA
    /////////////////////////////////////////////////////////////////////////////

	GOLInit();                      // Initialize graphics library and create default style scheme for GOL

    // initialize GFX3 SST25 flash SPI
    SST25Init((void*) &SPI_Init_Data);                    
   
    TickInit();                     	

	
#if defined(SPI_CHANNEL_1_ENABLE) && defined(__PIC32MX__)          //SPI1 shares pins with the PMP CS. Not recommended for use
    SPI1TouchInit();

/****
 * AR1020 Touch Screen Controller
 *
 * Because the AR1020 needs to use the SPI channel to retrieve data and 
 * SPI channel 1 shares the PMP CS pin, this combination is not supported.
 * The user will receive a compile time error to avoid run time errors 
 * with this combination.
 ****/
#ifdef USE_TOUCHSCREEN_AR1020
#error "The combination of AR1020 touch screen controller and SPI 1 channel is not supported.  Please use SPI channel 2 with the AR1020 controller, or resistive touch."
#endif

#else	
    // initialize the components for Resistive Touch Screen
    TouchInit(NVMWrite, NVMRead, NVMSectorErase, TOUCH_INIT_VALUES);  
#endif	

    HardwareButtonInit();           	// Initialize the hardware buttons

}   
Exemple #10
0
void spi_open(_SPI *self, _PIN *MISO, _PIN *MOSI, _PIN *SCK, float freq, uint8_t mode) {
    uint16_t primary, secondary;
    uint16_t modebits[4] = { 0x0100, 0x0000, 0x0140, 0x0040 };

    if ((MISO->rpnum==-1) || (MOSI->rpnum==-1) || (SCK->rpnum==-1))
        return; // At least one of the specified pins is not an RP pin
    if ((MISO->owner==NULL) && (MOSI->owner==NULL) && (SCK->owner==NULL)) {
        // All of the specified pins are available and RP pins, so configure 
        // as specified
        pin_digitalIn(MISO);
        pin_digitalOut(MOSI);
        pin_set(MOSI);
        pin_digitalOut(SCK);
        pin_clear(SCK);
        self->MISO = MISO;
        MISO->owner = (void *)self;
        MISO->write = NULL;
        MISO->read = NULL;
        self->MOSI = MOSI;
        MOSI->owner = (void *)self;
        MOSI->write = NULL;
        MOSI->read = NULL;
        self->SCK = SCK;
        SCK->owner = (void *)self;
        SCK->write = NULL;
        SCK->read = NULL;
        __builtin_write_OSCCONL(OSCCON&0xBF);
        *(self->MISOrpinr) &= ~(0x3F<<(self->MISOrpshift));
        *(self->MISOrpinr) |= (MISO->rpnum)<<(self->MISOrpshift);
        *(MOSI->rpor) &= ~(0x3F<<(MOSI->rpshift));
        *(MOSI->rpor) |= (self->MOSIrpnum)<<(MOSI->rpshift);
        *(SCK->rpor) &= ~(0x3F<<(SCK->rpshift));
        *(SCK->rpor) |= (self->SCKrpnum)<<(SCK->rpshift);
        __builtin_write_OSCCONL(OSCCON|0x40);
    } else if ((self->MISO!=MISO) || (self->MOSI!=MOSI) || (self->SCK!=SCK)) {
        return; // At least one of the specified pins does not match the 
                // previous assignment
    }
    // Clip freq to be in allowable range of values
    if (freq>(FCY/2.))
        freq = FCY/2.;
    if (freq<(FCY/(64.*8.)))
        freq = FCY/(64.*8.);
    // Select primary prescale bits
    if (freq<=(FCY/(2.*64.))) {
        freq *= 64.;
        primary = 0;    // Set primary prescale bits for 64:1
    } else if (freq<=(FCY/(2.*16.))) {
        freq *= 16.;
        primary = 1;    // Set primary prescale bits for 16:1
    } else if (freq<=(FCY/(2.*4.))) {
        freq *= 4.;
        primary = 2;    // Set primary prescale bits for 4:1
    } else {
        primary = 3;    // Set primary prescale bits for 1:1
    }
    // Compute secondary prescale value to get closest SPI clock freq to that 
    // specified
    secondary = (uint16_t)(0.5+FCY/freq);
    secondary = (8-secondary)<<2;   // Map secondary prescale bits for SPIxCON1
    // Configure the SPI module
    //   set SPI module to 8-bit master mode
    //   set SMP = 0, CKE = 1, and CKP = 0, 0x0120
    //   set SMP=1, CKE,CKP=0, 0x0220
    //   set SPRE and PPRE bits to get the closest SPI clock freq to that 
    //   specified
    *(self->SPIxCON1) = 0x0220|primary|secondary;
    *(self->SPIxCON2) = 0;
    // Enable the SPI module and clear status flags
    *(self->SPIxSTAT) = 0x8000;
}
Exemple #11
0
/** Main **/
int main(void){  
    /** Declare Local Variables **/
    
    /** Initialize State Variables **/
    myBOOLs.mainMenuTrue = TRUE;    // want program to enter into the main menu
    myBOOLs.mainDecide = TRUE;      // want program to enter into the main menu
    myBOOLs.modeMenuTrue = FALSE;
    myBOOLs.modeDecide = FALSE;
    myBOOLs.rpmMenuTrue = FALSE;
    myBOOLs.rpmDecide = FALSE;
    
    /** Initialize Value Variables **/
    rpm = 60;
    
    /** Configure Analog Ports **/
    AD1PCFGbits.PCFG5 = HIGH;  // disable analog functionality for AN5 (Encoder Pin A)
    AD1PCFGbits.PCFG0 = HIGH;  // disable analog functionality for AN0 (SPI - SS)
    AD1PCFGbits.PCFG2 = HIGH;  // disable analog functionality for AN2 (SPI - SDI)
    AD1PCFGbits.PCFG4 = HIGH;  // disable analog functionality for AN4 (SPI - SCK)

    /** Configure Pin Directions **/
    TRISAbits.TRISA2 = OUTPUT;      // *output* Stepper Motor Dir
    TRISAbits.TRISA4 = OUTPUT;      // *output* Red LED Sink
    
    TRISBbits.TRISB3 = INPUT;       // *input* (Encoder Pin A) ~interrupt
    TRISBbits.TRISB4 = INPUT;       // *input* (Encoder Pin B)
    TRISBbits.TRISB9 = INPUT;       // *input* (Encoder PUSH) ~interrupt
    
    TRISAbits.TRISA0 = OUTPUT;      // *output* (SS for Thermo)
    TRISBbits.TRISB0 = INPUT;       // *input*  (SPI - SDI)
    TRISBbits.TRISB2 = OUTPUT;      // *output* (SPI - SCK)
    
    /** Initialize Pin States **/
    LATAbits.LATA2 = LOW;       // Set direction to CW
    LATAbits.LATA4 = LOW;       // Set Red LED ON (sink current)
    LATAbits.LATA0 = HIGH;      // Set SS high
    TRISBbits.TRISB2 = LOW;     // Set SCK low
    
    /** Configure Peripheral Pin Selects **/
    __builtin_write_OSCCONL(OSCCON & 0xBF); // unlock registers to configure PPS
    RPINR0bits.INT1R = 3;   // configure RP3 as Ext. Int. 1
    RPINR1bits.INT2R = 9;   // configure RP9 as Ext. Int. 2
    RPOR7bits.RP15R = 18;   // configure RP15 as OC1 (PWM for EasyDriver)
    RPOR5bits.RP10R = 19;   // configure RP11 as OC2 (PWM for buzzer)
    __builtin_write_OSCCONL(OSCCON | 0x40); // lock registers
    
    /** Configure PWMs **/
    period = ((8000000*60)/(1600*rpm));     // calculate PR based on desired PRM
    duty = period/2;                        // duty cycle of 50%
    initPWM(period, duty);                  // PWM initialization function
    initPWMbuzz();

    /** Configure PMP & LCD **/
    initPMP();
    initLCD();
    
    setLCDG(0);
    putLCD(0b00000);
    putLCD(0b01100);
    putLCD(0b01100);
    putLCD(0b01100);
    putLCD(0b11110);
    putLCD(0b11110);
    putLCD(0b01100);
    putLCD(0);
    
    /** Configure Interrupts **/
    INTCON2bits.ALTIVT = 0; //use primary IVT
    //EXT1 interrupt
    INTCON2bits.INT1EP = 1; // interrupt on falling edge
    IPC5bits.INT1IP = 4; //set priority level to 4
    IFS1bits.INT1IF = 0; //initialize INT1 flag to zero
    IEC1bits.INT1IE = 1; //enable the interrupt source
    //EXT2 interrupt
    INTCON2bits.INT2EP = 1; // interrupt on falling edge
    IPC7bits.INT2IP = 7; //set priority level to 4
    IFS1bits.INT2IF = 0; //initialize INT2 flag to zero
    IEC1bits.INT2IE = 1; //enable the interrupt source

    /** LCD Splash Screen **/
    clearLCD();
    setCursor(1,0);
    putsLCD("   Stir Plate   ");
    setCursor(2,0);
    putsLCD("      9000      ");
    delay_ms(3000);
    clearLCD();
    OC2CON = 0x0000;
    /*------------------INFINITE LOOP------------------*/
    while(1)
    {
        menuDecision();
    }
    return (EXIT_SUCCESS);
}
int main (void)
{

   FSFILE * pointer=NULL;
   DWORD first_sector;
   BYTE test_array[512];
   SearchRec rec;
   pointer=NULL;
   unsigned char attributes;
   unsigned char size = 0, i;
   PLLFBD =38;
   CLKDIVbits.PLLPOST=0;
   CLKDIVbits.PLLPRE=0;
   __builtin_write_OSCCONH(0b011);
   __builtin_write_OSCCONL(0b01);
	while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur	
	while(OSCCONbits.LOCK != 1) {};
	UART2Init();
	printf("starting Integration test\r\n");
	//DataEEInit();
	int id=0;
	id=Get_ID_Code();
	printf("ID: %u\r\n",id);
	OFB_init(id);
	Increment_ID_Code();
	#ifdef __DEBUG
		printf("Clock Switch Complete, Waiting For Media\r\n");
	#endif
	//waits for a card to be inserted
   while (!MDD_MediaDetect());
	#ifdef __DEBUG
		printf("Media Found, Waiting for FSinit\r\n");
	#endif
   // Initialize the library
   while (!FSInit());
   char filename[9];
   sprintf(filename,"%05d.bin",id);
   // Create a file
   printf("filename will be: %s\r\n",filename);
   while(pointer==NULL)
   {
   		pointer = FSfopen (filename, "w");
   }
   #ifdef __DEBUG
   	printf("File Has been opened\r\n");
   #endif		
	
	while(1)
	{
		Service_Spi(pointer);
	}	
	//printf("stuipd thing");
	//TRISD=0x0FF;
	//setting up pins to show on usb debugger
	TRISDbits.TRISD6=1;
	TRISAbits.TRISA7=0;
	TRISAbits.TRISA6=0;
	TRISAbits.TRISA5=0;
	TRISAbits.TRISA4=0;
	TRISGbits.TRISG0=0;
	AD1PCFGLbits.PCFG0=1;	
	//LATA=1;
	//_LATA4=1;
	//_RA7=1;
	//_LATA6=1;
	
	//_LATA5=1;
	//_LATA7=1;
	
	//printf("they should be on now");
	//while(1);
	//LATAbits.LATA7=0;
	//TRISB=0xFFFF;
	//AD1PCFGLbits.PCFG1=1;	
	//Service_Spi();
	/*#ifdef __DEBUG
		printf("Clock Switch Complete, Waiting For Media\r\n");
	#endif
	//waits for a card to be inserted
   while (!MDD_MediaDetect());
   
   
	#ifdef __DEBUG
		printf("Media Found, Waiting for FSinit\r\n");
	#endif
   // Initialize the library
   while (!FSInit());
	char temp;
	int character_count,remove_success;
	character_count=0;
   // Create a file
   printf("starting up\r\n");
   remove_success=FSremove("WRITE.TXT");
   printf("Removal of prev: %d\r\n",remove_success);
   pointer = FSfopen ("WRITE.TXT", "w");

   if (pointer == NULL)
   {
	   #ifdef __DEBUG
	   	printf("File open failed\r\n");
	   #endif
      while(1);
   }   

   printf("waiting for operation\r\n");
   printf("in file resize_test\r\n");
   
   
   DWORD sizeinbytes;
   //need to convert from number of sectors to number of bytes and allocate that much space
   sizeinbytes=(DWORD)FILESIZE*(DWORD)512;
   printf("Chew Fat: %lu\r\nChew Fat Sectors: %d\r\n",CHEW_FAT_SIZE,CHEW_FAT_SIZE_IN_SECTORS);
   //sizeinbytes=3774873*(DWORD)512;
   //allocate_size(sizeinbytes,pointer,FALSE);
   //FSfclose(pointer);*/
   /*FILEallocate_multiple_clusters(pointer,24);
   FAT_print_cluster_chain(pointer->cluster, pointer->dsk);
   FILEallocate_multiple_clusters(pointer,24);
   FAT_print_cluster_chain(pointer->cluster, pointer->dsk);
   int numclus,numcount;
   //DWORD clusttemp;
   printf("First CLuster in main: %lu\r\n",get_First_Sector(pointer));
   for (numclus=0;numclus<48;numclus++)
   {
		for(numcount=0;numcount<512;numcount++)
		{
		   test_array[numcount]=numclus+48;
		}
		MDD_SDSPI_SectorWrite(get_First_Sector(pointer)+numclus,test_array,FALSE);
	}*/
   //FILEallocate_multiple_clusters(pointer,24);
   //FILEallocate_multiple_clusters(pointer,24);
   //FILEallocate_multiple_clusters(pointer,CHEW_FAT_SIZE_IN_SECTORS);
   //FSfclose(pointer);
   //FILEallocate_multiple_clusters(pointer,4096);
   //FSfclose(pointer);
   //FILEallocate_multiple_clusters(pointer,1024);
   //FILEallocate_multiple_clusters(pointer,1024);
   
   //FSfseek(pointer,0,SEEK_SET);
   first_sector=get_First_Sector(pointer);
   set_First_Sector(first_sector);
   DWORD erasure;
   OFB_init(0x1f1f);
   //FSfclose(pointer);
   //MDD_ShutdownMedia();
   printf("done with file allocation\r\n");
   #ifdef DMAON
   #else
   #endif
      
      //while(UART2IsEmpty());
      //temp=UART2GetChar();
      //write_array[character_count]=temp;
      //character_count++;
    while(1)
    {
	    Service_Spi(pointer);
	}
}
/********************************************************************
* Function: 	main()
********************************************************************/
INT main(void)
{
   DWORD count1 = 0;
   BYTE timer_ro = 1;

   // switch to FRC w/PLL to keep up at higher baud rates (120MHz!
   PLLFBD=63;
   CLKDIVbits.PLLPOST = 0;
   CLKDIVbits.PLLPRE = 0;

    __builtin_write_OSCCONH(0x01);
   __builtin_write_OSCCONL(OSCCON | 0x01);

   while (OSCCONbits.COSC != 0b001);
   while (OSCCONbits.LOCK != 1);

   // Initialize I/O, UART and timer (interrupt)
   initIO();

   led1Off();
   led2Off();
   led3Off();

   printString("BL:V1.00:");
   
   if (ValidAppPresent())
   {
      while(count1<20)
      {
         if ((SWITCH1 == 0) || (SWITCH2 == 0))  // if either switch gets released, start app
            JumpToApp();

         // Blink LEDs
         if (timer_ro)
         {
            if (TMR1 > 7000)
            {
               blinkLEDs();
               count1++;
               timer_ro = 0;
            }
         }
         else if (TMR1 < 7000)
            timer_ro = 1;
      }
      printString("PB:");
   }
   else
   {
      printString("NA:");                    // No app present, enter bootloader regardless
   }

   T1CONbits.TON = 0;
   PR1 = 50000;                              // slow down blinking
   T1CONbits.TON = 1;

   blink_mode = 1;

   // Be in loop till framework recieves "run application" command from PC
   while(!ExitFirmwareUpgradeMode()) 
   {
      uartTask();          // Run Transport layer tasks
      if(FrameWorkTask())  // Run frame work related tasks (Handling Rx frame, process frame and so on)
      {
         blink_mode = 2;   // If we've communicated with the PC, use progress flashing
      }

      // Blink LEDs
      if (timer_ro)
      {
         if (TMR1 > 25000)
         {
            if (SWITCH1 && (SWITCH2 == 0))   // reset the device on SWITCH1 press
               reset();
            
            blinkLEDs();
            timer_ro = 0;
         }
      }
      else if (TMR1 < 25000)
         timer_ro = 1;
   }
   
	JumpToApp();
	return 0;
}			
Exemple #14
0
    /* read out configuration from HW */  
    return systemClockGetFcy( );
}

u32 systemClockGetFcy ( )
{
    u32 frequency = 0;
    switch ( OSCCONbits.COSC )
    {

        case CLK_SRC_LPRC:
	    frequency = LPRC_NOMINAL;
	    break;

        case CLK_SRC_SOSC:
	    frequency = SOSC_NOMINAL;
	    break;

        case CLK_SRC_POSC_PLL:
	    if ( POSC_NOMINAL )
	    {
	        frequency = systemClockFromPllPrescaler( );
	    }
	    break;

	case CLK_SRC_POSC:
	    frequency = POSC_NOMINAL;
	    break;

        case CLK_SRC_FRCDIV:
	    frequency = systemClockFromFrcPostscaler( );
	    break;

        case CLK_SRC_FRCPLL:
	  frequency = systemClockFromPllPrescaler( );
	  break;

        case CLK_SRC_FRC:
	  frequency = FRC_NOMINAL;
	  break;
    }
    theSystemClock = frequency / 2; /* the theSystemClock is always half the system clock frequency */ 
    return theSystemClock;
}

u8 systemClockGetClockSource ( )
{
    return OSCCONbits.COSC;
}


#if !defined(__PIC24FJ256GB110__)   /* TODO: adapt this for GB110 (has no PLLEN but PLLDIS in config words) */
u32 systemClockChangeClockSource ( u16 source, u32 newFcy )
{
    u32 frequency = newFcy * 2;

    PwrMgnt_OscSel( source );

#if 0
    /* if necessary change the source */
    if ( OSCCONbits.COSC != source )
    { /* change source */
        OSCCONBITS newOSCCONbits = OSCCONbits;
        WORD_VAL newOSCCON;

        /* NOTE: the Config Word2 must have either FCKSM_CSECME or FCKSM_CSECMD
           This means that clock-switching is enabled. We could read out the
           config-word2 and check that the corresponding bit is cleared.
           */

        newOSCCONbits.NOSC = source;
        newOSCCONbits.LOCK = 0;  /* read-only - so don't care */
        newOSCCONbits.OSWEN = 1; /* switch clock */

        /* convert from struct to word - need to go via the "void*" as we
           compile with strict-aliasing */
	newOSCCON.Val = *(WORD*)((void*)(&newOSCCONbits));

        __builtin_write_OSCCONH( newOSCCON.byte.HB );
        __builtin_write_OSCCONL( newOSCCON.byte.LB );

        while ( OSCCONbits.OSWEN ); /* wait for switch */


    }
#endif

    /* now depending on clock source we can trim the frequency or not */
    switch ( OSCCONbits.COSC )
    {
        case CLK_SRC_LPRC:
	    frequency = LPRC_NOMINAL;
            CLKDIVbits.PLLEN = 0; /* disable pll */
	    break;

        case CLK_SRC_SOSC:
	    frequency = SOSC_NOMINAL;
            CLKDIVbits.PLLEN = 0; /* disable pll */
	    break;

        case CLK_SRC_POSC_PLL:
	    if ( POSC_NOMINAL )
	    {
	      /* find desired fcy in either 4, 8, 16, or 32 MHz */
	        systemClockFindPllPrescaler( frequency );
		frequency = systemClockFromPllPrescaler( );
	    }
	    break;

	case CLK_SRC_POSC:
	    frequency = POSC_NOMINAL;
            CLKDIVbits.PLLEN = 0; /* disable pll */
	    break;

        case CLK_SRC_FRCDIV:
	    /* find desired fcy in either 8, 4, 2, .... 32.25kHz */
	    systemClockFindFrcPostscaler( frequency );
	    frequency = systemClockFromFrcPostscaler( );
            CLKDIVbits.PLLEN = 0; /* disable pll */
	    break;

        case CLK_SRC_FRCPLL:
	    /* find desired fcy in either 4, 8, 16, or 32 MHz */
	    systemClockFindPllPrescaler( frequency );
	    frequency = systemClockFromPllPrescaler( );
	    break;

        case CLK_SRC_FRC:
	    frequency = FRC_NOMINAL;
            CLKDIVbits.PLLEN = 0; /* disable pll */
	    break;
    }
    theSystemClock = frequency / 2; /* the theSystemClock is always half the system clock frequency */ 
    return theSystemClock;
}
Exemple #15
0
int main(void)
{

	short i,j;
	
// 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 switching 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) {};


	TRISA = 0x0;				// set to all outputs

	// setup the SPI1 port
	// setup the I/O pins properly (SDI1 as input, SDO1 as output, RG3 as output)
	PORTG = 0xFFFF;
	TRISG = 0x5F5F;
	PORTF = 0x0;
	TRISF = 0x5F;
	AD1PCFGLbits.PCFG2 = 1;		// set the RB0 pin to Digital Mode (all others to analog) 
	TRISF = 0x0080;				// set PORTF to output except for SDI1
	
	
	

	while(1)
	{
		//demonstrate the SPI peripheral in Master Mode CKE = 0, CKP = 0
	
			Init_SPI();
	
		for (i=0;i<255;i++)
			{
				write_SPI1(i);
				delay();
			} 

		for (i=0;i<255;i++)
			{
				write_SPI2(i);
				delay();
			} 

		for (i=0;i<255;i++)
			{
				write_SPI1(i);
				delay();
				write_SPI2(i);
				delay();
			} 


	}
}
Exemple #16
0
int main (void)
{
   FSFILE * pointer;
   #if defined(SUPPORT_LFN)
   char count = 80;
   #endif
   char * pointer2;
   SearchRec rec;
   unsigned char attributes;
   unsigned char size = 0, i;

	// Turn on the secondary oscillator
	__asm__ ("MOV #OSCCON,w1");
	__asm__ ("MOV.b #0x02, w0");
	__asm__ ("MOV #0x46, w2");
	__asm__ ("MOV #0x57, w3");
	__asm__ ("MOV.b w2, [w1]");
	__asm__ ("MOV.b w3, [w1]");
	__asm__ ("MOV.b w0, [w1]");

	// Activate the RTCC module
	__asm__ ("mov #NVMKEY,W0");
	__asm__ ("mov #0x55,W1");
	__asm__ ("mov #0xAA,W2");
	__asm__ ("mov W1,[W0]");
	__asm__ ("nop");
	__asm__ ("mov W2,[W0]");
	__asm__ ("bset RCFGCAL,#13");
	__asm__ ("nop");
	__asm__ ("nop");
	RCFGCALbits.RTCPTR0 = 1;
	RCFGCALbits.RTCPTR1 = 1;
	// Set it to the correct time
	// These values won't be accurate
	RTCVAL = 0x0007;   
	RTCVAL = 0x0717;
	RTCVAL = 0x0208;
	RTCVAL = 0x2137;
	RCFGCAL = 0x8000;

	#if defined(__PIC24FJ256DA210__)

		// Make Analog Pins Digital
		ANSB = 0x0000 ; 
		ANSA = 0x0000;
		ANSC = 0x0000;
		ANSD = 0x0000;

		// Enable PLL
		CLKDIVbits.PLLEN = 1; 

		// Configure SPI1 PPS pins (ENC28J60/ENCX24J600/MRF24WB0M or other PICtail Plus cards)
		__builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS

		RPOR1bits.RP2R = 8;       // assign RP2 for SCK1
		RPOR0bits.RP1R = 7;       // assign RP1 for SDO1
		RPINR20bits.SDI1R = 0;    // assign RP0 for SDI1

		__builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS                

	#elif defined(__PIC24FJ256GB110__)

		AD1PCFGL = 0xFFFF;

		//Initialize the SPI
		RPINR20bits.SDI1R = 23;
		RPOR7bits.RP15R = 7;
		RPOR0bits.RP0R = 8;    

		//enable a pull-up for the card detect, just in case the SD-Card isn't attached
		//  then lets have a pull-up to make sure we don't think it is there.
		CNPU5bits.CN68PUE = 1; 

	#endif

   while (!MDD_MediaDetect());

   // Initialize the library
   while (!FSInit());

#ifdef ALLOW_WRITES
   // Create a file
   pointer = FSfopen ("FILE1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write 21 1-byte objects from sendBuffer into the file
   if (FSfwrite (sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // FSftell returns the file's current position
   if (FSftell (pointer) != 21)
      while(1);

   // FSfseek sets the position one byte before the end
   // It can also set the position of a file forward from the
   // beginning or forward from the current position
   if (FSfseek(pointer, 1, SEEK_END))
      while(1);

   // Write a 2 at the end of the string
   if (FSfwrite (send2, 1, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create a second file
   pointer = FSfopen ("Microchip File 1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write the string to it again
   if (FSfwrite ((void *)sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);
#endif

   // Open file 1 in read mode
   pointer = FSfopen ("FILE1.TXT", "r");
   if (pointer == NULL)
      while(1);

   if (FSrename ("Microchip File 2.TXT", pointer))
      while(1);

   // Read one four-byte object
   if (FSfread (receiveBuffer, 4, 1, pointer) != 1)
      while(1);

   // Check if this is the end of the file- it shouldn't be
   if (FSfeof (pointer))
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Make sure we read correctly
   if ((receiveBuffer[0] != 'T') ||
         (receiveBuffer[1] != 'h')  ||
         (receiveBuffer[2] != 'i')  ||
         (receiveBuffer[3] != 's'))
   {
      while(1);
   }

#ifdef ALLOW_DIRS
   // Create a small directory tree
   // Beginning the path string with a '.' will create the tree in
   // the current directory.  Beginning with a '..' would create the
   // tree in the previous directory.  Beginning with just a '\' would
   // create the tree in the root directory.  Beginning with a dir name
   // would also create the tree in the current directory
   if (FSmkdir (".\\Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Change to 'Directory 3' in our new tree
   if (FSchdir ("Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Create another tree in 'Directory 3'
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 6"))
      while(1);

   // Create a third file in directory THREE
   pointer = FSfopen ("CWD.TXT", "w");
   if (pointer == NULL)
      while(1);

   #if defined(SUPPORT_LFN)
   // Get the name of the current working directory
   /* it should be "\Microchip Directory 1\Dir2\Directory 3" */
   pointer2 = wFSgetcwd ((unsigned short int *)path1, count);
   #endif

   if (pointer2 != path1)
      while(1);

   // Simple string length calculation
   i = 0;
   while(*((unsigned short int *)path1 + i) != 0x00)
   {
      size++;
      size++;
      i++;
   }
   // Write the name to CWD.TXT
   if (FSfwrite (path1, size, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create some more directories
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 7\\..\\Directory 8\\..\\..\\DIRNINE\\Directory 10\\..\\Directory 11\\..\\Directory 12"))
      while(1);

   /*******************************************************************
      Now our tree looks like this

 \ -> Mchp Directory 1 -> Dir2 -> Directory 3 -> Directory 4 -> Directory 5 -> Directory 6
                                                                                 -> Directory 7
                                                                                 -> Directory 8

                                                                    DIRNINE -> Directory 10
                                                                            -> Directory 11
                                                                            -> Directory 12
   ********************************************************************/

   // This will delete only Directory 8
   // If we tried to delete Directory 5 with this call, the FSrmdir
   // function would return -1, since Directory 5 is non-empty
   if (FSrmdir ("\\Mchp Directory 1\\Dir2\\Directory 3\\Directory 4\\Directory 5\\Directory 8", FALSE))
      while(1);

   // This will delete DIRNINE and all three of its sub-directories
   if (FSrmdir ("Directory 4\\DIRNINE", TRUE))
      while(1);

   // Change directory to the root dir
   if (FSchdir ("\\"))
      while(1);
#endif

#ifdef ALLOW_FILESEARCH
   // Set attributes
   attributes = ATTR_ARCHIVE | ATTR_READ_ONLY | ATTR_HIDDEN;

   // Functions "FindFirst" & "FindNext" can be used to find files
   // and directories with required attributes in the current working directory.

   // Find the first TXT file with any (or none) of those attributes that
   // has a name beginning with the letters "Mic"
   // These functions are more useful for finding out which files are
   // in your current working directory
   if (FindFirst ("Mic*.TXT", attributes, &rec))
      while(1);

 //   Find file to get "Microchip File 2.TXT"
      if (FindNext (&rec))
         while(1);

   #if defined(SUPPORT_LFN) 
  // Delete file 2
   // If the file name is long
   if(rec.utf16LFNfoundLength)
   {
      // NOTE : "wFSremove" function deletes specific file not directory.
      //        To delete directories use "wFSrmdir" function
      if (wFSremove (rec.utf16LFNfound))
         while(1);
   }
   else
   #endif
   {
      // NOTE : "FSremove" function deletes specific file not directory.
      //        To delete directories use "FSrmdir" function
      if (FSremove (rec.filename))
         while(1);
   }

#endif


/*********************************************************************
   The final contents of our card should look like this:
   \ -> Microchip File 1.TXT
      -> Mchp Directory 1 -> Dir2 -> Directory 3 -> CWD.TXT
                                                 -> Directory 4 -> Directory 5 -> Directory 6
                                                                               -> Directory 7

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


   while(1);
}
Exemple #17
0
/****************************************************************************
  Function:
    static void InitializeBoard(void)

  Description:
    This routine initializes the hardware.  It is a generic initialization
    routine for many of the Microchip development boards, using definitions
    in HardwareProfile.h to determine specific initialization.

  Precondition:
    None

  Parameters:
    None - None

  Returns:
    None

  Remarks:
    None
  ***************************************************************************/
static void InitializeBoard(void)
{	
	// LEDs
	LED0_TRIS = 0;
	LED1_TRIS = 0;
	LED2_TRIS = 0;
	LED3_TRIS = 0;
	LED4_TRIS = 0;
	LED5_TRIS = 0;
	LED6_TRIS = 0;
	LED7_TRIS = 0;
//	LED_PUT(0x00);

#if defined(__18CXX)
	// Enable 4x/5x/96MHz PLL on PIC18F87J10, PIC18F97J60, PIC18F87J50, etc.
    OSCTUNE = 0x40;

	// Set up analog features of PORTA

	// PICDEM.net 2 board has POT on AN2, Temp Sensor on AN3
	#if defined(PICDEMNET2)
		ADCON0 = 0x09;		// ADON, Channel 2
		ADCON1 = 0x0B;		// Vdd/Vss is +/-REF, AN0, AN1, AN2, AN3 are analog
	#elif defined(PICDEMZ)
		ADCON0 = 0x81;		// ADON, Channel 0, Fosc/32
		ADCON1 = 0x0F;		// Vdd/Vss is +/-REF, AN0, AN1, AN2, AN3 are all digital
	#elif defined(__18F87J11) || defined(_18F87J11) || defined(__18F87J50) || defined(_18F87J50)
		ADCON0 = 0x01;		// ADON, Channel 0, Vdd/Vss is +/-REF
		WDTCONbits.ADSHR = 1;
		ANCON0 = 0xFC;		// AN0 (POT) and AN1 (temp sensor) are anlog
		ANCON1 = 0xFF;
		WDTCONbits.ADSHR = 0;		
	#else
		ADCON0 = 0x01;		// ADON, Channel 0
		ADCON1 = 0x0E;		// Vdd/Vss is +/-REF, AN0 is analog
	#endif
	ADCON2 = 0xBE;		// Right justify, 20TAD ACQ time, Fosc/64 (~21.0kHz)


    // Enable internal PORTB pull-ups
    INTCON2bits.RBPU = 0;

	// Configure USART
    TXSTA = 0x20;
    RCSTA = 0x90;

	// See if we can use the high baud rate setting
	#if ((GetPeripheralClock()+2*BAUD_RATE)/BAUD_RATE/4 - 1) <= 255
		SPBRG = (GetPeripheralClock()+2*BAUD_RATE)/BAUD_RATE/4 - 1;
		TXSTAbits.BRGH = 1;
	#else	// Use the low baud rate setting
		SPBRG = (GetPeripheralClock()+8*BAUD_RATE)/BAUD_RATE/16 - 1;
	#endif


	// Enable Interrupts
	RCONbits.IPEN = 1;		// Enable interrupt priorities
    INTCONbits.GIEH = 1;
    INTCONbits.GIEL = 1;

    // Do a calibration A/D conversion
	#if defined(__18F87J10) || defined(__18F86J15) || defined(__18F86J10) || defined(__18F85J15) || defined(__18F85J10) || defined(__18F67J10) || defined(__18F66J15) || defined(__18F66J10) || defined(__18F65J15) || defined(__18F65J10) || defined(__18F97J60) || defined(__18F96J65) || defined(__18F96J60) || defined(__18F87J60) || defined(__18F86J65) || defined(__18F86J60) || defined(__18F67J60) || defined(__18F66J65) || defined(__18F66J60) || \
	     defined(_18F87J10) ||  defined(_18F86J15) || defined(_18F86J10)  ||  defined(_18F85J15) ||  defined(_18F85J10) ||  defined(_18F67J10) ||  defined(_18F66J15) ||  defined(_18F66J10) ||  defined(_18F65J15) ||  defined(_18F65J10) ||  defined(_18F97J60) ||  defined(_18F96J65) ||  defined(_18F96J60) ||  defined(_18F87J60) ||  defined(_18F86J65) ||  defined(_18F86J60) ||  defined(_18F67J60) ||  defined(_18F66J65) ||  defined(_18F66J60)
		ADCON0bits.ADCAL = 1;
	    ADCON0bits.GO = 1;
		while(ADCON0bits.GO);
		ADCON0bits.ADCAL = 0;
	#elif defined(__18F87J11) || defined(__18F86J16) || defined(__18F86J11) || defined(__18F67J11) || defined(__18F66J16) || defined(__18F66J11) || \
		   defined(_18F87J11) ||  defined(_18F86J16) ||  defined(_18F86J11) ||  defined(_18F67J11) ||  defined(_18F66J16) ||  defined(_18F66J11) || \
		  defined(__18F87J50) || defined(__18F86J55) || defined(__18F86J50) || defined(__18F67J50) || defined(__18F66J55) || defined(__18F66J50) || \
		   defined(_18F87J50) ||  defined(_18F86J55) ||  defined(_18F86J50) ||  defined(_18F67J50) ||  defined(_18F66J55) ||  defined(_18F66J50)
		ADCON1bits.ADCAL = 1;
	    ADCON0bits.GO = 1;
		while(ADCON0bits.GO);
		ADCON1bits.ADCAL = 0;
	#endif

#else	// 16-bit C30 and and 32-bit C32
	#if defined(__PIC32MX__)
	{
		// Enable multi-vectored interrupts
		INTEnableSystemMultiVectoredInt();
		
		// Enable optimal performance
		SYSTEMConfigPerformance(GetSystemClock());
		mOSCSetPBDIV(OSC_PB_DIV_1);				// Use 1:1 CPU Core:Peripheral clocks
		
		// Disable JTAG port so we get our I/O pins back, but first
		// wait 50ms so if you want to reprogram the part with 
		// JTAG, you'll still have a tiny window before JTAG goes away.
		// The PIC32 Starter Kit debuggers use JTAG and therefore must not 
		// disable JTAG.
		DelayMs(50);
		#if !defined(__MPLAB_DEBUGGER_PIC32MXSK) && !defined(__MPLAB_DEBUGGER_FS2)
			DDPCONbits.JTAGEN = 0;
		#endif
		LED_PUT(0x00);				// Turn the LEDs off
		
		CNPUESET = 0x00098000;		// Turn on weak pull ups on CN15, CN16, CN19 (RD5, RD7, RD13), which is connected to buttons on PIC32 Starter Kit boards
	}
	#endif

	#if defined(__dsPIC33F__) || defined(__PIC24H__)
		// Crank up the core frequency
		PLLFBD = 38;				// Multiply by 40 for 160MHz VCO output (8MHz XT oscillator)
		CLKDIV = 0x0000;			// FRC: divide by 2, PLLPOST: divide by 2, PLLPRE: divide by 2
	
		// Port I/O
		#if defined (WIFI_BOARD_FOC_HUB)
			AD1PCFGL = 0xFFFF; 	// All pins digital
		#else
			AD1PCFGHbits.PCFG23 = 1;	// Make RA7 (BUTTON1) a digital input
			AD1PCFGHbits.PCFG20 = 1;	// Make RA12 (INT1) a digital input for MRF24WB0M PICtail Plus interrupt
			
			// ADC
	    	AD1CHS0 = 0;				// Input to AN0 (potentiometer)
			AD1PCFGLbits.PCFG5 = 0;		// Disable digital input on AN5 (potentiometer)
			AD1PCFGLbits.PCFG4 = 0;		// Disable digital input on AN4 (TC1047A temp sensor)
		#endif
	#else	//defined(__PIC24F__) || defined(__PIC32MX__)
		#if defined(__PIC24F__)
			CLKDIVbits.RCDIV = 0;		// Set 1:1 8MHz FRC postscalar
		#endif
		
		// ADC
	    #if defined(__PIC24FJ256DA210__) || defined(__PIC24FJ256GB210__)
	    	// Disable analog on all pins
	    	ANSA = 0x0000;
	    	ANSB = 0x0000;
	    	ANSC = 0x0000;
	    	ANSD = 0x0000;
	    	ANSE = 0x0000;
	    	ANSF = 0x0000;
	    	ANSG = 0x0000;
		#else
		    AD1CHS = 0;					// Input to AN0 (potentiometer)
			AD1PCFGbits.PCFG4 = 0;		// Disable digital input on AN4 (TC1047A temp sensor)
			#if defined(__32MX460F512L__) || defined(__32MX795F512L__)	// PIC32MX460F512L and PIC32MX795F512L PIMs has different pinout to accomodate USB module
				AD1PCFGbits.PCFG2 = 0;		// Disable digital input on AN2 (potentiometer)
			#else
				AD1PCFGbits.PCFG5 = 0;		// Disable digital input on AN5 (potentiometer)
			#endif
		#endif
	#endif

	// ADC
	#if defined (WIFI_BOARD_FOC_HUB)
		// Don't need to do the stuff below
	#else 
		AD1CON1 = 0x84E4;			// Turn on, auto sample start, auto-convert, 12 bit mode (on parts with a 12bit A/D)
		AD1CON2 = 0x0404;			// AVdd, AVss, int every 2 conversions, MUXA only, scan
		AD1CON3 = 0x1003;			// 16 Tad auto-sample, Tad = 3*Tcy
		#if defined(__32MX460F512L__) || defined(__32MX795F512L__)	// PIC32MX460F512L and PIC32MX795F512L PIMs has different pinout to accomodate USB module
			AD1CSSL = 1<<2;				// Scan pot
		#else
			AD1CSSL = 1<<5;				// Scan pot
		#endif
	#endif

	// UART
	#if defined(STACK_USE_UART)
		UARTTX_TRIS = 0;
		UARTRX_TRIS = 1;
		UMODE = 0x8000;			// Set UARTEN.  Note: this must be done before setting UTXEN

		#if defined(__C30__)
			USTA = 0x0400;		// UTXEN set
			#define CLOSEST_UBRG_VALUE ((GetPeripheralClock()+8ul*BAUD_RATE)/16/BAUD_RATE-1)
			#define BAUD_ACTUAL (GetPeripheralClock()/16/(CLOSEST_UBRG_VALUE+1))
		#else	//defined(__C32__)
			USTA = 0x00001400;		// RXEN set, TXEN set
			#define CLOSEST_UBRG_VALUE ((GetPeripheralClock()+8ul*BAUD_RATE)/16/BAUD_RATE-1)
			#define BAUD_ACTUAL (GetPeripheralClock()/16/(CLOSEST_UBRG_VALUE+1))
		#endif
	
		#define BAUD_ERROR ((BAUD_ACTUAL > BAUD_RATE) ? BAUD_ACTUAL-BAUD_RATE : BAUD_RATE-BAUD_ACTUAL)
		#define BAUD_ERROR_PRECENT	((BAUD_ERROR*100+BAUD_RATE/2)/BAUD_RATE)
		#if (BAUD_ERROR_PRECENT > 3)
			#warning UART frequency error is worse than 3%
		#elif (BAUD_ERROR_PRECENT > 2)
			#warning UART frequency error is worse than 2%
		#endif
	
		UBRG = CLOSEST_UBRG_VALUE;
	#endif

#endif

// Deassert all chip select lines so there isn't any problem with 
// initialization order.  Ex: When ENC28J60 is on SPI2 with Explorer 16, 
// MAX3232 ROUT2 pin will drive RF12/U2CTS ENC28J60 CS line asserted, 
// preventing proper 25LC256 EEPROM operation.
#if defined(ENC_CS_TRIS)
	ENC_CS_IO = 1;
	ENC_CS_TRIS = 0;
#endif
#if defined(ENC100_CS_TRIS)
	ENC100_CS_IO = (ENC100_INTERFACE_MODE == 0);
	ENC100_CS_TRIS = 0;
#endif
#if defined(EEPROM_CS_TRIS)
	EEPROM_CS_IO = 1;
	EEPROM_CS_TRIS = 0;
#endif
#if defined(SPIRAM_CS_TRIS)
	SPIRAM_CS_IO = 1;
	SPIRAM_CS_TRIS = 0;
#endif
#if defined(SPIFLASH_CS_TRIS)
	SPIFLASH_CS_IO = 1;
	SPIFLASH_CS_TRIS = 0;
#endif
#if defined(WF_CS_TRIS)
	WF_CS_IO = 1;
	WF_CS_TRIS = 0;
#endif

#if defined (WIFI_BOARD_FOC_HUB)
	// Inputs (WIFI/EE) on SPI1
	_SDI1R = 8;	// SDI1 = RP8
	_INT1R = 7;	// Assign RB7/RP7 to INT1 (input) for MRF24WB0M Wi-Fi PICtail Plus interrupt
	
	// Inputs (MOTHER) on SPI2
	_SDI2R = 12;	// SDI2 = RP12
	_SCK2R = 11;	// SCK2 = RP11 - clock is input because this is the slave
	_SS2R = 13;		// SS2 = RP13  - set slave select pin.		
	
	// Outputs (WIFI/EEP) on SPI1
	_RP6R = 8; 		// RP6 = SCK1
	_RP5R = 7;		// RP5 = SDO1
	
	// Outputs (MOTHER) on SPI2
	_RP10R = 10;	// RP10 = SDO2
	
#endif

#if defined(PIC24FJ64GA004_PIM)
	__builtin_write_OSCCONL(OSCCON & 0xBF);  // Unlock PPS

	// Remove some LED outputs to regain other functions
	LED1_TRIS = 1;		// Multiplexed with BUTTON0
	LED5_TRIS = 1;		// Multiplexed with EEPROM CS
	LED7_TRIS = 1;		// Multiplexed with BUTTON1
	
	// Inputs
	RPINR19bits.U2RXR = 19;			//U2RX = RP19
	RPINR22bits.SDI2R = 20;			//SDI2 = RP20
	RPINR20bits.SDI1R = 17;			//SDI1 = RP17
	
	// Outputs
	RPOR12bits.RP25R = U2TX_IO;		//RP25 = U2TX  
	RPOR12bits.RP24R = SCK2OUT_IO; 	//RP24 = SCK2
	RPOR10bits.RP21R = SDO2_IO;		//RP21 = SDO2
	RPOR7bits.RP15R = SCK1OUT_IO; 	//RP15 = SCK1
	RPOR8bits.RP16R = SDO1_IO;		//RP16 = SDO1
	
	AD1PCFG = 0xFFFF;				//All digital inputs - POT and Temp are on same pin as SDO1/SDI1, which is needed for ENC28J60 commnications

	__builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(__PIC24FJ256DA210__)
	__builtin_write_OSCCONL(OSCCON & 0xBF);  // Unlock PPS

	// Inputs
	RPINR19bits.U2RXR = 11;	// U2RX = RP11
	RPINR20bits.SDI1R = 0;	// SDI1 = RP0
	RPINR0bits.INT1R = 34;	// Assign RE9/RPI34 to INT1 (input) for MRF24WB0M Wi-Fi PICtail Plus interrupt
	
	// Outputs
	RPOR8bits.RP16R = 5;	// RP16 = U2TX
	RPOR1bits.RP2R = 8; 	// RP2 = SCK1
	RPOR0bits.RP1R = 7;		// RP1 = SDO1

	__builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(__PIC24FJ256GB110__) || defined(__PIC24FJ256GB210__)
	__builtin_write_OSCCONL(OSCCON & 0xBF);  // Unlock PPS
	
	// Configure SPI1 PPS pins (ENC28J60/ENCX24J600/MRF24WB0M or other PICtail Plus cards)
	RPOR0bits.RP0R = 8;		// Assign RP0 to SCK1 (output)
	RPOR7bits.RP15R = 7;	// Assign RP15 to SDO1 (output)
	RPINR20bits.SDI1R = 23;	// Assign RP23 to SDI1 (input)

	// Configure SPI2 PPS pins (25LC256 EEPROM on Explorer 16)
	RPOR10bits.RP21R = 11;	// Assign RG6/RP21 to SCK2 (output)
	RPOR9bits.RP19R = 10;	// Assign RG8/RP19 to SDO2 (output)
	RPINR22bits.SDI2R = 26;	// Assign RG7/RP26 to SDI2 (input)
	
	// Configure UART2 PPS pins (MAX3232 on Explorer 16)
	#if !defined(ENC100_INTERFACE_MODE) || (ENC100_INTERFACE_MODE == 0) || defined(ENC100_PSP_USE_INDIRECT_RAM_ADDRESSING)
	RPINR19bits.U2RXR = 10;	// Assign RF4/RP10 to U2RX (input)
	RPOR8bits.RP17R = 5;	// Assign RF5/RP17 to U2TX (output)
	#endif
	
	// Configure INT1 PPS pin (MRF24WB0M Wi-Fi PICtail Plus interrupt signal when in SPI slot 1)
	RPINR0bits.INT1R = 33;	// Assign RE8/RPI33 to INT1 (input)

	// Configure INT3 PPS pin (MRF24WB0M Wi-Fi PICtail Plus interrupt signal when in SPI slot 2)
	RPINR1bits.INT3R = 40;	// Assign RC3/RPI40 to INT3 (input)

	__builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(__PIC24FJ256GA110__)
	__builtin_write_OSCCONL(OSCCON & 0xBF);  // Unlock PPS
	
	// Configure SPI2 PPS pins (25LC256 EEPROM on Explorer 16 and ENC28J60/ENCX24J600/MRF24WB0M or other PICtail Plus cards)
	// Note that the ENC28J60/ENCX24J600/MRF24WB0M PICtails SPI PICtails must be inserted into the middle SPI2 socket, not the topmost SPI1 slot as normal.  This is because PIC24FJ256GA110 A3 silicon has an input-only RPI PPS pin in the ordinary SCK1 location.  Silicon rev A5 has this fixed, but for simplicity all demos will assume we are using SPI2.
	RPOR10bits.RP21R = 11;	// Assign RG6/RP21 to SCK2 (output)
	RPOR9bits.RP19R = 10;	// Assign RG8/RP19 to SDO2 (output)
	RPINR22bits.SDI2R = 26;	// Assign RG7/RP26 to SDI2 (input)
	
	// Configure UART2 PPS pins (MAX3232 on Explorer 16)
	RPINR19bits.U2RXR = 10;	// Assign RF4/RP10 to U2RX (input)
	RPOR8bits.RP17R = 5;	// Assign RF5/RP17 to U2TX (output)
	
	// Configure INT3 PPS pin (MRF24WB0M PICtail Plus interrupt signal)
	RPINR1bits.INT3R = 36;	// Assign RA14/RPI36 to INT3 (input)

	__builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif


#if defined(DSPICDEM11)
	// Deselect the LCD controller (PIC18F252 onboard) to ensure there is no SPI2 contention
	LCDCTRL_CS_TRIS = 0;
	LCDCTRL_CS_IO = 1;

	// Hold the codec in reset to ensure there is no SPI2 contention
	CODEC_RST_TRIS = 0;
	CODEC_RST_IO = 0;
#endif

#if defined(SPIRAM_CS_TRIS)
	SPIRAMInit();
#endif
#if defined(EEPROM_CS_TRIS)
	XEEInit();
#endif
#if defined(SPIFLASH_CS_TRIS)
	SPIFlashInit();
#endif
}
Exemple #18
0
int main(void)
{
    GOL_MSG msg;                    // GOL message structure to interact with GOL
    
    Nop();
    
    #if defined(PIC24FJ256DA210_DEV_BOARD)
    
    _ANSG8 = 0; /* S1 */
    _ANSE9 = 0; /* S2 */
    _ANSB5 = 0; /* S3 */
        
    #else
    /////////////////////////////////////////////////////////////////////////////
    // ADC Explorer 16 Development Board Errata (work around 2)
    // RB15 should be output
    /////////////////////////////////////////////////////////////////////////////
	#ifndef MULTI_MEDIA_BOARD_DM00123
    LATBbits.LATB15 = 0;
    TRISBbits.TRISB15 = 0;
    #endif
	#endif
    /////////////////////////////////////////////////////////////////////////////
    #if defined(__dsPIC33F__) || defined(__PIC24H__)

    // 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 switching 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)
    { };
    
    // Set PMD0 pin functionality to digital
    AD1PCFGL = AD1PCFGL | 0x1000;
    
    #elif defined(__PIC32MX__)
    INTEnableSystemMultiVectoredInt();
    SYSTEMConfigPerformance(GetSystemClock());
    #ifdef MULTI_MEDIA_BOARD_DM00123
    CPLDInitialize();
    CPLDSetGraphicsConfiguration(GRAPHICS_HW_CONFIG);
    CPLDSetSPIFlashConfiguration(SPI_FLASH_CHANNEL);
    #endif // #ifdef MULTI_MEDIA_BOARD_DM00123
    #endif // #if defined(__dsPIC33F__) || defined(__PIC24H__)

    GOLInit();                      // initialize graphics library &
                                    // create default style scheme for GOL

    #if defined (GFX_PICTAIL_V1) || defined (GFX_PICTAIL_V2)
    EEPROMInit();                   // initialize Exp.16 EEPROM SPI
    BeepInit();
    #else
	    #if defined (USE_SST25VF016)
            SST25Init();            // initialize GFX3 SST25 flash SPI
        #endif
    #endif
    
    TouchInit();                    // initialize touch screen
    HardwareButtonInit();           // Initialize the hardware buttons

    // create default style scheme for GOL
    TickInit();                     // initialize tick counter (for random number generation)

    // create default style scheme for GOL
    #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)

    // If S3 button on Explorer 16 board is pressed calibrate touch screen
    TRISAbits.TRISA9 = 1;
    if(PORTAbits.RA9 == 0)
    {
        TRISAbits.TRISA9 = 0;
        TouchCalibration();
        TouchStoreCalibration();
    }

    TRISAbits.TRISA9 = 0;
	#else

	    /**
	     * Force a touchscreen calibration by pressing the switch
	     * Explorer 16 + GFX PICTail    - S3 (8 bit PMP)
	     * Explorer 16 + GFX PICTail    - S5 (16 bit PMP)
	     * Starter Kit + GFX PICTail    - S0 (8 bit PMP)
	     * Multimedia Expansion Board   - Fire Button
	     * DA210 Developement Board     - S1
	     * NOTE:    Starter Kit + GFX PICTail will switches are shared
	     *          with the 16 bit PMP data bus.
	     **/
	    if(GetHWButtonTouchCal() == HW_BUTTON_PRESS)
	    {
	        TouchCalibration();
	        TouchStoreCalibration();
	    }
    #endif

    // If it's a new board (EEPROM_VERSION byte is not programed) calibrate touch screen
    #if defined (GFX_PICTAIL_V1) || defined (GFX_PICTAIL_V2)
    if(GRAPHICS_LIBRARY_VERSION != EEPROMReadWord(ADDRESS_VERSION))
    {
        TouchCalibration();
        TouchStoreCalibration();
    }

    #else
        #if defined (USE_SST25VF016)
        if(GRAPHICS_LIBRARY_VERSION != SST25ReadWord(ADDRESS_VERSION))
        {
            TouchCalibration();
            TouchStoreCalibration();
        }
        #elif defined (USE_SST39LF400)
        WORD tempArray[12], tempWord = 0x1234;

        SST39LF400Init(tempArray);
        tempWord = SST39LF400ReadWord(ADDRESS_VERSION);
        SST39LF400DeInit(tempArray);

        if(GRAPHICS_LIBRARY_VERSION != tempWord)
        {
            TouchCalibration();
            TouchStoreCalibration();
        }
        #endif
    #endif

    // Load touch screen calibration parameters from memory
    TouchLoadCalibration();

    GDDDemoCreateFirstScreen();

    while(1)
    {
        if(GOLDraw())               // Draw GOL object
        {
            TouchGetMsg(&msg);      // Get message from touch screen
			
            #if (NUM_GDD_SCREENS > 1)
			// GDD Readme:
			// The following line of code allows a GDD user to touch the touchscreen
			// to cycle through different static screens for viewing. This is useful as a
			// quick way to view how each screen looks on the physical target hardware.
			// This line of code should eventually be commented out for actual development.
			// Also note that widget/object names can be found in GDD_Screens.h
			if(msg.uiEvent == EVENT_RELEASE) GDDDemoNextScreen();
			#endif
			
            GOLMsg(&msg);           // Process message
        }
    }//end while
}
Exemple #19
0
/* Initialize UART2 module */
void uart2_init (void)
{
//	TRISBbits.TRISB9 = 0;		// PTX out, rest inputs
//	LATBbits.LATB9 = !SIG_LEVEL; 

	__builtin_write_OSCCONL(0x0);	// enable writes to RP regs
//	_IOLOCK = 0;
//	_U2RXR = 8;			/* U1RX  -- RB8  -- RP8  -- CN22 */
//	_RP9R = 5;			/* U1TX  -- RB9  -- RP9  -- CN21 */
//	_RP10R = 6;			/* U1RTS -- RB10 -- RP10 -- CN16 */
//	_U2CTSR = 11;		/* U1CTS -- RB11 -- RP11 -- CN15 */
//	_CN15PUE = 1;		// pull-up on for CTS
//
	_U2RXR = 3;			/* U2RX  -- RB3  -- RP3  -- CN7 */
	_RP2R = 5;			/* U2TX  -- RB2  -- RP2  -- CN6 */
//	_RP10R = 6;			/* U1RTS -- RB10 -- RP10 -- CN16 */
//	_U2CTSR = 11;		/* U1CTS -- RB11 -- RP11 -- CN15 */
//	_CN15PUE = 1;		// pull-up on for CTS
//
	__builtin_write_OSCCONL(0x40);	// set _IOLOCK
//	_IOLOCK = 1;

	/* Disable UART1 Tx/Rx interrupts */
	// configure U2MODE
	U2MODEbits.UARTEN = 0;	// Bit15 TX, RX DISABLED, ENABLE at end of func
	//						// Bit14
	U2MODEbits.USIDL = 0;	// Bit13 Continue in Idle
	U2MODEbits.IREN = 0;	// Bit12 No IR translation
	U2MODEbits.RTSMD = 0;	// Bit11 Simplex Mode
	//						// Bit10
	U2MODEbits.UEN = 0;		// Bits8,9 TX,RX enabled, CTS,RTS not
	U2MODEbits.WAKE = 0;	// Bit7 No Wake up (since we don't sleep here)
	U2MODEbits.LPBACK = 0;	// Bit6 No Loop Back
	U2MODEbits.ABAUD = 0;	// Bit5 No Autobaud (would require sending '55')
	U2MODEbits.URXINV = SIG_LEVEL;	// Bit4 IdleState = 1  (for dsPIC)
	U2MODEbits.BRGH = 1;	// Bit3 4 clocks per bit period
	U2MODEbits.PDSEL = 0;	// Bits1,2 8bit, No Parity
	U2MODEbits.STSEL = 0;	// Bit0 One Stop Bit

	// Load all values in for U1STA SFR
	U2STAbits.UTXISEL1 = 0;	//Bit15 Int when Char is transferred (1/2 config!)
	U2STAbits.UTXINV = SIG_LEVEL;	//Bit14 N/A, IRDA config
	U2STAbits.UTXISEL0 = 1;	//Bit13 Other half of Bit15
	//						//Bit12
	U2STAbits.UTXBRK = 0;	//Bit11 Disabled
	//U1STAbits.UTXEN = 1;	//Bit10 TX pins controlled by periph (handled below)
	//U1STAbits.UTXBF = 0;	//Bit9 *Read Only Bit*
	//U1STAbits.TRMT = 0;	//Bit8 *Read Only bit*
	U2STAbits.URXISEL = 0;	//Bits6,7 Int. on character recieved
	U2STAbits.ADDEN = 0;	//Bit5 Address Detect Disabled
	//U1STAbits.RIDLE = 0;	//Bit4 *Read Only Bit*
	//U1STAbits.PERR = 0;	//Bit3 *Read Only Bit*
	//U1STAbits.FERR = 0;	//Bit2 *Read Only Bit*
	U2STAbits.OERR = 0;		//Bit1 *Read Only Bit*
	//U1STAbits.URXDA = 0;	//Bit0 *Read Only Bit*

	_U2RXIP = 1;	// Low Range Interrupt Priority level, no urgent reason
	_U2TXIP = 1;	// Low Range Interrupt Priority level, no urgent reason

	/* Initialize UART1 */
	U2BRG = (FCY / 4 / BPS) - 1;

	_U2TXIF = 0;	// Clear the Transmit Interrupt Flag
	_U2TXIE = 0;	// Disable Transmit Interrupts
	_U2RXIF = 0;	// Clear the Recieve Interrupt Flag
	_U2RXIE = 0;	// Enable Receive Interrupts

	/* Clear Tx/Rx FIFOs */
	Tx2Fifo.ri = 0; Tx2Fifo.wi = 0; Tx2Fifo.ct = 0;
	Rx2Fifo.ri = 0; Rx2Fifo.wi = 0; Rx2Fifo.ct = 0;
	Tx2Run = 0;

	U2MODEbits.UARTEN = 1;	// And turn the peripheral on
	U2STAbits.UTXEN = 1;

	/* Enable UART Tx/Rx interruptrs */
	_U2RXIE = 1;
	_U2TXIE = 1;
}
int main (void)
{
   FSFILE * pointer;
   #if defined(SUPPORT_LFN)
   char count = 80;
   #endif
   char * pointer2;
   SearchRec rec;
   unsigned char attributes;
   unsigned char size = 0, i;

    // Initialize and configure Primary PLL, and enabled Secondary Oscillator
    PLLFBD = 58;			/* M  = 60	*/
    CLKDIVbits.PLLPOST = 0;	/* N1 = 2	*/
    CLKDIVbits.PLLPRE = 0;	/* N2 = 2	*/
    OSCTUN = 0;
    __builtin_write_OSCCONH(0x03);		
    __builtin_write_OSCCONL(0x03);
    while (OSCCONbits.COSC != 0x3); 
    while (_LOCK == 0);

   // Activate the RTCC module
   __builtin_write_RTCWEN();
   Nop();
   Nop();
   RCFGCALbits.RTCPTR0 = 1;
   RCFGCALbits.RTCPTR1 = 1;
   
   // Set it to the correct time
   // These values won't be accurate
   RTCVAL = 0x0011;   
   RTCVAL = 0x0815;
   RTCVAL = 0x0108;
   RTCVAL = 0x2137;
   RCFGCAL = 0x8000;

   while (!MDD_MediaDetect());

   // Initialize the library
   while (!FSInit());

#ifdef ALLOW_WRITES
   // Create a file
   pointer = FSfopen ("FILE1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write 21 1-byte objects from sendBuffer into the file
   if (FSfwrite (sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // FSftell returns the file's current position
   if (FSftell (pointer) != 21)
      while(1);

   // FSfseek sets the position one byte before the end
   // It can also set the position of a file forward from the
   // beginning or forward from the current position
   if (FSfseek(pointer, 1, SEEK_END))
      while(1);

   // Write a 2 at the end of the string
   if (FSfwrite (send2, 1, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create a second file
   pointer = FSfopen ("Microchip File 1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write the string to it again
   if (FSfwrite ((void *)sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);
#endif

   // Open file 1 in read mode
   pointer = FSfopen ("FILE1.TXT", "r");
   if (pointer == NULL)
      while(1);

   if (FSrename ("Microchip File 2.TXT", pointer))
      while(1);

   // Read one four-byte object
   if (FSfread (receiveBuffer, 4, 1, pointer) != 1)
      while(1);

   // Check if this is the end of the file- it shouldn't be
   if (FSfeof (pointer))
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Make sure we read correctly
   if ((receiveBuffer[0] != 'T') ||
         (receiveBuffer[1] != 'h')  ||
         (receiveBuffer[2] != 'i')  ||
         (receiveBuffer[3] != 's'))
   {
      while(1);
   }

#ifdef ALLOW_DIRS
   // Create a small directory tree
   // Beginning the path string with a '.' will create the tree in
   // the current directory.  Beginning with a '..' would create the
   // tree in the previous directory.  Beginning with just a '\' would
   // create the tree in the root directory.  Beginning with a dir name
   // would also create the tree in the current directory
   if (FSmkdir (".\\Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Change to 'Directory 3' in our new tree
   if (FSchdir ("Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Create another tree in 'Directory 3'
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 6"))
      while(1);

   // Create a third file in directory THREE
   pointer = FSfopen ("CWD.TXT", "w");
   if (pointer == NULL)
      while(1);

   #if defined(SUPPORT_LFN)
   // Get the name of the current working directory
   /* it should be "\Mchp Directory 1\Dir2\Directory 3" */
   pointer2 = wFSgetcwd ((unsigned short int *)path1, count);
   #endif

   if (pointer2 != path1)
      while(1);

   // Simple string length calculation
   i = 0;
   while(*((unsigned short int *)path1 + i) != 0x00)
   {
      size++;
      size++;
      i++;
   }
   // Write the name to CWD.TXT
   if (FSfwrite (path1, size, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create some more directories
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 7\\..\\Directory 8\\..\\..\\DIRNINE\\Directory 10\\..\\Directory 11\\..\\Directory 12"))
      while(1);

   /*******************************************************************
      Now our tree looks like this

 \ -> Mchp Directory 1 -> Dir2 -> Directory 3 -> Directory 4 -> Directory 5 -> Directory 6
                                                                                 -> Directory 7
                                                                                 -> Directory 8

                                                                    DIRNINE -> Directory 10
                                                                            -> Directory 11
                                                                            -> Directory 12
   ********************************************************************/

   // This will delete only Directory 8
   // If we tried to delete Directory 5 with this call, the FSrmdir
   // function would return -1, since Directory 5 is non-empty
   if (FSrmdir ("\\Mchp Directory 1\\Dir2\\Directory 3\\Directory 4\\Directory 5\\Directory 8", FALSE))
      while(1);

   // This will delete DIRNINE and all three of its sub-directories
   if (FSrmdir ("Directory 4\\DIRNINE", TRUE))
      while(1);

   // Change directory to the root dir
   if (FSchdir ("\\"))
      while(1);
#endif

#ifdef ALLOW_FILESEARCH
   // Set attributes
   attributes = ATTR_ARCHIVE | ATTR_READ_ONLY | ATTR_HIDDEN;

   // Functions "FindFirst" & "FindNext" can be used to find files
   // and directories with required attributes in the current working directory.

   // Find the first TXT file with any (or none) of those attributes that
   // has a name beginning with the letters "Mic"
   // These functions are more useful for finding out which files are
   // in your current working directory
   if (FindFirst ("Mic*.TXT", attributes, &rec))
      while(1);

 //   Find file to get "Microchip File 2.TXT"
      if (FindNext (&rec))
         while(1);

   #if defined(SUPPORT_LFN) 
  // Delete file 2
   // If the file name is long
   if(rec.utf16LFNfoundLength)
   {
      // NOTE : "wFSremove" function deletes specific file not directory.
      //        To delete directories use "wFSrmdir" function
      if (wFSremove (rec.utf16LFNfound))
         while(1);
   }
   else
   #endif
   {
      // NOTE : "FSremove" function deletes specific file not directory.
      //        To delete directories use "FSrmdir" function
      if (FSremove (rec.filename))
         while(1);
   }

#endif


/*********************************************************************
   The final contents of our card should look like this:
   \ -> Microchip File 1.TXT
      -> Mchp Directory 1 -> Dir2 -> Directory 3 -> CWD.TXT
                                                 -> Directory 4 -> Directory 5 -> Directory 6
                                                                               -> Directory 7

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


   while(1);
}
Exemple #21
0
BOOL InitializeSystem ( void )
{
    #if defined(__dsPIC33EP512MU810__)||defined(__PIC24EP512GU810__)

    // Configure the device PLL to obtain 60 MIPS operation. The crystal
    // frequency is 8MHz. Divide 8MHz by 2, multiply by 60 and divide by
    // 2. This results in Fosc of 120MHz. The CPU clock frequency is
    // Fcy = Fosc/2 = 60MHz. Wait for the Primary PLL to lock and then
    // configure the auxilliary PLL to provide 48MHz needed for USB 
    // Operation.

    PLLFBD = 38;				/* M  = 60	*/
    CLKDIVbits.PLLPOST = 0;		/* N1 = 2	*/
    CLKDIVbits.PLLPRE = 0;		/* N2 = 2	*/
    OSCTUN = 0;			

    /*	Initiate Clock Switch to Primary
     *	Oscillator with PLL (NOSC= 0x3)*/

    __builtin_write_OSCCONH(0x03);		
    __builtin_write_OSCCONL(0x01);

    while (OSCCONbits.COSC != 0x3);       

        // Configuring the auxiliary PLL, since the primary
        // oscillator provides the source clock to the auxiliary
        // PLL, the auxiliary oscillator is disabled. Note that
        // the AUX PLL is enabled. The input 8MHz clock is divided
        // by 2, multiplied by 24 and then divided by 2. Wait till 
        // the AUX PLL locks.

        ACLKCON3 = 0x24C1;   
        ACLKDIV3 = 0x7;

        ACLKCON3bits.ENAPLL = 1;
        while(ACLKCON3bits.APLLCK != 1); 

        ANSELA = 0x0000;
        ANSELB = 0x0000;
        ANSELC = 0x0000;
        ANSELD = 0x0000;
        ANSELE = 0x0000;
        ANSELG = 0x0000;

        // The dsPIC33EP512MU810 features Peripheral Pin
        // select. The following statements map UART2 to 
        // device pins which would connect to the the 
        // RX232 transciever on the Explorer 16 board.

        RPINR19 = 0;
        RPINR19 = 0x64;
        RPOR9bits.RP101R = 0x3;

#endif
    
    #if defined( __PIC24FJ256GB110__ )
        // Configure U2RX - put on pin 49 (RP10)
        RPINR19bits.U2RXR = 10;

        // Configure U2TX - put on pin 50 (RP17)
        RPOR8bits.RP17R = 5;

        OSCCON = 0x3302;    // Enable secondary oscillator
        CLKDIV = 0x0000;    // Set PLL prescaler (1:1)

        TRISA = 0x0000;
        TRISD = 0x00C0;

   #elif defined(__PIC24FJ64GB004__)
	//On the PIC24FJ64GB004 Family of USB microcontrollers, the PLL will not power up and be enabled
	//by default, even if a PLL enabled oscillator configuration is selected (such as HS+PLL).
	//This allows the device to power up at a lower initial operating frequency, which can be
	//advantageous when powered from a source which is not gauranteed to be adequate for 32MHz
	//operation.  On these devices, user firmware needs to manually set the CLKDIV<PLLEN> bit to
	//power up the PLL.
    {
        unsigned int pll_startup_counter = 600;
        CLKDIVbits.PLLEN = 1;
        while(pll_startup_counter--);
    }

    #elif defined(__PIC32MX__)
        {
            int  value;
    
            value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() );
    
            // Enable the cache for the best performance
            CheKseg0CacheOn();
    
            INTEnableSystemMultiVectoredInt();
    
            value = OSCCON;
            while (!(value & 0x00000020))
            {
                value = OSCCON;    // Wait for PLL lock to stabilize
            }
        }
    #endif

    // Init LCD
    LCDInit();

    // Init LEDs
    mInitAllLEDs();
    mLED_9_Off();
    mLED_10_Off();

    // Init Switches
    //mInitAllSwitches();
    SwitchState = IOPORT_BIT_6|IOPORT_BIT_7;

    // Init UART
    UART2Init();

    // Set Default demo state
    DemoState = DEMO_INITIALIZE;

    return TRUE;
} // InitializeSystem
/******************************************************************************
* Function:     main(void)
*
* Output:		None
*
* Overview:		Main function used to init the ADC, PWM and TIMER2 modules. 
*				It also inits the global variables used in the interrupts and 
*				PI controller.
*				The main task executed here is to start and stop the motor 
*				as well as setting the ramp-up initial parameters to 
*				spin the motor
*
* Note:			None
*******************************************************************************/
int main(void)
{

	// Configure Oscillator to operate the device at 30Mhz
	// Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
	// Fosc= 7.37*32/(2*2)= 58.96Mhz for 7.37 input clock
	/****************** Clock definitions *********************************/
	PLLFBD=30;					// M=32
	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(0x01);		// Initiate Clock Switch to
										// FRC with PLL (NOSC=0b001)
	__builtin_write_OSCCONL(0x01);		// Start clock switching
	while (OSCCONbits.COSC != 0b001);	// Wait for Clock switch to occur

	// Wait for PLL to lock
	while(OSCCONbits.LOCK!=1) {};
		   
	/****************** PID init **************************************/	
#ifdef CLOSELOOPMODE
	ReferenceSpeed = (MIN_DUTY_CYCLE*2)/3;								
	
	// load the PID gain coeffecients into an array;
	PIDGainCoefficients[0] = SpeedControl_P;
	PIDGainCoefficients[1] = SpeedControl_I;
	PIDGainCoefficients[2] = SpeedControl_D;				

	// Initialize the PIDStructure variable before calculation the K1, K2, and K3 terms	
	PIDStructure.abcCoefficients = abcCoefficients;	
	PIDStructure.controlHistory = controlHistory;
	PIDCoeffCalc(PIDGainCoefficients, &PIDStructure);
	// initialize control history
	PIDInit(&PIDStructure);
	PIDStructure.controlOutput = MIN_DUTY_CYCLE;
	/****************************************************************/							
#endif	
	
	/****************** I/O port Init *********************************/
	/* Configuring Digital PORTS multiplexed with PWMs as outputs*/
	LATBbits.LATB10 = 0;	//PWM1H3
	TRISBbits.TRISB10 = 0;
	LATBbits.LATB11 = 0;	//PWM1L3
	TRISBbits.TRISB11 = 0;
	LATBbits.LATB12 = 0;	//PWM1H2
	TRISBbits.TRISB12 = 0;
	LATBbits.LATB13 = 0;	//PWM1L2
	TRISBbits.TRISB13 = 0;	
	LATBbits.LATB14 = 0;	//PWM1H1
	TRISBbits.TRISB14 = 0;	
	LATBbits.LATB15 = 0;	//PWM1L1
	TRISBbits.TRISB15 = 0;	

	/*Push Buttons ports*/
	LATBbits.LATB4 = 0;
	TRISBbits.TRISB4 = 1;
	LATAbits.LATA8 = 0;
	TRISAbits.TRISA8 = 1;
	
	/****************** Functions init *********************************/
	INTCON1bits.NSTDIS = 0;		    // Enabling nested interrupts	
	InitMCPWM();					//Configuring MC PWM module
	InitADC10();					//Configuring ADC
	InitTMR2();						//Configuring TIMER 3, used to measure speed
	InitTMR1();						//Configuring TIMER 1, used for the commutation delay

	Flags.RotorAlignment = 0;		// TURN OFF RAMP UP
	Flags.RunMotor = 0;				// indication the run motor condition
	
	/****************** Infinite Loop *********************************/
	for(;;)
		{	

		while (!S3);					// wait for S3 button to be hit
		while (S3)						// wait till button is released
			DelayNmSec(DEBOUNCE_DELAY);
		
		T2CONbits.TON = 1;				// Start TIMER , enabling speed measurement
		PWM1CON1 = 0x0777;				// enable PWM outputs
			
		/*ROTOR ALIGNMENT SEQUENCE*/
		Flags.RotorAlignment = 1;		// TURN ON rotor alignment sequence
		Flags.RunMotor = 1;				// Indicating that motor is running
		CurrentPWMDutyCycle = MIN_DUTY_CYCLE;	//Init PWM values
		DesiredPWMDutyCycle = MIN_DUTY_CYCLE;	//Init PWM values
		PWMticks = 0;					//Init Rotor aligment counter
		
		/************* Rotor alignment sequence and ramp-up sequence ************/
		for(RampUpCommState=1;RampUpCommState<7;RampUpCommState++)
			{
            
			while(++PWMticks<MAX_PWM_TICKS)
				P1OVDCON=PWM_STATE[RampUpCommState];
			PWMticks = 0;				
			}   
		Flags.RotorAlignment = 0;		// TURN OFF rotor alignment sequence
		PWMticks = MAX_PWM_TICKS+1;		// RAMP UP for breaking the motor IDLE state
		DelayNmSec(RAM_UP_DELAY);		// RAMP UP DELAY
                Sub_timer=Sub_timer++;
		/****************** Motor is running *********************************/
		while(Flags.RunMotor)			// while motor is running
			{
 
		/****************** Stop Motor *********************************/
                    


			//if (S3)							// if S3 is pressed
				//{
                    Sub_timer=0;                        // Musses
                    while ( Sub_timer=Sub_timer++<=600) // Musses
				//while (S3)					// wait for key release
					DelayNmSec(DEBOUNCE_DELAY);		
		
				PWM1CON1 = 0x0700;			// disable PWM outputs
  			    P1OVDCON = 0x0000;			// override PWM low.
				Flags.RotorAlignment = 0;	// turn on RAMP UP
				Flags.RunMotor = 0;			// reset run flag
				CurrentPWMDutyCycle = 1;	// Set PWM to the min value
				
				//Initi speed measurement variables & timer
				T2CONbits.TON = 0;	// Stop TIMER2
				TMR2 = 0;			//Clear TIMER2 register
				Timer2Value = 0;
				Timer2Average = 0;

#ifdef CLOSELOOPMODE					
				//Init PI controller variables
				DesiredSpeed = (int)((ReferenceSpeed*3)/2);
				CurrentSpeed = 0;

				// load the PID gain coeffecients into an array;
				PIDGainCoefficients[0] = SpeedControl_P;
				PIDGainCoefficients[1] = SpeedControl_I;
				PIDGainCoefficients[2] = SpeedControl_D;				

				// Initialize the PIDStructure variable before calculation the K1, K2, and K3 terms	
				PIDStructure.abcCoefficients = abcCoefficients;	
				PIDStructure.controlHistory = controlHistory;
				PIDCoeffCalc(PIDGainCoefficients, &PIDStructure);
				// initialize control history
				PIDInit(&PIDStructure);
				PIDStructure.controlOutput = MIN_DUTY_CYCLE;
#endif
								
               // }
			}//end of motor running loop
		}//end of infinite loop

 return 0;
}//end of main function
Exemple #23
0
void system_Init(void){
    //    CLKDIVbits.RCDIV = 1;
    AD1PCFGL = 0xFFFF; // all as digital
    TRISB = ~(0b0100000011110101);  // diody
    TRISFbits.TRISF5 = 0;   // triac kierunek wyjsciowy
    // Unlock Registers
    __builtin_write_OSCCONL(OSCCON & 0xBF);     // page 140 in datasheet
    //////     INT1    //////
    RPINR0bits.INT1R = 24;  // RP24
    INTCON2bits.INT1EP = 1;
    IPC5bits.INT1IP = 3;
    IFS1bits.INT1IF = 0;
    IEC1bits.INT1IE = 1;
#ifndef DEBUG__
    //////     INT2    //////
    RPINR1bits.INT2R = 1;   // RP1
    INTCON2bits.INT2EP = 1;
    IPC7bits.INT2IP = 3;
    IFS1bits.INT2IF = 0;
    IEC1bits.INT2IE = 1;
#endif
    //////     INT3    //////
    RPINR1bits.INT3R = 29;  // RP29
    INTCON2bits.INT3EP = 1; // negative edge
    IPC13bits.INT3IP = 3;
    IFS3bits.INT3IF = 0;
//    INTCON1bits.NSTDIS = 1;
    IEC3bits.INT3IE = 1;    // enable
    //////     INT4    //////
    RPINR2bits.INT4R = 10;  // RP10
    INTCON2bits.INT4EP = 0; // positive edge
    IEC3bits.INT4IE = 1;
    //////////////////////////

    //////     TIMER 2/3    //////
    T2CONbits.T32 = 1;      // 32 bits mode
    T2CONbits.TCKPS = 0;    // prescaler 1:1
    T2CONbits.TCS = 0; //TCS = 0/1 taktowanie wewn?trzne/zewn?trzne
    T2CONbits.TGATE = 0; //TGATE = 0/1 Gated Time Accumulation Mode wy??czony/w??czony
    PR3 = 0x00;   // przerwanie co 50 us
    PR2 = 0x320;
    IEC0bits.T3IE = 1; //w??cz przerwanie
    IFS0bits.T3IF = 0; //wyczy?? flag? przerwania
    T2CONbits.TON = 1;
    ///////////////////////////////

    ////////    Timer 1    ////////
    T1CONbits.TCKPS = 1;    // preskaler 1:8
    T1CONbits.TCS = 0;      // taktowanie wewnetrzne
    T1CONbits.TGATE = 0;    // gated disable
    IEC0bits.T1IE = 0;      // wylacz przerwanie
    IFS0bits.T1IF = 0;      // wyczysc flage
    T1CONbits.TON = 1;      // wlacz zliczanie
    //////// Input Capture ////////
    RPINR7bits.IC1R = 16;       // RP16
    IC1CON2bits.SYNCSEL = 0;    // no synchronization
    IC1CON1bits.ICM = 1;        // capture every edge
    IC1CON1bits.ICTSEL = 4;     // Timer1 as select timer
    IC1CON2bits.SYNCSEL = 0;   // synchronization ICP1
    IC1CON2bits.ICTRIG = 1;
    IC1CON2bits.TRIGSTAT = 1;
    IEC0bits.IC1IE = 1;         // turn on interrupt
    IFS0bits.IC1IF = 0;
    /////////// UART1 ///////////
    RPINR18bits.U1RXR = 8;      // RP8 as RX
    RPOR4bits.RP9R = 3;         // RP9 as TX
    U1BRG = 51;                 // Baud rate 19200
    U1STAbits.UTXISEL0 = 0;     // the UxTXIF is set when a character is transferred from the transmit
                                // buffer to the Transmit Shift register (UxTSR). This implies at
    U1STAbits.UTXISEL1 = 0;     // least one location is empty in the transmit buffer.
    U1STAbits.URXISEL = 0;
    IFS0bits.U1RXIF = 0;
    IFS0bits.U1TXIF = 0;
    IEC0bits.U1RXIE = 1;
    IEC0bits.U1TXIE = 1;
    U1MODEbits.UARTEN = 1;
    U1STAbits.UTXEN = 1;
    // Lock Registers
    __builtin_write_OSCCONL(OSCCON | 0x40);// page 140 in datasheet
}
Exemple #24
0
    int main(void)
{
    SHORT       width, height;	// variables to store the height and width of the 16-bit bitmap image
    SHORT       counter;		// loop control variable for each shape that controls how many shapes are printed and their scale
    SHORT  		triangle[] = {160,120,160,120,160,120,160,120};		// triangle polygon points (start triangle in center of LCD)
    
    #if defined(__dsPIC33F__) || defined(__PIC24H__)

    // 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 switching 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)
    { };
    #elif defined(__PIC32MX__)
    INTEnableSystemMultiVectoredInt();
    SYSTEMConfigPerformance(GetSystemClock());
    #ifdef MULTI_MEDIA_BOARD_DM00123
    CPLDInitialize();
    CPLDSetGraphicsConfiguration(GRAPHICS_HW_CONFIG);
    CPLDSetSPIFlashConfiguration(SPI_FLASH_CHANNEL);
    #endif
    #endif

    #if defined (PIC24FJ256DA210_DEV_BOARD)
    
    // _ANSG8 = 0; /* S1 */
    // _ANSE9 = 0; /* S2 */
    // _ANSB5 = 0; /* S3 */
        
    #else

    /////////////////////////////////////////////////////////////////////////////
    // ADC Explorer 16 Development Board Errata (work around 2)
    // RB15 should be output
    /////////////////////////////////////////////////////////////////////////////
    LATBbits.LATB15 = 0;
    TRISBbits.TRISB15 = 0;

    #endif

    /////////////////////////////////////////////////////////////////////////////
    #if defined(__dsPIC33FJ128GP804__) || defined(__PIC24HJ128GP504__)
    AD1PCFGL = 0xffff;
    #endif
    InitGraph();

    while(1)
    {
	    /* Display the Kettering Logo bit image with the Welcome to the ECE in the center 
	    /* The image was taken from a JPEG and converted to a 16-bit bitmap in order to meet 
	    /* the display requirement of 16-bits per pixel. This can be done by resaving the
	    /* JPEG as 16-bit bitmap in a image editing program and then converting it using
	    /* the graphics library resource converter. The LCD only supports 4-bit, 8-bit, and
	    /* 16-bits per pixel images 
	    */
	    width = GetImageWidth((void *) &kulogo);
		SetFont((void *) &Font25);
	    WAIT_UNTIL_FINISH(PutImage(45, 20 , (void *) &kulogo,  1)); // image location is relative to the top left corner of the image
        SetColor(WHITE);
        Bar(45, 110, width + 45, 135);	// Draw a bar over the image to place the text over.
        SetColor(BLUE);
        OutTextXY(65, 110, "WELCOME TO THE ECE");
        
        DelayMs(DEMODELAY);	// delay for 1 sec and clear the screen
        SetColor(BLACK);
        ClearDevice();

		/* Display multiple circles, starting at the center and increasing in size at 
        /* each draw until the LCD borders are met. Increasing the counter value will 
        /* expand the shape size more quickly. */
        for(counter = 0; counter < MIN(GetMaxX(), GetMaxY()) >> 1; counter += 14)
        {
	        SetColor(BLACK);	// refresh the screen
	        ClearDevice();	
	        SetColor(BRIGHTRED);
	        SetFont((void *) &Font25);		// draw the name of the shape in the center
	        OutTextXY(135, 110, "Circle");
            WAIT_UNTIL_FINISH(Circle(GetMaxX() >> 1, GetMaxY() >> 1, counter + 5));	// draw the shape
            DelayMs(50);	// display for 50 ms
        }

        DelayMs(DEMODELAY);	// delay for 1 sec and clear the screen
        SetColor(BLACK);
        ClearDevice();

		/* Display multiple rectangles, starting at the center and increasing in size at 
        /* each draw until the LCD borders are met. Increasing the counter value will 
        /* expand the shape size more quickly. */
        for(counter = 0; counter < MIN(GetMaxX() / 2, GetMaxY() / 2) >> 1; counter += 5)
        {	
	        SetColor(BLACK);	// refresh the screen
	        ClearDevice();	
	        SetColor(BRIGHTBLUE);
	        OutTextXY(120, 110, "Rectangle");	// draw the name of the shape in the center
            WAIT_UNTIL_FINISH
            (
                Rectangle
                    (
                        GetMaxX() / 2 - counter * 3 + 6,	// x value of top left corner of rectangle
                        GetMaxY() / 2 - counter * 2 - 8,	// y value of top left corner of rectangle
                        GetMaxX() / 2 + counter * 3 - 6,	// x value of bottom right corner of rectangle
                        GetMaxY() / 2 + counter * 2 + 8     // y value of bottom right corner of rectangle        
                    )
            );
            DelayMs(20); // Display for 20 ms
            
        }

        DelayMs(DEMODELAY); // delay for 1 sec and clear the screen
        SetColor(BLACK);
        ClearDevice();
        
        /* Display multiple triangles, starting at the center and increasing in size at 
        /* each draw until the LCD borders are met. Increasing the counter value will 
        /* expand the shape size more quickly. */
        int i;
		for(counter = 0; counter < MIN(GetMaxX() / 2, GetMaxY() / 2) >> 1; counter += 10)
		{
			SetColor(BLACK);	// refresh the screen
			ClearDevice();
			SetColor(GREEN);	// draw the name of the shape at the center
			OutTextXY(125, 110, "Triangle");
			
			//{160,120,160,120,160,120,160,120} start in center of screen
			triangle[1] = triangle[1] - counter * 2 - 20; 	 // top point y
			triangle[7] = triangle[1];				 		 // top point y (close triangle)
			triangle[2] = triangle[2] - counter * 2 - 58; 	 // left corner point x
			triangle[3] = triangle[3] + counter * 2 + 16;	 // left corner point y
			triangle[4] = triangle[4] + counter * 2 + 58; 	 // right corner point x
			triangle[5] = triangle[5] + counter * 2 + 16;	 // right corner point y
			
			DrawPoly(4, triangle);	// draw the triangle (4 points to enclose it)
			
			// reset each of the triangle points to the center to prevent over expansion
			for (i = 0; i < 8; i++)
				if (i % 2 == 0)
					triangle[i] = 160;
				else
					triangle[i] = 120;
				
			DelayMs(50);	// display for 50 ms
		}
		
       
		DelayMs(DEMODELAY); // delay for 1 sec and clear the screen
    	SetColor(BLACK);
    	ClearDevice();
        
    }
}
/*------------------MAIN FUNCTION------------------*/
int main(void)
{  
    __builtin_write_OSCCONL(2); // Enable secondary oscillator with unlock sequence
    T1CON = 0x8012; // Enable T1 from external oscillator (SECONDARY), pre-scaler of 8)
    T2CON = 0x8000;
    PR1 = 410;      // this value generates an interrupt every 100 milliseconds (Primary)

    /*------------------CONFIGURE INTERRUPTS------------------*/
    INTCON2bits.INT0EP = 0;     // interrupt on positive edge
    INTCON2bits.ALTIVT = 0;     // use primary IVT
    IPC0bits.T1IP = 4;          // set priority level to 4 (100)
    IFS0bits.T1IF = 0;          // initialize T1 flag to zero
    IEC0bits.T1IE = 1;          // enable the T1 timer interrupt source
    
    TRISBbits.TRISB2 = 0; // Used as Register Select for LCD
    initPMP();
    initLCD();
    
    setLCDG(0);
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b00000);
    putLCD(0b00100);
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b01110);
    putLCD(0);
    
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b00000);
    putLCD(0b00100);
    putLCD(0b00000);
    putLCD(0b00000);
    putLCD(0b11111);
    putLCD(0);
    
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b00000);
    putLCD(0b00100);
    putLCD(0b00000);
    putLCD(0b01110);
    putLCD(0b10001);
    putLCD(0);

    int Buf = 0;
    initADC();
    //TRISB = 0xFF00; // configure LED port as outputs
    char BufString[20];
    char BufString2[5];
    char BufString3[16];
    double voltage, vAvg, avgTime;
    int i, time;
    unsigned long bufAvg;
    int nAvg = 100;
    TMR1 = 0;
    /*------------------INFINITE LOOP------------------*/
    while(1)
    {
        vAvg = 0;
        voltage = 0;
        bufAvg = 0;
        time = 0;
        avgTime = 0;
        for(i=0;i<nAvg;i++)
        {
            TMR2 = 0;
            Buf = getADC(0);    // read channel 1 of ADC
            time = TMR2;
            voltage = Buf*3.3/1023;
            vAvg = vAvg + voltage;
            bufAvg = bufAvg + Buf;
            avgTime = avgTime + time;
        }
        vAvg = vAvg/nAvg;
        bufAvg = bufAvg/nAvg;
        avgTime = avgTime/nAvg/16/1000;
        if(myBOOLs.timer_flag == TRUE)
        {
            setCursor(1,0);
            putsLCD("Voltage: ");
            sprintf(BufString,"%.02f",vAvg);
            sprintf(BufString2,"%lu",bufAvg);
            sprintf(BufString3,"%.05f",avgTime);
            setCursor(1,9);
            putsLCD(BufString);
            setCursor(1,16);
            putsLCD(BufString2);
            putsLCD("   ");
            setCursor(2,0);
            putsLCD("Time: ");
            setCursor(2,6);
            putsLCD(BufString3);
            setCursor(2,14);
            putsLCD("ms");
            setCursor(2,19);
            if(bufAvg > 1023*2/3)
                putLCD(0);
            if(bufAvg < 1023*2/3 && bufAvg > 1023*1/3)
                putLCD(1);
            if(bufAvg < 1023*1/3 && bufAvg > 0)
                putLCD(2);
            myBOOLs.timer_flag = FALSE;
        }
    }
    return (EXIT_SUCCESS);
}
Exemple #26
0
static void InitializeSystem(void)
{
    #if defined(__C30__) || defined __XC16__
        #if defined(__dsPIC33EP512MU810__) || defined (__PIC24EP512GU810__)
        	ANSELA = 0x0000;
    		ANSELB = 0x0000;
    		ANSELC = 0x0000;
    		ANSELD = 0x0000;
    		ANSELE = 0x0000;
    		ANSELG = 0x0000;

            // The dsPIC33EP512MU810 features Peripheral Pin
            // select. The following statements map UART2 to
            // device pins which would connect to the the
            // RX232 transciever on the Explorer 16 board.

             RPINR19 = 0;
             RPINR19 = 0x64;
             RPOR9bits.RP101R = 0x3;

        #else
            AD1PCFGL = 0xFFFF;
        #endif
    #endif

    #if defined(__dsPIC33EP512MU810__) || defined (__PIC24EP512GU810__)

    // Configure the device PLL to obtain 60 MIPS operation. The crystal
    // frequency is 8MHz. Divide 8MHz by 2, multiply by 60 and divide by
    // 2. This results in Fosc of 120MHz. The CPU clock frequency is
    // Fcy = Fosc/2 = 60MHz. Wait for the Primary PLL to lock and then
//    // configure the auxilliary PLL to provide 48MHz needed for USB
    // Operation.

	PLLFBD = 38;				/* M  = 60	*/
	CLKDIVbits.PLLPOST = 0;		/* N1 = 2	*/
	CLKDIVbits.PLLPRE = 0;		/* N2 = 2	*/
	OSCTUN = 0;

    /*	Initiate Clock Switch to Primary
     *	Oscillator with PLL (NOSC= 0x3)*/

    __builtin_write_OSCCONH(0x03);
	__builtin_write_OSCCONL(0x01);


	while (OSCCONbits.COSC != 0x3);

    // Configuring the auxiliary PLL, since the primary
    // oscillator provides the source clock to the auxiliary
    // PLL, the auxiliary oscillator is disabled. Note that
    // the AUX PLL is enabled. The input 8MHz clock is divided
    // by 2, multiplied by 24 and then divided by 2. Wait till
    // the AUX PLL locks.

    ACLKCON3 = 0x24C1;
    ACLKDIV3 = 0x7;


    ACLKCON3bits.ENAPLL = 1;
    while(ACLKCON3bits.APLLCK != 1);

    #endif

//	The USB specifications require that USB peripheral devices must never source
//	current onto the Vbus pin.  Additionally, USB peripherals should not source
//	current on D+ or D- when the host/hub is not actively powering the Vbus line.
//	When designing a self powered (as opposed to bus powered) USB peripheral
//	device, the firmware should make sure not to turn on the USB module and D+
//	or D- pull up resistor unless Vbus is actively powered.  Therefore, the
//	firmware needs some means to detect when Vbus is being powered by the host.
//	A 5V tolerant I/O pin can be connected to Vbus (through a resistor), and
// 	can be used to detect when Vbus is high (host actively powering), or low
//	(host is shut down or otherwise not supplying power).  The USB firmware
// 	can then periodically poll this I/O pin to know when it is okay to turn on
//	the USB module/D+/D- pull up resistor.  When designing a purely bus powered
//	peripheral device, it is not possible to source current on D+ or D- when the
//	host is not actively providing power on Vbus. Therefore, implementing this
//	bus sense feature is optional.  This firmware can be made to use this bus
//	sense feature by making sure "USE_USB_BUS_SENSE_IO" has been defined in the
//	HardwareProfile.h file.
    #if defined(USE_USB_BUS_SENSE_IO)
    tris_usb_bus_sense = INPUT_PIN; // See HardwareProfile.h
    #endif

//	If the host PC sends a GetStatus (device) request, the firmware must respond
//	and let the host know if the USB peripheral device is currently bus powered
//	or self powered.  See chapter 9 in the official USB specifications for details
//	regarding this request.  If the peripheral device is capable of being both
//	self and bus powered, it should not return a hard coded value for this request.
//	Instead, firmware should check if it is currently self or bus powered, and
//	respond accordingly.  If the hardware has been configured like demonstrated
//	on the PICDEM FS USB Demo Board, an I/O pin can be polled to determine the
//	currently selected power source.  On the PICDEM FS USB Demo Board, "RA2"
//	is used for	this purpose.  If using this feature, make sure "USE_SELF_POWER_SENSE_IO"
//	has been defined in HardwareProfile - (platform).h, and that an appropriate I/O pin
//  has been mapped	to it.
    #if defined(USE_SELF_POWER_SENSE_IO)
    tris_self_power = INPUT_PIN;	// See HardwareProfile.h
    #endif

    USBDeviceInit();	//usb_device.c.  Initializes USB module SFRs and firmware
    					//variables to known states.

    
}//end InitializeSystem
Exemple #27
0
/****************************************************************************
  Function:
    void BSP_Initialize(void)

  Description:
    This routine initializes the hardware. 

  Precondition:
    None

  Parameters:
    None - None

  Returns:
    None

  Remarks:
    None
 ***************************************************************************/
void BSP_Initialize(void)
{
    // LEDs
    LED0_TRIS = 0;
    LED1_TRIS = 0;
    LED2_TRIS = 0;
    LED3_TRIS = 0;
    LED4_TRIS = 0;
    LED5_TRIS = 0;
    LED6_TRIS = 0;
    LED_PUT(0x00);


#if defined(__dsPIC33F__) || defined(__PIC24H__)
    // Crank up the core frequency
    PLLFBD = 38; // Multiply by 40 for 160MHz VCO output (8MHz XT oscillator)
    //	CLKDIV = 0x0000;			// FRC: divide by 2, PLLPOST: divide by 2, PLLPRE: divide by 2
    CLKDIVbits.PLLPOST = 0; /* N1 = 2	*/
    CLKDIVbits.PLLPRE = 0; /* N2 = 2	*/
    OSCTUN = 0;

    /*	Initiate Clock Switch to Primary
     *	Oscillator with PLL (NOSC= 0x3)*/
    __builtin_write_OSCCONH(0x03);
    __builtin_write_OSCCONL(0x01);
    // Disable Watch Dog Timer
    RCONbits.SWDTEN = 0;
    while (OSCCONbits.COSC != 0x3);
    while (_LOCK == 0); /* Wait for PLL lock at 60 MIPS */
    // Port I/O
    AD1PCFGHbits.PCFG23 = 1; // Make RA7 (BUTTON1) a digital input
    AD1PCFGHbits.PCFG20 = 1; // Make RA12 (INT1) a digital input for MRF24W PICtail Plus interrupt

    // ADC
    AD1CHS0 = 0; // Input to AN0 (potentiometer)
    AD1PCFGLbits.PCFG5 = 0; // Disable digital input on AN5 (potentiometer)
    AD1PCFGLbits.PCFG4 = 0; // Disable digital input on AN4 (TC1047A temp sensor)

    TRISFbits.TRISF6 = 0;
    TRISFbits.TRISF7 = 0;
    TRISFbits.TRISF8 = 0;

#elif defined(__dsPIC33E__)||defined(__PIC24E__)

    // Crank up the core frequency
    PLLFBD = 38; /* M  = 30	*/
    CLKDIVbits.PLLPOST = 0; /* N1 = 2	*/
    CLKDIVbits.PLLPRE = 0; /* N2 = 2	*/
    OSCTUN = 0;

    /*	Initiate Clock Switch to Primary
     *	Oscillator with PLL (NOSC= 0x3)*/
    __builtin_write_OSCCONH(0x03);
    __builtin_write_OSCCONL(0x01);
    // Disable Watch Dog Timer
    RCONbits.SWDTEN = 0;
    while (OSCCONbits.COSC != 0x3);
    while (_LOCK == 0); /* Wait for PLL lock at 60 MIPS */
    // Port I/O
    ANSELAbits.ANSA7 = 0; //Make RA7 (BUTTON1) a digital input
#if defined ENC100_INTERFACE_MODE > 0
    ANSELEbits.ANSE0 = 0; // Make these PMP pins as digital output when the interface is parallel.
    ANSELEbits.ANSE1 = 0;
    ANSELEbits.ANSE2 = 0;
    ANSELEbits.ANSE3 = 0;
    ANSELEbits.ANSE4 = 0;
    ANSELEbits.ANSE5 = 0;
    ANSELEbits.ANSE6 = 0;
    ANSELEbits.ANSE7 = 0;
    ANSELBbits.ANSB10 = 0;
    ANSELBbits.ANSB11 = 0;
    ANSELBbits.ANSB12 = 0;
    ANSELBbits.ANSB13 = 0;
    ANSELBbits.ANSB15 = 0;
#endif

    ANSELEbits.ANSE8 = 0; // Make RE8(INT1) a digital input for ZeroG ZG2100M PICtail

    AD1CHS0 = 0; // Input to AN0 (potentiometer)
    ANSELBbits.ANSB0 = 1; // Input to AN0 (potentiometer)
    ANSELBbits.ANSB5 = 1; // Disable digital input on AN5 (potentiometer)
    ANSELBbits.ANSB4 = 1; // Disable digital input on AN4 (TC1047A temp sensor)
    ANSELDbits.ANSD7 = 0; //  Digital Pin Selection for S3(Pin 83) and S4(pin 84).
    ANSELDbits.ANSD6 = 0;

    ANSELGbits.ANSG6 = 0; // Enable Digital input for RG6 (SCK2)
    ANSELGbits.ANSG7 = 0; // Enable Digital input for RG7 (SDI2)
    ANSELGbits.ANSG8 = 0; // Enable Digital input for RG8 (SDO2)
    ANSELGbits.ANSG9 = 0; // Enable Digital input for RG9 (CS)
#if defined ENC100_INTERFACE_MODE == 0	// SPI Interface, UART can be used for debugging. Not allowed for other interfaces.
    RPOR9 = 0x0300; //RP101= U2TX
    RPINR19 = 0X0064; //RP100= U2RX
#endif

#if defined WF_CS_TRIS
    RPINR1bits.INT3R = 30;
    WF_CS_IO = 1;
    WF_CS_TRIS = 0;

#endif

#else	//defined(__PIC24F__)
#if defined(__PIC24F__)
    CLKDIVbits.RCDIV = 0; // Set 1:1 8MHz FRC postscalar
#endif

    // ADC
#if defined(__PIC24FJ256DA210__) || defined(__PIC24FJ256GB210__)
    // Disable analog on all pins
    ANSA = 0x0000;
    ANSB = 0x0000;
    ANSC = 0x0000;
    ANSD = 0x0000;
    ANSE = 0x0000;
    ANSF = 0x0000;
    ANSG = 0x0000;
#else
    AD1CHS = 0; // Input to AN0 (potentiometer)
    AD1PCFGbits.PCFG4 = 0; // Disable digital input on AN4 (TC1047A temp sensor)
    AD1PCFGbits.PCFG5 = 0; // Disable digital input on AN5 (potentiometer)
#endif
#endif

    // ADC
    AD1CON1 = 0x84E4; // Turn on, auto sample start, auto-convert, 12 bit mode (on parts with a 12bit A/D)
    AD1CON2 = 0x0404; // AVdd, AVss, int every 2 conversions, MUXA only, scan
    AD1CON3 = 0x1003; // 16 Tad auto-sample, Tad = 3*Tcy
    AD1CSSL = 1 << 5; // Scan pot

    // Deassert all chip select lines so there isn't any problem with
    // initialization order.  Ex: When ENC28J60 is on SPI2 with Explorer 16,
    // MAX3232 ROUT2 pin will drive RF12/U2CTS ENC28J60 CS line asserted,
    // preventing proper 25LC256 EEPROM operation.
#if defined(ENC_CS_TRIS)
    ENC_CS_IO = 1;
    ENC_CS_TRIS = 0;
#endif
#if defined(ENC100_CS_TRIS)
    ENC100_CS_IO = (ENC100_INTERFACE_MODE == 0);
    ENC100_CS_TRIS = 0;
#endif
#if defined(EEPROM_CS_TRIS)
    EEPROM_CS_IO = 1;
    EEPROM_CS_TRIS = 0;
#endif
#if defined(SPIRAM_CS_TRIS)
    SPIRAM_CS_IO = 1;
    SPIRAM_CS_TRIS = 0;
#endif
#if defined(SPIFLASH_CS_TRIS)
    SPIFLASH_CS_IO = 1;
    SPIFLASH_CS_TRIS = 0;
#endif
#if defined(TCPIP_IF_MRF24W)
    // Removed CS operation here for better code organization
    // Tested fine with removing these two lines
#endif

#if defined(PIC24FJ64GA004_PIM)
    __builtin_write_OSCCONL(OSCCON & 0xBF); // Unlock PPS

    // Remove some LED outputs to regain other functions
    LED1_TRIS = 1; // Multiplexed with BUTTON0
    LED5_TRIS = 1; // Multiplexed with EEPROM CS
    LED7_TRIS = 1; // Multiplexed with BUTTON1

    // Inputs
    RPINR19bits.U2RXR = 19; //U2RX = RP19
    RPINR22bits.SDI2R = 20; //SDI2 = RP20
    RPINR20bits.SDI1R = 17; //SDI1 = RP17

    // Outputs
    RPOR12bits.RP25R = U2TX_IO; //RP25 = U2TX
    RPOR12bits.RP24R = SCK2OUT_IO; //RP24 = SCK2
    RPOR10bits.RP21R = SDO2_IO; //RP21 = SDO2
    RPOR7bits.RP15R = SCK1OUT_IO; //RP15 = SCK1
    RPOR8bits.RP16R = SDO1_IO; //RP16 = SDO1

    AD1PCFG = 0xFFFF; //All digital inputs - POT and Temp are on same pin as SDO1/SDI1, which is needed for ENC28J60 commnications

    __builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(__PIC24FJ256DA210__)
    __builtin_write_OSCCONL(OSCCON & 0xBF); // Unlock PPS

    // Inputs
    RPINR19bits.U2RXR = 11; // U2RX = RP11
    RPINR20bits.SDI1R = 0; // SDI1 = RP0
    RPINR0bits.INT1R = 34; // Assign RE9/RPI34 to INT1 (input) for MRF24W Wi-Fi PICtail Plus interrupt

    // Outputs
    RPOR8bits.RP16R = 5; // RP16 = U2TX
    RPOR1bits.RP2R = 8; // RP2 = SCK1
    RPOR0bits.RP1R = 7; // RP1 = SDO1

    __builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(__PIC24FJ256GB110__) || defined(__PIC24FJ256GB210__)
    __builtin_write_OSCCONL(OSCCON & 0xBF); // Unlock PPS

    // Configure SPI1 PPS pins (ENC28J60/ENCX24J600/MRF24W or other PICtail Plus cards)
    RPOR0bits.RP0R = 8; // Assign RP0 to SCK1 (output)
    RPOR7bits.RP15R = 7; // Assign RP15 to SDO1 (output)
    RPINR20bits.SDI1R = 23; // Assign RP23 to SDI1 (input)

    // Configure SPI2 PPS pins (25LC256 EEPROM on Explorer 16)
    RPOR10bits.RP21R = 11; // Assign RG6/RP21 to SCK2 (output)
    RPOR9bits.RP19R = 10; // Assign RG8/RP19 to SDO2 (output)
    RPINR22bits.SDI2R = 26; // Assign RG7/RP26 to SDI2 (input)

    // Configure UART2 PPS pins (MAX3232 on Explorer 16)
#if !defined(ENC100_INTERFACE_MODE) || (ENC100_INTERFACE_MODE == 0) || defined(ENC100_PSP_USE_INDIRECT_RAM_ADDRESSING)
    RPINR19bits.U2RXR = 10; // Assign RF4/RP10 to U2RX (input)
    RPOR8bits.RP17R = 5; // Assign RF5/RP17 to U2TX (output)
#endif

    // Configure INT1 PPS pin (MRF24W Wi-Fi PICtail Plus interrupt signal when in SPI slot 1)
    RPINR0bits.INT1R = 33; // Assign RE8/RPI33 to INT1 (input)

    // Configure INT3 PPS pin (MRF24W Wi-Fi PICtail Plus interrupt signal when in SPI slot 2)
    RPINR1bits.INT3R = 40; // Assign RC3/RPI40 to INT3 (input)

    __builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(__PIC24FJ256GA110__)
    __builtin_write_OSCCONL(OSCCON & 0xBF); // Unlock PPS

    // Configure SPI2 PPS pins (25LC256 EEPROM on Explorer 16 and ENC28J60/ENCX24J600/MRF24W or other PICtail Plus cards)
    // Note that the ENC28J60/ENCX24J600/MRF24W PICtails SPI PICtails must be inserted into the middle SPI2 socket, not the topmost SPI1 slot as normal.  This is because PIC24FJ256GA110 A3 silicon has an input-only RPI PPS pin in the ordinary SCK1 location.  Silicon rev A5 has this fixed, but for simplicity all demos will assume we are using SPI2.
    RPOR10bits.RP21R = 11; // Assign RG6/RP21 to SCK2 (output)
    RPOR9bits.RP19R = 10; // Assign RG8/RP19 to SDO2 (output)
    RPINR22bits.SDI2R = 26; // Assign RG7/RP26 to SDI2 (input)

    // Configure UART2 PPS pins (MAX3232 on Explorer 16)
    RPINR19bits.U2RXR = 10; // Assign RF4/RP10 to U2RX (input)
    RPOR8bits.RP17R = 5; // Assign RF5/RP17 to U2TX (output)

    // Configure INT3 PPS pin (MRF24W PICtail Plus interrupt signal)
    RPINR1bits.INT3R = 36; // Assign RA14/RPI36 to INT3 (input)

    __builtin_write_OSCCONL(OSCCON | 0x40); // Lock PPS
#endif

#if defined(SPIRAM_CS_TRIS)
    SPIRAMInit();
#endif
#if defined(EEPROM_CS_TRIS)
    XEEInit();
#endif
#if defined(SPIFLASH_CS_TRIS)
    SPIFlashInit();
#endif

}
Exemple #28
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
        case SYSTEM_STATE_USB_START:
            //Switch to alternate interrupt vector table for bootloader
            INTCON2bits.ALTIVT = 1;
            BUTTON_Enable(BUTTON_USB_DEVICE_HID_CUSTOM);

            if((BUTTON_IsPressed(BUTTON_USB_DEVICE_HID_CUSTOM)==false) && ((RCON & 0x83) != 0))
            {
                //Switch to app standare IVT for non boot mode
                INTCON2bits.ALTIVT = 0;
                __asm__("goto 0x1800");
            }
            ANSELA = 0x0000;
            ANSELB = 0x0000;
            ANSELC = 0x0000;
            ANSELD = 0x0000;
            ANSELE = 0x0000;
            ANSELG = 0x0000;

            // Configure the device PLL to obtain 60 MIPS operation. The crystal
            // frequency is 8MHz. Divide 8MHz by 2, multiply by 60 and divide by
            // 2. This results in Fosc of 120MHz. The CPU clock frequency is
            // Fcy = Fosc/2 = 60MHz. Wait for the Primary PLL to lock and then
            // configure the auxilliary PLL to provide 48MHz needed for USB
            // Operation.

            PLLFBD = 58;                        /* M  = 60  */
            CLKDIVbits.PLLPOST = 0;             /* N1 = 2   */
            CLKDIVbits.PLLPRE = 0;              /* N2 = 2   */
            OSCTUN = 0;

            /*	Initiate Clock Switch to Primary
             *	Oscillator with PLL (NOSC= 0x3)*/
            __builtin_write_OSCCONH(0x03);
            __builtin_write_OSCCONL(0x01);

            while (OSCCONbits.COSC != 0x3);

            // Configuring the auxiliary PLL, since the primary
            // oscillator provides the source clock to the auxiliary
            // PLL, the auxiliary oscillator is disabled. Note that
            // the AUX PLL is enabled. The input 8MHz clock is divided
            // by 2, multiplied by 24 and then divided by 2. Wait till
            // the AUX PLL locks.

            ACLKCON3 = 0x24C1;
            ACLKDIV3 = 0x7;

            ACLKCON3bits.ENAPLL = 1;
            while(ACLKCON3bits.APLLCK != 1);
            
            LED_Enable(LED_USB_DEVICE_STATE);
            LED_Enable(LED_USB_DEVICE_HID_CUSTOM);
            
            break;
            
        case SYSTEM_STATE_USB_SUSPEND:
            break;
            
        case SYSTEM_STATE_USB_RESUME:
            break;
    }
}
Exemple #29
0
void hw_init(void)
{
    volatile unsigned int i;
    /* LED */
    LED_DIR = 0;
    LED = 0;

    /* make all ports digital */
    ANSELA = 0;
    ANSELB = 0;
    ANSELC = 0;

    /* for debug */
    TRISBbits.TRISB4 = 0;
    LATBbits.LATB4 = 0;


#ifndef WITH_BOOTLOADER
    /* oscillator config */
    /* Fosc = 140MHz (70MIPS) */
    /* Fsys = 280MHz */
    CLKDIVbits.PLLPRE = 0;
    CLKDIVbits.PLLPOST = 0;
    PLLFBDbits.PLLDIV = 74;

    /* switch clock to FRC oscillator with PLL */
    __builtin_write_OSCCONH(1);
    __builtin_write_OSCCONL(OSCCON | 1);

    /* wait for clock switch to complete */
    while (OSCCONbits.OSWEN == 1);
    /* wait for PLL lock */
    while (OSCCONbits.LOCK != 1);
#endif

    LED = 1;

    /* detect hw revision */
    /* set RB9 internal pull down */
    _TRISB9 = 1;
    _CNPUB9 = 0;
    _CNPDB9 = 1;

    /* set RA9 internal pull down */
    _TRISA9 = 1;
    _CNPUA9 = 0;
    _CNPDA9 = 1;
    for (i = 0; i < 10000; i++);
    
    if (_RB9 == 1)
        /* hw 0v3 has external pull-up on RB9 */
        hw_rev = 0x03;
    else if (_RA9 == 1)
        /* hw 0v2 has RB9 floating and RA9 pull-up */
        hw_rev = 0x02;
    else
        /* hw 0v1 has RA9 and RB9 floating */
        hw_rev = 0x01;
    _CNPDB9 = 0;
    _CNPDA9 = 0;

    /* weak pull up on serial port rx pins */
    if (hw_rev == 0x03) {
        _CNPUB11 = 1;
        _CNPUB6 = 1;
        _CNPUB2 = 1;
        _CNPUB13 = 1;
    } else {
        _CNPUB6 = 1;
        _CNPUA4 = 1;
    }
}
Exemple #30
0
void	Init()
	{
	//*****************************************************************
	// Switch to operation at 50 MHz driven by external 12 MHz crystall
	//-----------------------------------------------------------------
	// PLL Pre-scaler
	_PLLPRE = 1;		// N1 	= (PLLPRE + 2) 	= 3;
						// Fref	= 12 MHz / 3 	= 4 MHz;
	// PLL Multiplier
	_PLLDIV = 38;		// M	= (PLLDIV + 2)	= 40;
						// Fvco = Fref * M		= 160 MHz
	// PLL Post-scaler
	_PLLPOST = 0;		// N2 	= (PLLPOST + 2) = 2;
						// Fosc	= Fvco / N2		= 80 MHz

	// By definition, Fcy = Fosc/2 = 80 MHz / 2 = 40 MHz
	//--------------------------------------------------------------------
	// Initiate Clock Switch to Primary Oscillator with PLL (NOSC = 0b011)
	__builtin_write_OSCCONH(0x03);		// Set OSCCONbits.NOSC = 0b011
	__builtin_write_OSCCONL(0x01);		// Request oscillator switch
				// NOTE: Statement above also sets IOLOCK=0, enabling
				// reconfiguration of remappable peripherals.
				//-----------------------------------------------------
	// Wait for Clock switch to occur
	while (_COSC != 0b011);	// Wait for COSC = NOSC
	// Wait for PLL to lock
	while( !_LOCK);			// Wait for PLL Lock
	
	//***********************************************
	// NOTE: on POR all ports are configured as INPUT
	//***********************************************
	// NOTE: Pins configured as digital inputs do not
	// convert an analog input. Analog levels on any
	// pin defined as a digital input (including the
	// ANx pins) can cause the input buffer to consume
	// current that exceeds the device specifications.
	//-----------------------------------------------
	// Thus, for safety reason, we leave all pins
	// shared with ANx pins in default ANALOG state.
	//***********************************************
	// Disable ADC through the control register
	//----------------------------------------------- 
	// As we did not disable ADC through the PMD fea-
	// ture (to avoid overloading corresponding pins),
	// we should disable it through the Control Regis-
	// ter (this does not have effect on the ANx pins -
	// they are still in the ANALOG mode)
	//***********************************************
	AD1CON1 = 0x0000;

	//***********************************************
	// Disable all HW modules except ADC
	// (using PERIPHERAL MODULE DISABLE CONTROL)
	//***********************************************
	PMD1 = 0xFFFE;		// AD1MD = 0 => Shared ANx
						// pins are left at default
						// ANALOG mode
	PMD2 = 0xFFFF;
	PMD3 = 0xFFFF;	


	//***********************************************
	// Configure Global Interrupt Control
	//***********************************************
	INTCON1			= 0;	// ...nested interrupts
							// enabled...
	INTCON2			= 0;	// ... globally disables
							// all interrupts...
	//***********************************************
	// Disable ALL Interrupts individually
	//***********************************************
	IEC0	= 0;
	IEC1	= 0;
	IEC2	= 0;
	IEC3	= 0;
	IEC4	= 0;
	//***********************************************
	// Clear ALL Interrupt Flags
	//***********************************************
	IFS0	= 0;
	IFS1	= 0;
	IFS2	= 0;
	IFS3	= 0;
	IFS4	= 0;
	
	}