Esempio n. 1
0
File: BOARD.c Progetto: mdunne/ANIMA
void BOARD_Init() {
    unsigned int dma_status;
    unsigned int int_status;
    //DEVCFG1bits.FCKSM = 0;
    //mSYSTEMUnlock(int_status, dma_status);
    //DEVCFG1bits.FCKSM = 0;
    //DEVCFG2bits.FPLLIDIV=1;
    SYSKEY = 0;
    SYSKEY = 0xAA996655;
    SYSKEY = 0x556699AA;
    CFGCONbits.IOLOCK = 0;
    SYSKEY = 0;
    SYSTEMConfig(SYSTEM_CLOCK, SYS_CFG_ALL);
    ANSELA=0;
    ANSELB=0;
    ANSELC=0;
    //OSCConfig(OSC_FRC_PLL, OSC_PLL_MULT_20, OSC_PLL_POST_1, OSC_FRC_POST_1);
    //OSCCONbits.NOSC=0x1;
    OSCSetPBDIV(OSC_PB_DIV_1);

    //mSYSTEMLock(int_status, dma_status);
    // AD1PCFG = 0xffff;

    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();
    SERIAL_Init();

    //printf("This code compiled at %s on %s\r\n", __TIME__, __DATE__);
}
Esempio n. 2
0
/****************************************************************************
  Function:
    void SYS_Init(void)

  Summary:
    Initialize the PIC32 core to the correct modes and clock speeds

  Description:
    Initialize the PIC32 core to the correct modes and clock speeds

  Precondition:
    Only runs on PIC32

  Parameters:
    None

  Return Values:
    None

  Remarks:
    None
  ***************************************************************************/
void SYS_Init(void)
{
    int  value;

    #if defined(RUN_AT_60MHZ)
        // Use OSCCON default
    #else
        OSCCONCLR = 0x38000000; //PLLODIV
        #if defined(RUN_AT_48MHZ)
            OSCCONSET = 0x08000000; //PLLODIV /2
        #elif defined(RUN_AT_24MHZ)
            OSCCONSET = 0x10000000; //PLLODIV /4
        #else
            #error Cannot set OSCCON
        #endif
    #endif

    value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() );

    // Enable the cache for the best performance
    CheKseg0CacheOn();

    INTEnableSystemMultiVectoredInt();

    DDPCONbits.JTAGEN = 0;

    value = OSCCON;
    while (!(value & 0x00000020))
    {
        value = OSCCON;    // Wait for PLL lock to stabilize
    }

    INTEnableInterrupts();
}
Esempio n. 3
0
File: main.c Progetto: ChakChel/Ix
/**
 * @fn      void intConfig( void );
 * @brief   Configuration des interruptions
 */
void intConfig( void ){

    // Config Interruptions
    // Mode "multi-vectored". Vecteurs d'interruption multiples
    INTEnableSystemMultiVectoredInt();
    // Validation globale des interruptions
    INTEnableInterrupts();
//    uartPutString("Interrupts configured\r\n");
}
Esempio n. 4
0
void __ISR(_TIMER_1_VECTOR, ipl7) _Timer1Handler(void)
{
	HWORD	dtcMtr;
	
	IFS0CLR = ( 1 << 4 );
	
	INTDisableInterrupts();
	if ( ! fMtrLeft ) {
		// Left motor feedback has timed out.
		
		INTEnableInterrupts();
		
		dtcMtr = OC1R + 20;
		if ( dtcMtrMax >= dtcMtr ) {
			OC1RS=  dtcMtr;
		}
		else {
			OC1RS = dtcMtrMax;
		}
	}
	else {
		fMtrLeft = fFalse;
		INTEnableInterrupts();
	}
	
	INTDisableInterrupts();
	if ( ! fMtrRight ) {
		// Right motor feedback has timed out.
		
		INTEnableInterrupts();
		
		dtcMtr = OC4R + 20;
		if ( dtcMtrMax >= dtcMtr ) {
			OC4RS = dtcMtr;
		}
		else {
			OC4RS = dtcMtrMax;
		}
	}
	else {
		fMtrRight = fFalse;
		INTEnableInterrupts();
	}
}
Esempio n. 5
0
void setup_spi() {
    // TODO move it out of here
    INTDisableInterrupts();
    mCNOpen(CN_ON | CN_IDLE_CON, CN1_ENABLE, CN1_PULLUP_ENABLE);
    mPORTCRead();
    mCNSetIntPriority(6); // same as below
    mCNClearIntFlag();
    mCNIntEnable(1);
    INTEnableInterrupts();
}
Esempio n. 6
0
/*********************************************************************
 * Function:  		DWORD get_fattime(void)
 *
 * PreCondition:    
 *
 * Input:           None
 *
 * Output:          Time
 *
 * Side Effects:    
 *
 * Overview:        when writing fatfs requires a time stamp
 *					in this exmaple we are going to use a counter
 *					If the starter kit has the 32kHz crystal
 *					installed then the RTCC could be used instead
 *
 * Note:           
 ********************************************************************/
DWORD get_fattime(void)
{
	DWORD tmr;

	INTDisableInterrupts();
	tmr = GetCurrentDateTimeAsDWORD();
	INTEnableInterrupts();

	return tmr;
}
Esempio n. 7
0
void Setup_communications(void)
{
    FIFOUART1_initialize();
    FIFOUART4_initialize(); //Maher

    //Enable system-wide interrupts
    INTEnableInterrupts();

    CommunicationLoop_start();
}
int main(int argc, char** argv)
{
    SetupTimer1();
    INTEnableInterrupts();

    while (1)
    {
    }
    return (EXIT_SUCCESS);
}
Esempio n. 9
0
//===========================
//	START INTERRUPTS
//===========================
void StartInterrupts(void)
{
  INT8 err;

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Enable timer interrupts
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  Timer.EnableInterrupt(TIMER_1);
//  Timer.EnableInterrupt(TIMER_2);
//  Timer.EnableInterrupt(TIMER_3);
//  Timer.EnableInterrupt(TIMER_4);
//  Timer.EnableInterrupt(TIMER_5);


//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Enable RX UART interrupts and disable TX interrupts. 
// TX interrupts are disabled at init and only
// enabled when writing to the user's TX FIFO buffer
// with Uart.PutTxFifoBuffer(...)
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//  Uart.EnableRxInterrupts (UART6);  // Enable RX Interrupts for UART6
//  Uart.DisableTxInterrupts(UART6);  // Disable TX Interrupts for UART6


//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Enable ADC interrupts
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//  Adc.EnableInterrupts();   // Works only when not in manual mode


//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Enable InputCapture interrupts
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//  InputCapture.EnableInterrupt(IC1);
//  InputCapture.EnableInterrupt(IC2);
//  InputCapture.EnableInterrupt(IC3);
//  InputCapture.EnableInterrupt(IC4);
//  InputCapture.EnableInterrupt(IC5);


//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Enable CAN interrupts
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  Can.EnableInterrupt(CAN1);


//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Enable multi-vector interrupts
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
  INTEnableInterrupts();

}
Esempio n. 10
0
void InitApp(void)
{
    /* Setup analog functionality and port direction */
    TRISEbits.TRISE9 = 1;/*equivalent to int2*/
    TRISEbits.TRISE8 = 1;/*equivalent to int1*/
    TRISAbits.TRISA2 = 1;
    TRISAbits.TRISA3 = 0;

    /* Initialize peripherals */
    INTEnableInterrupts();
    PIN_DEBUG = 1;
}
Esempio n. 11
0
void initialize(void){
     SYSTEMConfig(80000000, SYS_CFG_ALL); // sets up periferal and clock configuration
     INTEnableSystemMultiVectoredInt();
     INTEnableInterrupts(); // enable interrupts
     delay();
     timers();
     delay();
     PWM();
     delay();
     UART();
     delay();
     beginLIDARdecoder(returned_data, &buffer_five);
}
Esempio n. 12
0
/* 
 * Function twi_init
 * Desc     readys twi pins and sets twi bitrate
 * Input    none
 * Output   none
 */
void twi_init( void )
{
	// Enable the I2C1 module and turn on clock stretching.
	I2C1CONSET = ( 1 << bnOn ) | ( 1 << bnStren );
	// Enable Interrupts
	IEC0SET = ( 1 << bnI2c1mie ) | ( 1 << bnI2c1sie) | ( 1 << bnI2c1bie); // Enable interrupts
	IPC6SET = ( 1 << bnI2c1ip2) | ( 1 << bnI2c1ip1); // Setup Interupt Priority
	
	// Configure the I2C1 baud rate generator to output the appropriate
	// clock.
	I2C1BRGSET = ( CLK_PBUS/ ( 2 * TWI_FREQ ) ) - 2;
	
	// Clear the interrupt flags associated with the I2C1 module.
	IFS0CLR = ( 1 << bnI2c1mif ) | ( 1 << bnI2c1sif ) | ( 1 << bnI2c1bif );
	INTEnableSystemMultiVectoredInt ();
	INTEnableInterrupts ();
}
Esempio n. 13
0
File: part2.c Progetto: DC11011100/C
int main(void)
{
    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    // Auto-configure the PIC32 for optimum performance at the specified operating frequency.
    SYSTEMConfigPerformance(SYS_FREQ);

    // osc source, PLL multipler value, PLL postscaler , RC divisor
    OSCConfig(OSC_POSC_PLL, OSC_PLL_MULT_20, OSC_PLL_POST_1, OSC_FRC_POST_1);

    // Configure the PB bus to run at 1/4 the CPU frequency
    OSCSetPBDIV(OSC_PB_DIV_4);

    // Enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();
    INTEnableInterrupts();

    // Set up the UART peripheral so we can send serial data.
    UARTConfigure(UART_USED, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART_USED, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART_USED, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART_USED, F_PB, UART_BAUD_RATE);
    UARTEnable(UART_USED, UART_ENABLE | UART_TX);

    // And configure printf/scanf to use the correct UART.
    if (UART_USED == UART1) {
        __XC_UART = 1;
    }

/***************************************************************************************************
 * Your code goes in between this comment and the following one with asterisks.
 **************************************************************************************************/



/***************************************************************************************************
 * Your code goes in between this comment and the preceding one with asterisks.
 **************************************************************************************************/

    // Returning from main() is bad form in embedded environments. So we sit and spin.
    while (1);
}
void SYS_Initialize ( void* data )
{

    SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);
    
    /* Disable JTAG to free up PORTA pins */
    mJTAGPortEnable(DEBUG_JTAGPORT_OFF);

    BSP_Initialize();
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();
    BSP_WriteString("*** UART Interrupt-driven Application Example ***\r\n");
    BSP_WriteString("*** Type some characters and observe echo ***\r\n");


    /* Initialize the Application */
    APP_Initialize ( );

}
void setupTimer3(int freq) {

    INTDisableInterrupts(); //disable interrupts while settting up

    T3CON = 0b000 << 4; // set prescaler to 1:1
    T3CONCLR = 0x2; // set input to PBCLK (the default; all defaults fine)
    PR3 = (SYS_FREQ / freq) - 1; // set the period in period register 3
    TMR3 = 0; // reset the Timer3 count
    T3CONSET = 1 << 15; // turn Timer3 on


    IPC3bits.T3IP = 5; // set timer interrupt priority
    IPC3bits.T3IS = 0; // set subpriority
    IFS0bits.T3IF = 0; // clear interrupt flag


    INTEnableSystemMultiVectoredInt(); // enable interrupts at CPU
    INTEnableInterrupts();
}
void setupHardware()
{
    SYSTEMConfig(SYS_CLOCK, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    mPORTDSetPinsDigitalOut(BIT_1); //yellow LED
    mPORTGSetPinsDigitalOut(BIT_6); //green LED

    //A1 PIR Input (CN4 module, RB2)
    //A2 STB current consumption (AN3)
    //D0 IR Output
    mPORTDSetPinsDigitalOut(BIT_3); //D1 STB IRF control
    mPORTDSetPinsDigitalIn(BIT_4); //D2 BUT OTG
    mPORTDSetPinsDigitalOut(BIT_5); //D3 SHD RED LED Command OFF acqusition notificaiton
    mPORTDSetPinsDigitalOut(BIT_6); //D4 SHD GREEN LED Command ON acqusition notificaiton
    //D5 IR input (RD7)
    //D6 SHD BUT1
    //D7 SHD BUT2
    mPORTBSetPinsDigitalOut(BIT_14); //D9 monitor relay control

    DDPCONbits.JTAGEN = 0;

    initLEDs();
    initUART();

    initADC();
    setupCNModuleAnd_IR_PIR_Input();
    //setupCNModuleAndPIRInput();
    configureRTC();
    setupIRTransmit();

    switchMonitorOff();
    switchSTBOff();

    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();

    T2CONbits.ON = 1;
}
Esempio n. 17
0
void openSerial(unsigned char serialPortIndex, unsigned long baudRate) {
    // important to activate the RX for UART5. Information found on the net
    if (serialPortIndex == SERIAL_PORT_5) {
        PORTSetPinsDigitalIn(IOPORT_B, BIT_8);
    }
    UART_MODULE uart = getUartModule(serialPortIndex);
    UARTConfigure(uart, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(uart, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(uart, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(uart, GetPeripheralClock(), baudRate);
    UARTEnable(uart, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));

    INTEnable(INT_SOURCE_UART_RX(uart), INT_ENABLED);
    INTSetVectorPriority(INT_VECTOR_UART(uart), INT_PRIORITY_LEVEL_2);
    INTSetVectorSubPriority(INT_VECTOR_UART(uart), INT_SUB_PRIORITY_LEVEL_0);

    // TODO : Move this code to Global Setup !

    // configure for multi-vectored mode
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);

    // enable interrupts
    INTEnableInterrupts();
}
Esempio n. 18
0
U8 uOpioidInit(void)
{
	U8 errorCode = STD_EC_SUCCESS;

	// ====== µC Initialisation ====== //
	// Reset the Port
	LATB = LED_B;								//Everything to 0 except LED_B (active low)
	LATA = LED_R|LED_G;							//Everything to 0 except LED_B and LED_R (active low)

	// -- Set the IO direction -- //
	TRISA = 0xFFFF ^ (LED_R|LED_G);				//Everything in input except LED_R and LED_G
	TRISB = 0xFFFF ^ (LED_B|RAM_MOSI|RAM_SCK|RAM_SS|RAM_HOLD|EXT0_TX|COM0_TX|COM0_MOSI|COM0_SCK);		//Everything in input except LED_B, RAM_MOSI,RAM_SCK,RAM_HOLD,EXT0_TC,COM0_TX,COM0_MOSI and COM0_SCK
	// -------------------------- //

	// -- Attach pins to peripherals -- //
	ppsUnlock();
	ppsAttachOut(U1TX,RPB4);
	ppsAttachIn(U1RX,RPA4);

	ppsAttachOut(U2TX,RPB10);
	ppsAttachIn(U2RX,RPB11);

	ppsAttachOut(SDO1,RPB6);
	ppsAttachIn(SDI1,RPB8);

	ppsAttachOut(SDO2,RPB1);
	ppsAttachIn(SDI2,RPB2);

	ppsAttachIn(INT4,RPB3);
	ppsAttachIn(INT2,RPA2);

	ppsAttachOut(OC1,RPA0);
	ppsAttachOut(OC2,RPA1);
	ppsAttachOut(OC3,RPB0);

	//ppsAttachOut(REFCLKO,RPA2);
	ppsLock();
	// -------------------------------- //
	
	// -- Init the Interrupts -- //
	INTEnableSystemMultiVectoredInt();

	intFastSetPriority(COM0_IRQ0_INT_ID, 4);
	intSetExternalEdge(COM0_IRQ0_INT_IRQ, RISING);			//COM0 IRQ0 is Rising edge by default
	intFastSetPriority(COM0_IRQ1_INT_ID, 4);
	intSetExternalEdge(COM0_IRQ1_INT_IRQ, RISING);			//COM0 IRQ1 is Rising edge by default
	intFastSetPriority(COM0_SPI_INT_ID, 5);
	intFastSetPriority(COM0_UART_INT_ID, 5);

	intFastSetPriority(RAM_SPI_INT_ID, 6);

	intFastSetPriority(EXT0_IRQ_INT_ID, 2);
	intSetExternalEdge(EXT0_IRQ_INT_IRQ, RISING);			//EXT0 IRQ0 is Rising edge by default
	intFastSetPriority(EXT0_UART_INT_ID, 3);
	intFastSetPriority(BTN_INT_ID, 1);
	intSetExternalEdge(BTN_INT_IRQ, FALLING);				//BTN Falling edge trigger
	intFastInit(BTN_INT_ID);

	INTEnableInterrupts();
	// ------------------------- //

	// -- Init the realTime system -- //
	errorCode = realTimeInit(UOPIOID_SYSTICK_VALUE);
	if (errorCode != STD_EC_SUCCESS)
		return errorCode;
	// ------------------------------ //
	// =============================== //


	// ====== External Initialization ====== //
	// -- RAM initialisation -- //
	//Init the RAM SPI
	spiSetConfig(RAM_SPI_ID,SPI_MODE_MASTER|SPI_ENHANCED_BUF|SPI_TX_BUF_INT_BUF_EMPTY|SPI_RX_BUF_INT_BUF_HALF_FULL);
	spiSetBaudRate(RAM_SPI_ID,5000000);
	spiStart(RAM_SPI_ID);

	spiAddSlave(RAM_SPI_ID,&LATB,RAM_SS);
	// ------------------------ //

	// -- COM0 Initialisation -- //
	//Init the COM Uart
	errorCode = uartInit(COM0_UART_ID,UART_TX_INT_TSR_EMPTY|UART_RX_INT_DATA_READY|UART_MODE_8N1);
	if (errorCode != STD_EC_SUCCESS)
		return errorCode;

	//Init the COM SPI
	spiSetConfig(COM0_SPI_ID,SPI_MODE_MASTER|SPI_ENHANCED_BUF|SPI_TX_BUF_INT_BUF_EMPTY|SPI_RX_BUF_INT_BUF_HALF_FULL);
	spiSetBaudRate(COM0_SPI_ID,5000000);
	spiStart(COM0_SPI_ID);

	//Detect presence

	// ------------------------- //


	// -- EXT0 Initialisation -- //
	//Init the EXT Uart

	//Detect presence

	// ------------------------- //
	// ===================================== //
	
	return errorCode;
}
Esempio n. 19
0
int32_t main(void)
{

#ifndef PIC32_STARTER_KIT
    /*The JTAG is on by default on POR.  A PIC32 Starter Kit uses the JTAG, but
    for other debug tool use, like ICD 3 and Real ICE, the JTAG should be off
    to free up the JTAG I/O */
    DDPCONbits.JTAGEN = 0;
#endif

    /*Refer to the C32 peripheral library documentation for more
    information on the SYTEMConfig function.
    
    This function sets the PB divider, the Flash Wait States, and the DRM
    /wait states to the optimum value.  It also enables the cacheability for
    the K0 segment.  It could has side effects of possibly alter the pre-fetch
    buffer and cache.  It sets the RAM wait states to 0.  Other than
    the SYS_FREQ, this takes these parameters.  The top 3 may be '|'ed
    together:
    
    SYS_CFG_WAIT_STATES (configures flash wait states from system clock)
    SYS_CFG_PB_BUS (configures the PB bus from the system clock)
    SYS_CFG_PCACHE (configures the pCache if used)
    SYS_CFG_ALL (configures the flash wait states, PB bus, and pCache)*/

    /* TODO Add user clock/system configuration code if appropriate.  */
    SYSTEMConfig(SYS_FREQ, SYS_CFG_ALL); 

    /* Initialize I/O and Peripherals for application */
    InitApp();

    /*Configure Multivector Interrupt Mode.  Using Single Vector Mode
    is expensive from a timing perspective, so most applications
    should probably not use a Single Vector Mode*/
    // Configure UART2 RX Interrupt
    INTEnable(INT_SOURCE_UART_RX(UART2), INT_ENABLED);
    INTSetVectorPriority(INT_VECTOR_UART(UART2), INT_PRIORITY_LEVEL_2);
    INTSetVectorSubPriority(INT_VECTOR_UART(UART2), INT_SUB_PRIORITY_LEVEL_0);

    // configure for multi-vectored mode
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);

    // enable interrupts
    INTEnableInterrupts();


    /* TODO <INSERT USER APPLICATION CODE HERE> */
    //Open UART2
    OpenUART2(UART_EN, UART_BRGH_FOUR|UART_RX_ENABLE | UART_TX_ENABLE, 21);

    //Open SPI 1 channel
    PORTBbits.RB11 = 1;
    OpenSPI1( SPI_MODE8_ON | MASTER_ENABLE_ON | SEC_PRESCAL_1_1 | PRI_PRESCAL_1_1 | FRAME_ENABLE_OFF | CLK_POL_ACTIVE_HIGH | ENABLE_SDO_PIN , SPI_ENABLE );
    SPI1BRG=39;
    initRadio();
    setTXAddress("UNIT2");
    setRXAddress(0,"UNIT1");
    char temp;
    char text[6];
    text[0]='H';
    text[1]='e';
    text[2]='l';
    text[3]='l';
    text[4]='o';
    text[5]='!';
    while(1)
    {
        setTransmitter();
        PORTBbits.RB11 = 0;
        DelayMs(20);
        transmitData(&text[0],6);
        printf("Hello world! \r\n");
        PORTBbits.RB11 = 1;
        DelayMs(20);
    }
}
Esempio n. 20
0
void ClearExternalIO(void) {
	int i;

//	GS I2C Start
	i2c_disable();
	i2c_slave_disable();
//	GS I2C End

	if (SerialConsole != 1) SerialClose(1);
	if (SerialConsole != 2) SerialClose(2);
	if (SerialConsole != 3) SerialClose(3);
	if (SerialConsole != 4) SerialClose(4);

	// stop the sound
	SoundPlay = 0;
	CloseTimer2();
#ifdef OLIMEX
	CloseOC1();
#else
	CloseOC2();
#endif
	inttbl[NBRPINS + 2].intp = NULL;					// disable the tick interrupt
	for (i = 1; i < NBRPINS + 1; i++) {
		inttbl[i].intp = NULL;						// disable all interrupts
#ifdef OLIMEX
    #ifdef  OLIMEX_DUINOMITE_EMEGA
		if (ExtCurrentConfig[i] != EXT_CONSOLE_RESERVED && i != 35 ) {	// don't reset the serial console
    #else
		if (ExtCurrentConfig[i] != EXT_CONSOLE_RESERVED && i != 21 ) {	// don't reset the serial console
    #endif
#else
		if (ExtCurrentConfig[i] != EXT_CONSOLE_RESERVED) {              // don't reset the serial console
#endif
			ExtCfg(i, EXT_NOT_CONFIG);                              // all set to unconfigured
			ExtSet(i, 0);						// all outputs (when set) default to low
		}
	}
        InterruptReturn = NULL;
}


/****************************************************************************************************************************
Initialise the I/O pins
*****************************************************************************************************************************/
void initExtIO(void) {
	int i;

	for (i = 1; i < NBRPINS + 1; i++) {
		ExtCfg(i, EXT_NOT_CONFIG);                                      // all set to unconfigured
		ExtSet(i, 0);							// all outputs (when set) default to low
	}
#ifndef OLIMEX
 	CNCONbits.ON = 1;       						// turn on Change Notification module
 	CNPUEbits.CNPUE1 = 1;							// turn on the pullup for pin C13 also called CN1
#endif
	ExtCurrentConfig[0] = EXT_DIG_IN;                                       // and show that we can read from it
	P_LED_TRIS = P_OUTPUT; 							// make the LED pin an output
	ExtSet(0, 0);								// and turn it off
#ifdef OLIMEX
    #ifdef OLIMEX_DUINOMITE_EMEGA
	ExtCurrentConfig[35] = EXT_ANA_IN;
    #else
	ExtCurrentConfig[21] = EXT_ANA_IN;
    #endif
#endif

	// setup the analog (ADC) function
	AD1CON1 = 0x00E0;       						// automatic conversion after sampling
 	AD1CSSL = 0;       							// no scanning required
	AD1CON2 = 0;       							// use MUXA, use AVdd   &   AVss as Vref+/-
	AD1CON3 = 0x203; //0x1F3F;  							// Tsamp = 32 x Tad;
	AD1CON1bits.ADON = 1; 							// turn on the ADC

}


/****************************************************************************************************************************
Configure an I/O pin
Returns true if all is OK
*****************************************************************************************************************************/
int ExtCfg(int pin, int cfg) {
	int tris, ana, oc;

	if (pin < 0 || pin > NBRPINS) return false;						// initial sanity check

	// make sure that interrupts are disabled in case we are changing from an interrupt input
#ifdef OLIMEX
//	if (pin == 5) ConfigINT2(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
//	if (pin == 6) ConfigINT3(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
        #ifdef  OLIMEX_DUINOMITE_EMEGA
        #else
                if (pin == 7) ConfigINT4(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
        #endif
#else
	if (pin == 11) ConfigINT1(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
	if (pin == 12) ConfigINT2(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
	if (pin == 13) ConfigINT3(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
	if (pin == 14) ConfigINT4(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_DISABLE);
#endif

	inttbl[pin].intp = NULL;		// also disable a software interrupt on this pin

	switch (cfg) {
		case EXT_NOT_CONFIG:
//	#ifdef OLIMEX
//			if (pin == 5) {P_E5_TRIS = 1; P_E5_OC = 1;}
//			if (pin == 6) {P_E6_TRIS = 1; P_E6_OC = 1;}
//			if (pin == 11) {P_E11_TRIS = 1; P_E11_OC = 1;}
//			if (pin == 12) {P_E12_TRIS = 1; P_E12_OC = 1;}
//	#endif
			tris = 1; ana = 1; oc = 1;
			break;

		case EXT_ANA_IN:
//	#ifdef OLIMEX
			if (pin > 6 && pin < 19) return false;
//			if (pin == 5) {P_E5_TRIS = 1; P_E5_OC = 1;}
//			if (pin == 6) {P_E6_TRIS = 1; P_E6_OC = 1;}
//	#else
//			if (pin > 10) return false;
//	#endif
			tris = 1; ana = 0; oc = 1;
			break;

		case EXT_FREQ_IN:											// same as counting, so fall through
		case EXT_PER_IN:											// same as counting, so fall through
		case EXT_CNT_IN:
//	#ifdef OLIMEX
//	#else
//			if (pin == 11) {
//				INT1Count = INT1Value = 0;
//				ConfigINT1(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_ENABLE);
//				tris = 1; ana = 1; oc = 1;
//				break;
//			}
//	#endif
//	#ifdef OLIMEX
//			if (pin == 5) {
//				P_E5_TRIS = 1;
//				P_E5_OC = 1;
//	#else
//			if (pin == 12) {
//	#endif
//				INT2Count = INT2Value = 0;
//				ConfigINT2(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_ENABLE);
//				tris = 1; ana = 1; oc = 1;
//				break;
//			}
//	#ifdef OLIMEX
//			if (pin == 6) {
//				P_E6_TRIS = 1;
//				P_E6_OC = 1;
//	#else
//			if (pin == 13) {
//	#endif
//				INT3Count = INT3Value = 0;
//				ConfigINT3(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_ENABLE);
//				tris = 1; ana = 1; oc = 1;
//				break;
//			}
#ifdef  OLIMEX_DUINOMITE_EMEGA
                    break;
#else
	#ifdef OLIMEX
			if (pin == 7) {
	#else
			if (pin == 14) {
	#endif
				INT4Count = INT4Value = 0;
				ConfigINT4(EXT_INT_PRI_2 | RISING_EDGE_INT | EXT_INT_ENABLE);
				tris = 1; ana = 1; oc = 1;
				break;
			}
			return false;							// not an interrupt enabled pin
#endif

		case EXT_INT_LO:											// same as digital input, so fall through
		case EXT_INT_HI:											// same as digital input, so fall through
		case EXT_DIG_IN:
	#ifdef OLIMEX
//                        if (pin == 5) {P_E5_TRIS = 1; P_E5_OC = 1;}
//			if (pin == 6) {P_E6_TRIS = 1; P_E6_OC = 1;}
//			if (pin == 11) {P_E11_TRIS = 1; P_E11_OC = 1;}
//			if (pin == 12) {P_E12_TRIS = 1; P_E12_OC = 1;}
	#endif
			tris = 1; ana = 1; oc = 1;
			break;

		case EXT_DIG_OUT:
	#ifdef OLIMEX
//			if (pin == 11) {P_E11_TRIS = 1; P_E11_OC = 1;} //return false;
//			if (pin == 5) {P_E5_TRIS = 1; P_E5_OC = 1;}
//			if (pin == 6) {P_E6_TRIS = 1; P_E6_OC = 1;}
//			if (pin == 12) {P_E12_TRIS = 1; P_E12_OC = 1;}
	#endif
			tris = 0; ana = 1; oc = 0;
			break;

		case EXT_OC_OUT:
	#ifdef OLIMEX
//			if (pin == 11) {P_E11_TRIS = 1; P_E11_OC = 1;} //return false;
//			if (pin == 5) {P_E5_TRIS = 1; P_E5_OC = 1;}
//			if (pin == 6) {P_E6_TRIS = 1; P_E6_OC = 1;}
//			if (pin == 12) {P_E12_TRIS = 1; P_E12_OC = 1;}
	#else
			if (pin < 11) return false;
	#endif
			tris = 0; ana = 1; oc = 1;
			break;

		case EXT_COM_RESERVED:
		case EXT_CONSOLE_RESERVED:
			ExtCurrentConfig[pin] = cfg;		// don't do anything except set the config type
		#ifdef OLIMEX
//			if (pin == 5) {P_E5_TRIS = 1; P_E5_OC = 1; P_E5_ANALOG = 1;}
//			if (pin == 6) {P_E6_TRIS = 1; P_E6_OC = 1; P_E6_ANALOG = 1;}
//			if (pin == 11) {P_E11_TRIS = 1; P_E11_OC = 1;}
//			if (pin == 12) {P_E12_TRIS = 1; P_E12_OC = 1;}
		#endif
			return true;

		default:
			return false;
	}

	ExtCurrentConfig[pin] = cfg;

	// set the TRIS and analog characteristics
	switch (pin) {
		case 1:  P_E1_TRIS = tris;   P_E1_OC = oc;   P_E1_ANALOG = ana;		break;
		case 2:  P_E2_TRIS = tris;   P_E2_OC = oc;   P_E2_ANALOG = ana;		break;
		case 3:  P_E3_TRIS = tris;   P_E3_OC = oc;   P_E3_ANALOG = ana;		break;
		case 4:  P_E4_TRIS = tris;   P_E4_OC = oc;   P_E4_ANALOG = ana;		break;
		case 5:  P_E5_TRIS = tris;   P_E5_OC = oc;   P_E5_ANALOG = ana;		break;
		case 6:  P_E6_TRIS = tris;   P_E6_OC = oc;   P_E6_ANALOG = ana;		break;
	#ifdef OLIMEX
            #ifdef  OLIMEX_DUINOMITE_EMEGA
		case 7:  P_E7_TRIS = tris;   P_E7_OC = oc;   P_E7_ANALOG = ana;		break;
		case 8:  P_E8_TRIS = tris;   P_E8_OC = oc;   break;
		case 9:  P_E9_TRIS = tris;   P_E9_OC = oc;   break;
		case 10: P_E10_TRIS = tris;  P_E10_OC = oc;  break;
            #else
		case 7:  P_E7_TRIS = tris;   P_E7_OC = oc;	              break;
 		case 8:  if (!S.SDEnable) { P_E8_TRIS = tris; P_E8_OC = oc;}  break;
		case 9:  if (!S.SDEnable) { P_E9_TRIS = tris; P_E9_OC = oc;}  break;
		case 10: if (!S.SDEnable) { P_E10_TRIS = tris; P_E10_OC = oc;} break;
            #endif
	#else
		case 7:  P_E7_TRIS = tris;   P_E7_OC = oc;   P_E7_ANALOG = ana;		break;
		case 8:  P_E8_TRIS = tris;   P_E8_OC = oc;   P_E8_ANALOG = ana;		break;
		case 9:  P_E9_TRIS = tris;   P_E9_OC = oc;   P_E9_ANALOG = ana;		break;
		case 10: P_E10_TRIS = tris;  P_E10_OC = oc;  P_E10_ANALOG = ana;	break;
	#endif
		case 11: P_E11_TRIS = tris;  P_E11_OC = oc;			break;
		case 12: P_E12_TRIS = tris;  P_E12_OC = oc;			break;
		case 13: P_E13_TRIS = tris;  P_E13_OC = oc;			break;
		case 14: P_E14_TRIS = tris;  P_E14_OC = oc;			break;
		case 15: P_E15_TRIS = tris;  P_E15_OC = oc;			break;
		case 16: P_E16_TRIS = tris;  P_E16_OC = oc;			break;
		case 17: P_E17_TRIS = tris;  P_E17_OC = oc;			break;
		case 18: P_E18_TRIS = tris;  P_E18_OC = oc;			break;
	#ifdef OLIMEX
            // SPP +
            #ifdef	OLIMEX_DUINOMITE_EMEGA		// edit for DuinoMite eMega
		case 19: P_E19_TRIS = tris;  P_E19_OC = oc;			break;
		case 20: P_E20_TRIS = tris;  P_E20_OC = oc;                     break;
                case 21: P_E21_TRIS = tris;  P_E21_OC = oc;			break;
		case 22: P_E22_TRIS = tris;  P_E22_OC = oc;			break;
		case 23: P_E23_TRIS = tris;  P_E23_OC = oc;			break;
		case 24: P_E24_TRIS = tris;  P_E24_OC = oc;			break;
		case 25: P_E25_TRIS = tris;  P_E25_OC = oc;			break;
		case 26: P_E26_TRIS = tris;  P_E26_OC = oc;			break;
		case 27: P_E27_TRIS = tris;  P_E27_OC = oc;			break;
		case 28: P_E28_TRIS = tris;  P_E28_OC = oc;			break;
		case 29: P_E29_TRIS = tris;  P_E29_OC = oc;			break;
		case 30: P_E30_TRIS = tris;  P_E30_OC = oc;			break;
		case 31: P_E31_TRIS = tris;  P_E31_OC = oc; P_E31_ANALOG = ana;	break;
		case 32: P_E32_TRIS = tris;  P_E32_OC = oc; P_E31_ANALOG = ana;	break;
		case 33: P_E33_TRIS = tris;  P_E33_OC = oc;			break;
		case 34: P_E34_TRIS = tris;  P_E34_OC = oc;			break;
		case 35: P_E35_TRIS = tris;  P_E35_OC = oc; P_E31_ANALOG = ana; break;
		case 36: P_E36_TRIS = tris;  P_E36_OC = oc;			break;
		case 37: P_E37_TRIS = tris;  P_E37_OC = oc;			break;
		case 38: P_E38_TRIS = tris;  P_E38_OC = oc;			break;
		case 39: P_E39_TRIS = tris;  P_E39_OC = oc;			break;
            #else	// original by Geoff Graham for DuinoMite Mega
		case 19: //if (!S.VideoMode) {
                    P_E19_TRIS = tris; P_E19_OC = oc; P_E19_ANALOG = ana;//}
                break;
		case 20: if (!S.VideoMode || P_VGA_COMP) {P_E20_TRIS = tris; P_E20_OC = oc; P_E20_ANALOG = ana;} break;
		case 21: P_E21_TRIS = tris;  P_E21_OC = oc;  P_E21_ANALOG = ana;		break;
                case 22: P_E22_TRIS = tris;  P_E22_OC = oc; break;
                case 23: P_E23_TRIS = tris;  P_E23_OC = oc; break;
            #endif
            // SPP -
	#else
		case 19: P_E19_TRIS = tris;  P_E19_OC = oc;			break;
		case 20: P_E20_TRIS = tris;  P_E20_OC = oc;			break;
	#endif
	#ifdef UBW32
                case 21: P_E21_TRIS = tris;  P_E21_OC = oc;			break;
		case 22: P_E22_TRIS = tris;  P_E22_OC = oc;			break;
		case 23: P_E23_TRIS = tris;  P_E23_OC = oc;			break;
		case 24: P_E24_TRIS = tris;  P_E24_OC = oc;			break;
		case 25: P_E25_TRIS = tris;  P_E25_OC = oc;			break;
		case 26: P_E26_TRIS = tris;  P_E26_OC = oc;			break;
		case 27: P_E27_TRIS = tris;  P_E27_OC = oc;			break;
		case 28: P_E28_TRIS = tris;  P_E28_OC = oc;			break;
		case 29: P_E29_TRIS = tris;  P_E29_OC = oc;			break;
		case 30: P_E30_TRIS = tris;  P_E30_OC = oc;			break;
		case 31: P_E31_TRIS = tris;  P_E31_OC = oc;			break;
		case 32: P_E32_TRIS = tris;  P_E32_OC = oc;			break;
		case 33: P_E33_TRIS = tris;  P_E33_OC = oc;			break;
		case 34: P_E34_TRIS = tris;  P_E34_OC = oc;			break;
		case 35: P_E35_TRIS = tris;  P_E35_OC = oc;			break;
		case 36: P_E36_TRIS = tris;  P_E36_OC = oc;			break;
		case 37: P_E37_TRIS = tris;  P_E37_OC = oc;			break;
		case 38: P_E38_TRIS = tris;  P_E38_OC = oc;			break;
		case 39: P_E39_TRIS = tris;  P_E39_OC = oc;			break;
		case 40: P_E40_TRIS = tris;  P_E40_OC = oc;			break;
		case 41: P_E41_TRIS = tris;  P_E41_OC = oc;			break;
		case 42: P_E42_TRIS = tris;  P_E42_OC = oc;			break;
		case 43: P_E43_TRIS = tris;  P_E43_OC = oc;			break;
		case 44: P_E44_TRIS = tris;  P_E44_OC = oc;			break;
		case 45: P_E45_TRIS = tris;  P_E45_OC = oc;			break;
		case 46: P_E46_TRIS = tris;  P_E46_OC = oc;			break;
		case 47: P_E47_TRIS = tris;  P_E47_OC = oc;			break;
		case 48: P_E48_TRIS = tris;  P_E48_OC = oc;			break;
		case 49: P_E49_TRIS = tris;  P_E49_OC = oc;			break;
		case 50: P_E50_TRIS = tris;  P_E50_OC = oc;			break;
	#endif
	}

	if (cfg == EXT_NOT_CONFIG) ExtSet(pin, 0);						// set the default output to low
	return true;
}


/****************************************************************************************************************************
Set the output of a digital I/O pin
Returns true if all is OK
*****************************************************************************************************************************/
int ExtSet(int pin, int val){
	val = (val != 0);							// non zero is on
	INTDisableInterrupts();				// setting an output bit is NOT atomic and a bit set operation
																// in an interrupt could result in this set corrupting the output
	switch (pin) {
	#ifdef UBW32
		case 0:  P_LED_OUT = !val;  break;		// this is the LED - the UBW32 wired them upside down !!
	#else
		case 0:  P_LED_OUT = val;  break;			// this is the LED
	#endif
		case 1:  P_E1_OUT = val;   break;
		case 2:  P_E2_OUT = val;   break;
		case 3:  P_E3_OUT = val;   break;
		case 4:	 P_E4_OUT = val;   break;
		case 5:	 P_E5_OUT = val;   break;
		case 6:	 P_E6_OUT = val;   break;
		case 7:	 P_E7_OUT = val;   break;
	#ifdef OLIMEX
            #ifdef  OLIMEX_DUINOMITE_EMEGA
		case 8:	 P_E8_OUT = val;   break;
		case 9:	 P_E9_OUT = val;   break;
		case 10: P_E10_OUT = val;  break;
            #else
		case 8:	 if (!S.SDEnable) P_E8_OUT = val;   break;
		case 9:	 if (!S.SDEnable) P_E9_OUT = val;   break;
		case 10: if (!S.SDEnable) P_E10_OUT = val;  break;
            #endif
	#else
		case 8:	 P_E8_OUT = val;   break;
		case 9:	 P_E9_OUT = val;   break;
		case 10: P_E10_OUT = val;  break;
	#endif
		case 11: P_E11_OUT = val;  break;
		case 12: P_E12_OUT = val;  break;
		case 13: P_E13_OUT = val;  break;
		case 14: P_E14_OUT = val;  break;
		case 15: P_E15_OUT = val;  break;
		case 16: P_E16_OUT = val;  break;
		case 17: P_E17_OUT = val;  break;
		case 18: P_E18_OUT = val;  break;
	#ifdef OLIMEX
            #ifdef  OLIMEX_DUINOMITE_EMEGA
                case 19: P_E19_OUT = val; break;
                case 20: P_E20_OUT = val; break;
            #else
		case 19: P_E19_OUT = val;  break;
		case 20: if (!S.VideoMode || P_VGA_COMP) P_E20_OUT = val;  break;
                case 22: P_E22_OUT = val ; break;
                case 23: P_E23_OUT = val ; break;
            #endif
        #else
		case 19: P_E19_OUT = val;  break;
		case 20: P_E20_OUT = val;  break;
	#endif
        #if defined UBW32 || defined OLIMEX_DUINOMITE_EMEGA
		case 21: P_E21_OUT = val;	break;
		case 22: P_E22_OUT = val;	break;
		case 23: P_E23_OUT = val;	break;
		case 24: P_E24_OUT = val;	break;
		case 25: P_E25_OUT = val;	break;
		case 26: P_E26_OUT = val;	break;
		case 27: P_E27_OUT = val;	break;
		case 28: P_E28_OUT = val;	break;
		case 29: P_E29_OUT = val;	break;
		case 30: P_E30_OUT = val;	break;
		case 31: P_E31_OUT = val;	break;
		case 32: P_E32_OUT = val;	break;
		case 33: P_E33_OUT = val;	break;
		case 34: P_E34_OUT = val;	break;
		case 35: P_E35_OUT = val;	break;
		case 36: P_E36_OUT = val;	break;
		case 37: P_E37_OUT = val;	break;
		case 38: P_E38_OUT = val;	break;
		case 39: P_E39_OUT = val;	break;
        #endif
        #ifdef UBW32
		case 40: P_E40_OUT = val;	break;
		case 41: P_E41_OUT = val;	break;
		case 42: P_E42_OUT = val;	break;
		case 43: P_E43_OUT = val;	break;
		case 44: P_E44_OUT = val;	break;
		case 45: P_E45_OUT = val;	break;
		case 46: P_E46_OUT = val;	break;
		case 47: P_E47_OUT = val;	break;
		case 48: P_E48_OUT = val;	break;
		case 49: P_E49_OUT = val;	break;
		case 50: P_E50_OUT = val;	break;
	#endif
		default:
			INTEnableInterrupts();
			return false;
	}
	INTEnableInterrupts();
	return true;
}
Esempio n. 21
0
main()
{
    // Disable JTAG (on RA0 and RA1 )
    mJTAGPortEnable( DEBUG_JTAGPORT_OFF );

    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    initializeUART();
    initializeADC();
    initializeLCD();
    initializeRPG();
    
    /* Initialize SD card */
    setup_SDSPI();
    SD_setStart();
    /* Fill tempBuffer[] with int 0 to 63
     * Write it to the current block.
     * Empty tempBuffer[] to all 0.
     * Read from the current block to make sure that it returns the right value.
     */
    fillTempBuffer();
    testSDReadWrite(tempBuffer);

    curr_read_block = curr_block;
    
    ConfigTimer1(); // Enable Timer1 for second counts
    configureInterrupts();

    // T2CON = 0x8030; // TMR1 on, prescale 1:256 PB

    mPORTASetPinsDigitalOut( LED_MASK ); // LEDs = output
    mPORTDSetPinsDigitalIn( PB_MASK_D ); // PBs on D = input

    curr_state = READY;
    // enable interrupts
    INTEnableInterrupts();
    int i = 0;
    while( 1 )
    {
        if (getPrintToUARTFlag() == 1){
            LCDMenuControl();
        
            //mPORTAToggleBits( LED_MASK );
            convertAndPrintIntegerToString("i => ", i++);
            convertAndPrintIntegerToString("timeElapse => ", timeElapsed);
            convertAndPrintIntegerToString("timeElapsedLEDSample => ", timeElapsedLEDSample);
            convertAndPrintIntegerToString("timeElapsedLEDTurnedOff => ", timeElapsedLEDTurnedOff);
            convertAndPrintIntegerToString("sampleLEDNow => ", sampleLEDNow);

            convertAndPrintIntegerToString(" ADC Value => ", getChannel5Value());
            printShadowDetect();
            printLightLevel();
            drawLightDetectedBar();
            controlPowerRelay();

            switch(curr_state) {
            case READY : WriteString("State => READY     ");
                        break;
            case SLEEP : WriteString("State => SLEEP    ");
                        break;
            case HIBERNATE : WriteString("State => HIBERNATE");
                        break;
            case BUSY : WriteString("State => BUSY     ");
                        break;
            }

            WriteString("\r");
            
            setPrintToUARTFlag(0);
        }
        if (NEW_BYTE_RECEIVED == 1){
            curr_state = READY;
            NEW_BYTE_RECEIVED = 0;
            //mPORTAToggleBits( LED_MASK );
            char tempArray[] = "g";
            tempArray[0] = characterByteReceived;
            WriteString(tempArray);
            if(curr_state = HIBERNATE) {
                addByteToBuffer(characterByteReceived);
            }
            else {
                PutCharacter(characterByteReceived);
            }
        }
        if(bufferIndex == 512) {
            SDWriteBlock(currBlock);
            currBlock++;
            bufferIndex = 0;
        }
         if((curr_state == READY) && (timeElapsed >= SLEEP_TIMEOUT) && (timeElapsed < HIBERNATE_TIMEOUT)) {
             curr_state = SLEEP;
         }
         else if((curr_state == SLEEP) && (timeElapsed >= HIBERNATE_TIMEOUT)) {
             curr_state = HIBERNATE;
             timeElapsed = 0;
         }
        if (transmitDataFromSDCard == 1) {
            transmitDataFromSDCard = 0;
            forwardDataToPrinter();
        }
    } // main (while) loop

    return 0;

} // main
Esempio n. 22
0
/* main ***********************************************************************/
int main (void){
    CO_NMT_reset_cmd_t reset = CO_RESET_NOT;

    /* Configure system for maximum performance and enable multi vector interrupts. */
    SYSTEMConfig(CO_FSYS*1000, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();

    /* Disable JTAG and trace port */
    DDPCONbits.JTAGEN = 0;
    DDPCONbits.TROEN = 0;


    /* Verify, if OD structures have proper alignment of initial values */
    if(CO_OD_RAM.FirstWord != CO_OD_RAM.LastWord) while(1) ClearWDT();
    if(CO_OD_EEPROM.FirstWord != CO_OD_EEPROM.LastWord) while(1) ClearWDT();
    if(CO_OD_ROM.FirstWord != CO_OD_ROM.LastWord) while(1) ClearWDT();


    /* initialize EEPROM - part 1 */
#ifdef USE_EEPROM
    CO_ReturnError_t eeStatus = CO_EE_init_1(&CO_EEO, (uint8_t*) &CO_OD_EEPROM, sizeof(CO_OD_EEPROM),
                            (uint8_t*) &CO_OD_ROM, sizeof(CO_OD_ROM));
#endif


    programStart();


    /* increase variable each startup. Variable is stored in eeprom. */
    OD_powerOnCounter++;


    while(reset != CO_RESET_APP){
/* CANopen communication reset - initialize CANopen objects *******************/
        CO_ReturnError_t err;
        uint16_t timer1msPrevious;
        uint16_t TMR_TMR_PREV = 0;

        /* disable timer and CAN interrupts */
        CO_TMR_ISR_ENABLE = 0;
        CO_CAN_ISR_ENABLE = 0;
        CO_CAN_ISR2_ENABLE = 0;


        /* initialize CANopen */
        err = CO_init();
        if(err != CO_ERROR_NO){
            while(1) ClearWDT();
            /* CO_errorReport(CO->em, CO_EM_MEMORY_ALLOCATION_ERROR, CO_EMC_SOFTWARE_INTERNAL, err); */
        }


        /* initialize eeprom - part 2 */
#ifdef USE_EEPROM
        CO_EE_init_2(&CO_EEO, eeStatus, CO->SDO, CO->em);
#endif


        /* initialize variables */
        timer1msPrevious = CO_timer1ms;
        OD_performance[ODA_performance_mainCycleMaxTime] = 0;
        OD_performance[ODA_performance_timerCycleMaxTime] = 0;
        reset = CO_RESET_NOT;



        /* Configure Timer interrupt function for execution every 1 millisecond */
        CO_TMR_CON = 0;
        CO_TMR_TMR = 0;
        #if CO_PBCLK > 65000
            #error wrong timer configuration
        #endif
        CO_TMR_PR = CO_PBCLK - 1;  /* Period register */
        CO_TMR_CON = 0x8000;       /* start timer (TON=1) */
        CO_TMR_ISR_FLAG = 0;       /* clear interrupt flag */
        CO_TMR_ISR_PRIORITY = 3;   /* interrupt - set lower priority than CAN (set the same value in interrupt) */

        /* Configure CAN1 Interrupt (Combined) */
        CO_CAN_ISR_FLAG = 0;       /* CAN1 Interrupt - Clear flag */
        CO_CAN_ISR_PRIORITY = 5;   /* CAN1 Interrupt - Set higher priority than timer (set the same value in '#define CO_CAN_ISR_PRIORITY') */
        CO_CAN_ISR2_FLAG = 0;      /* CAN2 Interrupt - Clear flag */
        CO_CAN_ISR2_PRIORITY = 5;  /* CAN Interrupt - Set higher priority than timer (set the same value in '#define CO_CAN_ISR_PRIORITY') */


        communicationReset();


        /* start CAN and enable interrupts */
        CO_CANsetNormalMode(ADDR_CAN1);
        CO_TMR_ISR_ENABLE = 1;
        CO_CAN_ISR_ENABLE = 1;

#if CO_NO_CAN_MODULES >= 2
        CO_CANsetNormalMode(ADDR_CAN2);
        CO_CAN_ISR2_ENABLE = 1;
#endif


        while(reset == CO_RESET_NOT){
/* loop for normal program execution ******************************************/
            uint16_t timer1msCopy, timer1msDiff;

            ClearWDT();


            /* calculate cycle time for performance measurement */
            timer1msCopy = CO_timer1ms;
            timer1msDiff = timer1msCopy - timer1msPrevious;
            timer1msPrevious = timer1msCopy;
            uint16_t t0 = CO_TMR_TMR;
            uint16_t t = t0;
            if(t >= TMR_TMR_PREV){
                t = t - TMR_TMR_PREV;
                t = (timer1msDiff * 100) + (t / (CO_PBCLK / 100));
            }
            else if(timer1msDiff){
                t = TMR_TMR_PREV - t;
                t = (timer1msDiff * 100) - (t / (CO_PBCLK / 100));
            }
            else t = 0;
            OD_performance[ODA_performance_mainCycleTime] = t;
            if(t > OD_performance[ODA_performance_mainCycleMaxTime])
                OD_performance[ODA_performance_mainCycleMaxTime] = t;
            TMR_TMR_PREV = t0;


            /* Application asynchronous program */
            programAsync(timer1msDiff);

            ClearWDT();


            /* CANopen process */
            reset = CO_process(CO, timer1msDiff);

            ClearWDT();


#ifdef USE_EEPROM
            CO_EE_process(&CO_EEO);
#endif
        }
    }


/* program exit ***************************************************************/
    CO_DISABLE_INTERRUPTS();

    /* delete objects from memory */
    programEnd();
    CO_delete();

    /* reset */
    SoftReset();
}
Esempio n. 23
0
int main(void)
{
	int i, spi_timeout;
	unsigned long counter;

	/* Disable JTAG port so we get our I/O pins back */
	DDPCONbits.JTAGEN = 0;
	/* Enable optimal performance */
	SYSTEMConfigPerformance(GetSystemClock());
	/* Use 1:1 CPU Core:Peripheral clocks */
	OSCSetPBDIV(OSC_PB_DIV_1);

	/* configure the core timer roll-over rate */
	OpenCoreTimer(CORE_TICK_RATE);

	/* set up the core timer interrupt */
	mConfigIntCoreTimer((CT_INT_ON | CT_INT_PRIOR_6 | CT_INT_SUB_PRIOR_0));

	/* enable multi vector interrupts */
	INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
	INTEnableInterrupts();

	map_peripherals();
	init_io_ports();
	configure_pwm();
	init_spi();
	init_dma();

	/* wait until tx buffer is filled up */
	while (!SPI2STATbits.SPITBF);

	reset_board();
	spi_data_ready = 0;
	spi_timeout = 0;
	counter = 0;

	/* enable watchdog */
	WDTCONSET = 0x8000;

	/* main loop */
	while (1) {
		if (spi_data_ready) {
			spi_data_ready = 0;

			/* the first element received is a command string */
			switch (rxBuf[0]) {
			case 0x5453523E:	/* >RST */
				reset_board();
				break;
			case 0x314D433E:	/* >CM1 */
				stepgen_update_input((const void *)&rxBuf[1]);
				stepgen_get_position((void *)&txBuf[1]);
				break;
			case 0x324D433E:	/* >CM2 */
				update_outputs(rxBuf[1]);
				update_pwm_duty((uint32_t *)&rxBuf[2]);
				txBuf[1] = read_inputs();
				break;
			case 0x4746433E:	/* >CFG */
				stepgen_update_stepwidth(rxBuf[1]);
				update_pwm_period(rxBuf[2]);
				stepgen_reset();
				break;
			case 0x5453543E:	/* >TST */
				for (i=0; i<BUFSIZE; i++)
					txBuf[i] = rxBuf[i] ^ ~0;
				break;
			}
		}

		/* if rx buffer is half-full, update the integrity check.
		   There isn't enough time if we wait for complete transfer */
		if (DCH0INTbits.CHDHIF) {
			DCH0INTCLR = 1<<4;		/* clear flag */
			txBuf[0] = rxBuf[0] ^ ~0;
		}

		/* if rx buffer is full, data from spi bus is ready */
		if (DCH0INTbits.CHBCIF) {
			DCH0INTCLR = 1<<3;		/* clear flag */
			spi_data_ready = 1;
			spi_timeout = SPI_TIMEOUT;
		}

		/* reset the board if there is no SPI activity */
		if (spi_timeout)
			spi_timeout--;

		if (spi_timeout == 1) {				
			DCH0ECONSET=BIT_6;	/* abort DMA transfers */
			DCH1ECONSET=BIT_6;
		
			init_spi();
			init_dma();
			reset_board();

			/* wait until tx buffer is filled up */
			while (!SPI2STATbits.SPITBF);
		}

		/* blink onboard led */
		if (!(counter++ % (spi_timeout ? 0x10000 : 0x40000))) {
			LED_TOGGLE;
		}

		/* keep alive */
		WDTCONSET = 0x01;
	}
	return 0;
}
int main() {
    CFGCONbits.JTAGEN = 0; // turn off JTAG, get back those pins for IO use
    // set PIC32to max computing power
    DEBUGLED = 0;
    // enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();
    INTEnableInterrupts();
    PIC32MX250_setup_pins();
    SYSTEMConfigPerformance(SYS_FREQ);

    setTimer2(OUTPUT_FREQ); //
    setupTimer3(BUFFER_FREQ);
    initPWM(); //Initializing PWM on OC3.

    // Initialize texture buffer and index to zero

    int i;
    tBuff.Index = 0; //init to zero
    tBuff.On = 0; //turn off
    tBuff.Length0 = 0; //start with zero length
    tBuff.Length1 = 0; //start with zero length
    tBuff.Front = 0;
    for (i = 0; i < MAX_BUFFER_LENGTH; i++) {
        tBuff.Buff0[i] = 0; //init entire buffer to zero
        tBuff.Buff1[i] = 0; //init entire buffer to zero
    }


    // Initialize the USB host
    ConnectionInit();
    DEBUGLED = 1;

    //Main USB State Machine
    while (1) {
        // Keep the USB connection running;
        // Handle incoming data and manage outgoing data.
        ConnectionTasks();
        // Main state machine
        switch (state) {
            case STATE_INIT:

                state = STATE_WAITING;
                h = INVALID_CHANNEL_HANDLE;
                break;

            case STATE_WAITING:
                DEBUGLED = 0;
                if (ADBAttached()) {
                    state = STATE_CONNECTING;
                }
                break;

            case STATE_CONNECTING:

                if (ADBConnected()) {
                    // Open a channel to the Android device
                    // See "adb.h" in libadb for more details
                    // (I don't think the name tcp:4545 matters)
                    h = ADBOpen("tcp:4545", &ADBCallback);

                    if (h != INVALID_CHANNEL_HANDLE) {
                        state = STATE_CONNECTED;
                        WriteCoreTimer(0);
                        // Send plaintext and let the recipient do formatting
                        ADBWrite(h & 0xFF, "Hello from TPAD!", 17);
                    }
                }
                break;

            case STATE_CONNECTED:
                DEBUGLED = 1;

                if (!ADBAttached()) {
                    state = STATE_INIT;
                }
                if (ADBChannelReady(h)) {

                    // Execute tasks that rely on the Android-PIC32 connection
                    // Here we will just wait for messages to come in and be handled below
                }
                // Timeout timer. If the coretimer is not reset by a keepalive command from the Android, the PIC will reset the USB communications
                if (ReadCoreTimer() > 200000000) {
                    state = STATE_INIT;
                }

                break;
        } // end state machine
    } // end while loop

    return 0;
}
Esempio n. 25
0
void InitializeSystem() {

#ifdef BOARD_UBW32
    // Disable ADC port (allows PORTB to be used for digital I/O)
    AD1PCFG = 0xFFFF;

    TRISE = 0x0000;
    TRISB = 0x0000;
    TRISC = 0x0000;
    TRISD = 0x0000;
    LATE = 0x0000;
    LATB = 0x0000;
    LATC = 0x0000;
    LATD = 0x0000;
#endif
#ifdef BOARD_HEXLIGHT
    ANSELA = 0x0000;
    ANSELB = 0x0000;
#endif
    LATA = 0x0000;
    LATB = 0x0000;

    // Ensure LED drivers are driven low as soon as possible
//    _TRIS(PIO_OC1) = 0;
//    _TRIS(PIO_OC2) = 0;
//    _TRIS(PIO_OC3) = 0;
//    _TRIS(PIO_OC4) = 0;
//    _LAT(PIO_OC1) = OUTPUT;
//    _LAT(PIO_OC2) = OUTPUT;
//    _LAT(PIO_OC3) = OUTPUT;
//    _LAT(PIO_OC4) = OUTPUT;

    // Force disconnect of USB bootloader
    U1CON = 0x00000000;
    U1PWRC = 0x00000000;

    // LEDs
//    _TRIS(PIO_LED1) = OUTPUT;
//    _TRIS(PIO_LED2) = OUTPUT;
#ifdef BOARD_UBW32
    _TRIS(PIO_LED3) = OUTPUT;
    _TRIS(PIO_LED_USB) = OUTPUT;
    _TRIS(PIO_BTN_PGM) = 1;
    _TRIS(PIO_BTN_USR) = 1;
#elif BOARD_HEXLIGHT
    _TRIS(PIO_BTN1) = INPUT;
    _TRIS(PIO_BTN2) = INPUT;
#endif

//    _TRIS(PIO_USBP) = INPUT;
//    _TRIS(PIO_USBN) = INPUT;

//    _LAT(PIO_LED1) = LOW;
//    _LAT(PIO_LED2) = LOW;
#ifdef BOARD_UBW32
    _LAT(PIO_LED3) = HIGH;
    _LAT(PIO_LED_USB) = LOW;
#endif

    mJTAGPortEnable(0);

    // Initializethe PIC32 core
    //OSCConfig(OSC_POSC_PLL, OSC_PLL_MULT_20, OSC_PLL_POST_2, OSC_FRC_POST_2);
    sys_clock = F_SYSCLK;
    mOSCSetPBDIV(OSC_PB_DIV_1);
    pb_clock = SYSTEMConfig(sys_clock, SYS_CFG_ALL);


    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();

    // Initialize core time base
    SystickInit();
}
Esempio n. 26
0
int main(void)
{
    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    // Auto-configure the PIC32 for optimum performance at the specified operating frequency.
    SYSTEMConfigPerformance(SYS_FREQ);

    // osc source, PLL multipler value, PLL postscaler , RC divisor
    OSCConfig(OSC_POSC_PLL, OSC_PLL_MULT_20, OSC_PLL_POST_1, OSC_FRC_POST_1);

    // Configure the PB bus to run at 1/4 the CPU frequency
    OSCSetPBDIV(OSC_PB_DIV_4);

    // Enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();
    INTEnableInterrupts();

    // Set up the UART peripheral so we can send serial data.
    UARTConfigure(UART_USED, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART_USED, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART_USED, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART_USED, F_PB, UART_BAUD_RATE);
    UARTEnable(UART_USED, UART_ENABLE | UART_TX);

    // And configure printf/scanf to use the correct UART.
    if (UART_USED == UART1) {
        __XC_UART = 1;
    }

    // Enable LED outputs 0-7 by setting TRISE register
    TRISECLR = 0x00FF;
    // Initialize the PORTE to 0
    PORTECLR = 0x00FF;
    // Set the lowest bit
    int mask = 1;
    PORTESET = mask;
    int delay = 0xA0000;
    // Loop forever, it is bad to exit in an embedded processor.
    int count=0; // move this into the delay function
    while (1) {
        // Move this printf into your getDelay function!
        printf("Hello, world! %d\n",count++);
        // Replace this with the getDelay function call!

        //int delay = getDelay();

        // do nothing for a lot of cycles
        int i=0;
        for(i=0;i<delay;i++)
            ;
        // shift left by 1
        mask = mask << 1;
        // rotate around if more than 8 bits
        if (mask & 0x0100)
            mask = 1;
        // Set the output to the new mask
        PORTE=mask;

        delay = 0xA0000 + 0x40000*sin((double)count/10) + 0x20000*cos((double)count/5);

        if(delay < 0)
            delay *= -1;

    }
}
Esempio n. 27
0
// Main Application
int main(int argc, char** argv) {

    // Setup Main System
    SYSTEMConfigPerformance(80000000L);
    DDPCONbits.JTAGEN = 0;

    // Initialize System Pins
    initializeAllPins();

    // Initialize the Real Time Clock
    initializeRTCC();

    // Initialize Communication Systems
    initializeUART();

    // Configure for multi-vectored mode & Enable Interrupts
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableInterrupts();

    // Configure XBee
    xbee_baud.size = 1;     strcpy(xbee_baud.data, "6");
    xbee_channel.size = 2;  strcpy(xbee_channel.data, "15");
    xbee_network.size = 4;  strcpy(xbee_network.data, "3421");
    configureXBee(xbee_baud, xbee_channel, xbee_network);

    // Loop Infinitely
    while(1) {
        // Update Terminal Every Second, using the RTCC
        //while(!RtccGetSync());

        // Update Termina Every 300mS
        Delayms(200);



/*
        //Copy new GPS string to Globals
        if (gpsTempBuf.ready == 1) {

            // Copy GPS TempBuf to Sentence
            UINT8 gpsGGAPosition = 0;
            UINT8 ggaPosition = 0;

            int i = 0;
            for (i = 0; i < gpsTempBuf.size; i++) {
                gpsTempBuf.data[i] = gpsTempBuf.data[i];

                // Parse specific GPS Data
                if (gpsTempBuf.data[i] == ',') {
                    gpsGGAPosition++;
                    ggaPosition = 0;
                }

                char temp[1] = { gpsTempBuf.data[i] };
                if (gpsTempBuf.data[i] != ',') {
                    switch(gpsGGAPosition) {
                        case 1:
                            gpsBaseCurrent.time.data[ggaPosition] = gpsTempBuf.data[i];
                            gpsBaseCurrent.time.size++;
                            ggaPosition++;
                            break;
                        case 2:
                            gpsBaseCurrent.Latitude.data[ggaPosition] = gpsTempBuf.data[i];
                            gpsBaseCurrent.Latitude.size++;
                            ggaPosition++;
                            break;
                        case 3:
                            gpsBaseCurrent.Longitude.data[ggaPosition] = gpsTempBuf.data[i];
                            gpsBaseCurrent.Longitude.size++;
                            ggaPosition++;
                            break;
                        case 4:
                            gpsBaseCurrent.Fix = atoi(temp);
                            ggaPosition++;
                            break;
                        case 5:
                            gpsBaseCurrent.NumSatellites = atoi(temp);
                            ggaPosition++;
                            break;
                        case 6:
                            gpsBaseCurrent.HorizontalDilution.data[ggaPosition] = gpsTempBuf.data[i];
                            gpsBaseCurrent.HorizontalDilution.size++;
                            ggaPosition++;
                            break;
                        case 7:
                            gpsBaseCurrent.Altitude.data[ggaPosition] = gpsTempBuf.data[i];
                            gpsBaseCurrent.Altitude.size++;
                            ggaPosition++;
                            break;
                        case 8:
                            gpsBaseCurrent.HeightOfGeoid.data[ggaPosition] = gpsTempBuf.data[i];
                            gpsBaseCurrent.HeightOfGeoid.size++;
                            ggaPosition++;
                            break;
                        default:
                            break;
                    }
                }
            }

            // Update System Time
            DFloat currentTime;
            currentTime.timeBytes.RSV = 0x0000;
            currentTime.timeBytes.HU = gpsBaseCurrent.time.data[0];
            currentTime.timeBytes.HL = gpsBaseCurrent.time.data[1];
            currentTime.timeBytes.MU = gpsBaseCurrent.time.data[2];
            currentTime.timeBytes.ML = gpsBaseCurrent.time.data[3];
            currentTime.timeBytes.SU = gpsBaseCurrent.time.data[4];
            currentTime.timeBytes.SL = gpsBaseCurrent.time.data[5];
            RtccSetTimeDate(currentTime.UValue, 0);
        }
 */
  /*
        // Perform Magnetometer Calculations
            float tempMX = (float) compassCurrent.Signed.X;
            tempMX *= magGain[1] / 1000;

            float tempMY = (float) compassCurrent.Signed.Y;
            tempMY *= magGain[1] / 1000;

            float tempMZ = (float) compassCurrent.Signed.Z;
            tempMZ *= magGain[1] / 1000;

            // Create Unit Vectors
            float totalM = sqrtf(powf(tempMX,2) + powf(tempMY,2) + powf(tempMZ,2));
            tempMX /= totalM;
            tempMY /= totalM;
            tempMZ /= totalM;
*/

            // Convert to Degrees
            //tempMX = acosf(tempMX) * degrees_per_radian;
            //tempMY = acosf(tempMY) * degrees_per_radian;
            //tempMZ = acosf(tempMZ) * degrees_per_radian;

            // Match Current Angle with Calculated
            //sprintf(buf, "%04d X(%+07.2f, %5.3f) Y(%+07.2f, %5.3f) Z(%+07.2f, %5.3f) %02dmS %02dC \r\n", outputs, angleCurrent.X.Value, tempMX, angleCurrent.Y.Value, tempMY, angleCurrent.Z.Value, tempMZ, angleCurrent.T, gyroCurrent.TU);


            
            sprintf(buf, "%04d X(%+07.2f, %4d)\tY(%+07.2f, %4d)\tZ(%+07.2f, %4d)\tA(%3d, %4d)\tPWM(%3d, %3d, %3d, %3d) \r\n", outputs, angleCurrent.X.Value, errorReading[0], angleCurrent.Y.Value, errorReading[1], angleCurrent.Z.Value, errorReading[2], altitudeReading[0], errorReading[3], pwmReading[0], pwmReading[1], pwmReading[2], pwmReading[3]);
            outputs++;

            // Working, Shows Gyroscope Calculated Angles!
            //sprintf(buf, "Gyro: %+08.3f, %+08.3f, %+08.3f\r\n", tempX, tempY, tempZ);

            // Get Current Time
            //tempTime.l=RtccGetTime();

            // Format String
            //sprintf(buf, "Gyro: %07f, %07f, %07f | Acl: %07.3f, %07.3f, %07.3f | Ang: %03.3f, %03.3f, %03.3f | UT: %02d mS | BST: %02x:%02x:%02x | FCT: %02x:%02x:%02x\r\n", tempX, tempY, tempZ, accelCurrent.X, accelCurrent.Y, accelCurrent.Z, angleCurrent.X.Value, angleCurrent.Y.Value, angleCurrent.Z.Value, angleCurrent.T, tempTime.hour, tempTime.min, tempTime.sec, timeFCBCurrent.hour, timeFCBCurrent.min, timeFCBCurrent.sec);

            // Place on Bluetooth
            putsBluetooth(buf, strlen(buf));
    }

    return (EXIT_SUCCESS);
}
Esempio n. 28
0
/***	UpdateMotorControl
**
**	Synopsis:
**		PutChUart1(ch)
**
**	Parameters:
**		posX - x position of the right joystick
**		posY - y position of the right joystick
**
**	Return Values:
**		none
**
**	Errors:
**		none
**
**	Description:
**		This routine will update the motor controller based on the
**		current X and Y position of the right joystick of the controller.
*/
void UpdateMotorControl( HWORD posX, HWORD posY )
{
	static	HWORD	tusMtrLeftDcSav		= dtcMtrStopped;	// stopped
	static	HWORD	tusMtrRightDcSav	= dtcMtrStopped;	// stopped
	static	BYTE	dirMtrLeftSav		= dirMtrLeftFwd;
	static	BYTE	dirMtrRightSav		= dirMtrRightFwd;
			HWORD	tusMtrLeftFbNew;
			HWORD	tusMtrRightFbNew;
	
	// Determine motor direction and speed based on joystick position.
	if ( posYMax < posY ) {
		if ( posXMax < posX ) {
			// Go forward and left.
			MtrCtrlFwdLeft();
		}
		else if ( posXMin > posX ) {
			// Go backward and left.
			MtrCtrlBwdLeft();
		}
		else {
			// Go left.
			MtrCtrlLeft();
		}
	}
	else if ( posYMin > posY ) {
		if ( posXMax < posX ) {
			// Go forward and right.
			MtrCtrlFwdRight();
		}
		else if ( posXMin > posX ) {
			// Go backward and right.
			MtrCtrlBwdRight();
		}
		else {
			// Go right.
			MtrCtrlRight();
		}
	}
	else {
		if ( posXMax < posX ) {
			// Go forward.
			MtrCtrlFwd();
		}
		else if ( posXMin > posX ) {
			// Go backward.
			MtrCtrlBwd();
		}
		else {
			MtrCtrlStop();
			// Stop.
		}
	}
	
	// Update left motor speed if necessary.
	if ( tusMtrLeftDcSav != dtcMtrLeft ) {
		
		// 1. disable left motor feedback.
		INTDisableInterrupts();
		fMtrLeftFb	= fFalse;
		INTEnableInterrupts();
		
		if ( dtcMtrStopped != dtcMtrLeft ) {
			// 3. update left motor feedback
			tusMtrLeftFb = tusMtrLeftFbNew;
			
			// 4. re-enable left motor feedback.
			INTDisableInterrupts();
			fMtrLeft	= fFalse;
			fMtrLeftFb	= fTrue;
			INTEnableInterrupts();
			
			// 5. enable feedback watchdog
			T1CONSET = ( 1 << 15 );
		}
		else {
			
			// 2. update left motor duty cycle.
			OC1RS = dtcMtrLeft;
			
			// Disable feedback watchdog.
			T1CONCLR 	= ( 1 << 15 );
			TMR1		= 0;
			IFS0CLR		= ( 1 << 4 );
		}
		
		tusMtrLeftDcSav = dtcMtrLeft;
	}
	
	// Update right motor speed if necessary.
	if ( tusMtrRightDcSav != dtcMtrRight ) {
		
		// 1. disable right motor feedback.
		INTDisableInterrupts();
		fMtrRightFb	= fFalse;
		INTEnableInterrupts();
		
		if ( dtcMtrStopped != dtcMtrRight ) {
			// 3. update right motor feedback.
			tusMtrRightFb = tusMtrRightFbNew;
			
			// 4. re-enable right motor feedback.
			INTDisableInterrupts();
			fMtrRight	= fFalse;
			fMtrRightFb	= fTrue;
			INTEnableInterrupts();
			
			// 5. enable feedback watchdog
			T1CONSET = ( 1 << 15 );
		}
		else {
			
			// 2. update right motor duty cycle.
			OC4RS = dtcMtrRight;
		}
		
		tusMtrRightDcSav = dtcMtrRight;
	}
	
	// Update left motor direction if necessary.
	if ( dirMtrLeftSav != dirMtrLeft ) {
		
		OC1CONCLR	= ( 1 << 15 );	// Disable output compare module 1
									// to release I/O pin control of enable
									// signal.
									
		trisMtrLeftEnClr	= ( 1 << bnMtrLeftEn );	// Set enable pin as a digital output.
		prtMtrLeftEnClr		= ( 1 << bnMtrLeftEn ); // Drive enable pin low.
									
		if ( dirMtrLeftFwd	== dirMtrLeft ) {
			prtMtrLeftDirSet = ( 1 << bnMtrLeftDir );
		}
		else {
			prtMtrLeftDirClr = ( 1 << bnMtrLeftDir );
		}
									
		OC1CONSET	= ( 1 << 15 );	// Re-enable output compare module 1.
		dirMtrLeftSav = dirMtrLeft;	// Save the current direction of the
									// left motor.
	}
	
	// Update right motor direction if necessary.
	if ( dirMtrRightSav != dirMtrRight ) {
		OC4CONCLR	= ( 1 << 15 );	// Disable output compare module 4
									// to release I/O pin control of enable
									// signal.
									
		trisMtrRightEnClr	= ( 1 << bnMtrRightEn ); // Set enable pin as a digital output.
		prtMtrRightEnClr	= ( 1 << bnMtrRightEn ); // Drive enable pin low.
		
		if ( dirMtrRightFwd == dirMtrRight ) {
			prtMtrRightDirClr = ( 1 << bnMtrRightDir );
		}
		else {
			prtMtrRightDirSet = ( 1 << bnMtrRightDir );
		}
									
		OC4CONSET	= ( 1 << 15 );	// Re-enable output compare module 4.
		
		dirMtrRightSav = dirMtrRight;	// Save the current direciton of the
										// right motor.
	}
}
int main(void)
{
//LOCALS
	unsigned int temp;
	unsigned int channel1, channel2;
	M1_stepPeriod = M2_stepPeriod = M3_stepPeriod = M4_stepPeriod = 50; // in tens of u-seconds
	unsigned char M1_state = 0, M2_state = 0, M3_state = 0, M4_state = 0;

	SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

/* TIMER1 - now configured to interrupt at 10 khz (every 100us) */
	OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_1, T1_TICK);
	ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_2);
/* TIMER2 - 100 khz interrupt for distance measure*/
	OpenTimer2(T2_ON | T2_SOURCE_INT | T2_PS_1_1, T2_TICK);
	ConfigIntTimer2(T2_INT_ON | T2_INT_PRIOR_3); //It is off until trigger

/* PORTA b2 and b3 for servo-PWM */
	mPORTAClearBits(BIT_2 | BIT_3);
	mPORTASetPinsDigitalOut(BIT_2 | BIT_3);

/* ULTRASONICS: some bits of PORTB for ultrasonic sensors */
	PORTResetPins(IOPORT_B, BIT_8 | BIT_9| BIT_10 | BIT_11 );	
	PORTSetPinsDigitalOut(IOPORT_B, BIT_8 | BIT_9| BIT_10 | BIT_11); //trigger
/* Input Capture pins for echo signals */
	//interrupt on every risging/falling edge starting with a rising edge
	PORTSetPinsDigitalIn(IOPORT_D, BIT_8| BIT_9| BIT_10| BIT_11); //INC1, INC2, INC3, INC4 Pin
	mIC1ClearIntFlag();
	OpenCapture1(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//front
	ConfigIntCapture1(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);
	OpenCapture2(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//back
	ConfigIntCapture2(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);
	OpenCapture3(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//left
	ConfigIntCapture3(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);
	OpenCapture4(  IC_EVERY_EDGE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON );//right
	ConfigIntCapture4(IC_INT_ON | IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);

/* PINS used for the START (RD13) BUTTON */
    PORTSetPinsDigitalIn(IOPORT_D, BIT_13);
	#define CONFIG          (CN_ON | CN_IDLE_CON)
	#define INTERRUPT       (CHANGE_INT_ON | CHANGE_INT_PRI_2)
	mCNOpen(CONFIG, CN19_ENABLE, CN19_PULLUP_ENABLE);
	temp = mPORTDRead();

/* PORT D and E for motors */
	//motor 1
	mPORTDSetBits(BIT_4 | BIT_5 | BIT_6 | BIT_7); 		// Turn on PORTD on startup.
	mPORTDSetPinsDigitalOut(BIT_4 | BIT_5 | BIT_6 | BIT_7);	// Make PORTD output.
	//motor 2
	mPORTCSetBits(BIT_1 | BIT_2 | BIT_3 | BIT_4); 		// Turn on PORTC on startup.
	mPORTCSetPinsDigitalOut(BIT_1 | BIT_2 | BIT_3 | BIT_4);	// Make PORTC output.
	//motor 3 and 4
	mPORTESetBits(BIT_0 | BIT_1 | BIT_2 | BIT_3 |
					BIT_4 | BIT_5 | BIT_6 | BIT_7); 		// Turn on PORTE on startup.
	mPORTESetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 | BIT_3 |
					BIT_4 | BIT_5 | BIT_6 | BIT_7);	// Make PORTE output.

// UART2 to connect to the PC.
	// This initialization assumes 36MHz Fpb clock. If it changes,
	// you will have to modify baud rate initializer.
    UARTConfigure(UART2, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART2, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART2, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART2, GetPeripheralClock(), BAUD);
    UARTEnable(UART2, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_RX | UART_TX));
	// Configure UART2 RX Interrupt
	INTEnable(INT_SOURCE_UART_RX(UART2), INT_ENABLED);
    INTSetVectorPriority(INT_VECTOR_UART(UART2), INT_PRIORITY_LEVEL_2);
    INTSetVectorSubPriority(INT_VECTOR_UART(UART2), INT_SUB_PRIORITY_LEVEL_0);


/* PORTD for LEDs - DEBUGGING */
	mPORTDClearBits(BIT_0 | BIT_1 | BIT_2);
	mPORTDSetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2);

	

// Congifure Change/Notice Interrupt Flag
	ConfigIntCN(INTERRUPT);
// configure for multi-vectored mode
    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
// enable interrupts
    INTEnableInterrupts();


	counterDistanceMeasure=600; //measure ULTRASONICS distance each 60 ms

	while (1) {
	
/***************** Robot MAIN state machine *****************/
		unsigned char ret = 0;
		switch (Robo_State) {
			case 0:
				MotorsON = 0;
				Robo_State = 0;

				InvInitialOrientation(RESET);
				TestDog(RESET);
				GoToRoom4short(RESET);
				BackToStart(RESET);
				InitialOrientation(RESET);
				GoToCenter(RESET);
				GoToRoom4long(RESET);
				break;
			case 1:
				ret = InvInitialOrientation(GO);
				if (ret == 1) {
					Robo_State = 2;
				}
				break;
			case 2:
				ret = TestDog(GO);
				if (ret == 1) {
					Robo_State = 3;		//DOG not found
				} else if (ret == 2) {
					Robo_State = 4;		//DOG found
				}
				break;
			case 3:
				ret = GoToRoom4short(GO);
				if (ret == 1) {
					Robo_State = 0;
				}
				break;
			case 4:
				ret = BackToStart(GO);
				if (ret == 1) {
					Robo_State = 5;
				}
				break;
			case 5:
				ret = GoToCenter(GO);
				if (ret == 1) {
					Robo_State = 6;
				}
				break;
			case 6:
				ret = GoToRoom4long(GO);
				if (ret == 1) {
					Robo_State = 0;
				}
				break;
		}

		if (frontDistance < 30 || backDistance < 30 || leftDistance < 30 || rightDistance < 30)
			mPORTDSetBits(BIT_0);
		else 
			mPORTDClearBits(BIT_0);
/***************************************************************/


/***************** Motors State Machine ************************/

		if (MotorsON) {
			/****************************
			MOTOR MAP
				M1 O-------------O M2   ON EVEN MOTORS, STEPS MUST BE INVERTED
					|	 /\		|			i.e. FORWARD IS BACKWARD
					|	/  \	|
					|	 || 	|
					|	 ||		|
				M3 O-------------O M4
			*****************************/
			if (M1_counter == 0) {
				switch (M1_state) {
					case 0: // set 0011
						step (0x3 , 1);
						if (M1forward)
							M1_state = 1;
						else
							M1_state = 3;
						break;
					case 1: // set 1001
						step (0x9 , 1);
						if (M1forward)
							M1_state = 2;
						else
							M1_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 1);
						if (M1forward)
							M1_state = 3;
						else
							M1_state = 1;
						break;
					case 3: // set 0110
					default:
						step (0x6 , 1);
						if (M1forward)
							M1_state = 0;
						else
							M1_state = 2;
						break;	
				}
				M1_counter = M1_stepPeriod;
				step_counter[0]--;
				if (directionNow == countingDirection)
					step_counter[1]--;
			}
			
			if (M2_counter == 0) {
				switch (M2_state) {
					case 0: // set 0011
						step (0x3 , 2);
						if (M2forward)
							M2_state = 1;
						else
							M2_state = 3;
						break;
					case 1: // set 0110
						step (0x6 , 2);
						if (M2forward)
							M2_state = 2;
						else
							M2_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 2);
						if (M2forward)
							M2_state = 3;
						else
							M2_state = 1;
						break;
					case 3: // set 1001
					default:
						step (0x9 , 2);
						if (M2forward)
							M2_state = 0;
						else
							M2_state = 2;
						break;	
				}
				M2_counter = M2_stepPeriod;
			}

			if (M3_counter == 0) {
				switch (M3_state) {
					case 0: // set 0011
						step (0x3 , 3);
						if (M3forward)
							M3_state = 1;
						else
							M3_state = 3;
						break;
					case 1: // set 1001
						step (0x9 , 3);
						if (M3forward)
							M3_state = 2;
						else
							M3_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 3);
						if (M3forward)
							M3_state = 3;
						else
							M3_state = 1;
						break;
					case 3: // set 0110
					default:
						step (0x6 , 3);
						if (M3forward)
							M3_state = 0;
						else
							M3_state = 2;
						break;	
				}
				M3_counter = M3_stepPeriod;
			}
			
			if (M4_counter == 0) {
				switch (M4_state) {
					case 0: // set 0011
						step (0x3 , 4);
						if (M4forward)
							M4_state = 1;
						else
							M4_state = 3;
						break;
					case 1: // set 0110
						step (0x6 , 4);
						if (M4forward)
							M4_state = 2;
						else
							M4_state = 0;
						break;
					case 2: // set 1100
						step (0xC , 4);
						if (M4forward)
							M4_state = 3;
						else
							M4_state = 1;
						break;
					case 3: // set 1001
					default:
						step (0x9 , 4);
						if (M4forward)
							M4_state = 0;
						else
							M4_state = 2;
						break;	
				}
				M4_counter = M4_stepPeriod;
			}
		} else {
			//motors off
			mPORTDSetBits(BIT_4 | BIT_5 | BIT_6 | BIT_7);
			mPORTCSetBits(BIT_1 | BIT_2 | BIT_3 | BIT_4);
			mPORTESetBits(BIT_0 | BIT_1 | BIT_2 | BIT_3 |
					BIT_4 | BIT_5 | BIT_6 | BIT_7);
		}
/************************************************************/
		

/******* TEST CODE, toggles the servos (from 90 deg. to -90 deg.) every 1 s. ********/
/*		if (auxcounter == 0) {
			
			servo1_angle = 0;

			if (servo2_angle == 90)
				servo2_angle = -90;
			else
				servo2_angle = 90;

			auxcounter = 20000;		// toggle angle every 2 s.
		}
*/

		servo1_angle = 0;
		servo2_angle = -90;
	/*
		if (frontDistance > 13 && frontDistance < 17) {
			servo2_angle = 90;
		}
		else
			servo2_angle = -90;
	*/
/*******************************************************************/


/****************** SERVO CONTROL ******************/
		/*
			Changing the global servoX_angle at any point in the code will 
			move the servo to the desired angle.
		*/
		servo1_counter = (servo1_angle + 90)*(18)/180 + 6; // between 600 and 2400 us
		if (servo1_period == 0) {
			mPORTASetBits(BIT_2);
			servo1_period = SERVOMAXPERIOD; 		/* 200 * 100us = 20000us period  */
		}

		servo2_counter = (servo2_angle + 90)*(18)/180 + 6; // between 600 and 2400 us
		if (servo2_period == 0) {
			mPORTASetBits(BIT_3);
			servo2_period = SERVOMAXPERIOD; 		/* 200 * 100us = 20000us period  */
		}
/*****************************************************/
	
	} /* end of while(1)  */
		
	return 0;
}
Esempio n. 30
0
File: part1.c Progetto: DC11011100/C
int main(void)
{
    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    // Auto-configure the PIC32 for optimum performance at the specified operating frequency.
    SYSTEMConfigPerformance(SYS_FREQ);

    // osc source, PLL multipler value, PLL postscaler , RC divisor
    OSCConfig(OSC_POSC_PLL, OSC_PLL_MULT_20, OSC_PLL_POST_1, OSC_FRC_POST_1);

    // Configure the PB bus to run at 1/4 the CPU frequency
    OSCSetPBDIV(OSC_PB_DIV_4);

    // Enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();
    INTEnableInterrupts();

    // Set up the UART peripheral so we can send serial data.
    UARTConfigure(UART_USED, UART_ENABLE_PINS_TX_RX_ONLY);
    UARTSetFifoMode(UART_USED, UART_INTERRUPT_ON_TX_NOT_FULL | UART_INTERRUPT_ON_RX_NOT_EMPTY);
    UARTSetLineControl(UART_USED, UART_DATA_SIZE_8_BITS | UART_PARITY_NONE | UART_STOP_BITS_1);
    UARTSetDataRate(UART_USED, F_PB, UART_BAUD_RATE);
    UARTEnable(UART_USED, UART_ENABLE | UART_TX);

    // And configure printf/scanf to use the correct UART.
    if (UART_USED == UART1) {
        __XC_UART = 1;
    }
    
    // Initialize the array
    char seed1[] = __TIME__;
    unsigned int seed2 = (((unsigned int)(seed1[7] ^ seed1[2])) << 8) | ((unsigned int)(seed1[4] ^ seed1[6]));
    srand(seed2);
    unsigned char vals[] = { rand(), rand(), rand(), rand(), rand() };
    int valsToBeSorted[] = {vals[0], vals[1], vals[2], vals[3], vals[4]};
    
    // Sort the array in place.
    int i, j;
    for (i = 0; i < 5; ++i)
    {
            int aTemp = valsToBeSorted[i];
            for (j = i - 1; j >= 0; j--) {
                    if (valsToBeSorted[j] <= aTemp)
                        break;
                    valsToBeSorted[j + 1] = valsToBeSorted[j];
            }
            valsToBeSorted  [j+1]   =   aTemp;
    }

    // Print out the array
    printf("[");
    for (i=0;i<4;++i) {
        printf("%d, ", valsToBeSorted[i]);
    }
    printf("%d]\n", valsToBeSorted[i]);

    /*
     * Returning from main() is bad form in embedded environments. So we
     * sit and spin.
     */
    while (1);
}