Ejemplo n.º 1
0
int main(void)
{
    while(1)
    {
		previousSpriteState = spriteState;
        pollKeys();
		enableSounds();
		setupInterrupts();


		switch(state)
		{
			case SPLASH:
			{
				REG_DISPCNTL = BG2_ENABLE | MODE3;
				fillPicture((u16 *)splashBitmap);

				if (BUTTON_PRESSED(START_BUTTON))
				{
					state = GAME;
				}
				if (BUTTON_PRESSED(SELECT_BUTTON))
				{
					state = INSTRUCTIONS;
				}
			break;
			}

			case INSTRUCTIONS:
			{
				fillPicture((u16 *)instructionsBitmap);
				if (BUTTON_PRESSED(SELECT_BUTTON))
				{
					state = SPLASH;
				}
				break;
			}
			
			case GAME:
			{

				//load tiles
				DMA_MEMORY[3].source = backgroundTiles;
				DMA_MEMORY[3].destination = &CHARBLOCK[0];
				DMA_MEMORY[3].control = 12000 | DMA_ON;

				//load map
				DMA_MEMORY[3].source = backgroundMap;
				DMA_MEMORY[3].destination = &SCREENBLOCK[27];
				DMA_MEMORY[3].control = 4096 | DMA_ON;

				//load pallette
				DMA_MEMORY[3].source = backgroundPal;
				DMA_MEMORY[3].destination = PAL_MEM;
				DMA_MEMORY[3].control = 256 | DMA_ON;


				//load the sprites into memory
				DMA_MEMORY[3].source = playerTiles;
				DMA_MEMORY[3].destination = &CHARBLOCK[4];
				DMA_MEMORY[3].control = 16384 | DMA_ON;

				DMA_MEMORY[3].source = playerPal;
				DMA_MEMORY[3].destination = SPRITE_PALETTE;
				DMA_MEMORY[3].control = 256 | DMA_ON;
			    
			    
				//Hide all sprites
				int i;
				for(i=0; i<128; i++)
				{
					OAM[i].attr0 |= ATTR0_HIDE;
				}

				//Set Mode 0 BG 0 and Enable sprites. then set up the sprites
				REG_DISPCNTL = MODE0 | BG0_ENABLE | SPRITE_ENABLE;
				REG_BG0CNT = BG_8BPP | BG_REG_64x64 | CBB(0) | SBB(27);

				REG_TM0CNT = 0;
				DMA[1].cnt = 0;

				REG_TM0D   = timerintervalA;       
				REG_TM0CNT = TIMER_ON;

				DMA[1].src = bgsound;
				DMA[1].dst = REG_FIFO_A;
				DMA[1].cnt = DMA_ON | START_ON_FIFO_EMPTY |
							 DMA_32 | DMA_REPEAT |
							 DMA_DESTINATION_FIXED;

				startA = vblankcountA;

				while(1){

					shadowOAM[0].attr0 = (playerRow & MASKROW) | ATTR0_TALL | ATTR0_REGULAR | ATTR0_8BPP;
					shadowOAM[0].attr1 = (playerCol & MASKCOL)| ATTR1_SIZE32;
					shadowOAM[0].attr2 = (SPRITEOFFSET16(0,0));

					shadowOAM[1].attr0 = badguyRow | ATTR0_TALL | ATTR0_REGULAR | ATTR0_8BPP;
					shadowOAM[1].attr1 = badguyCol | ATTR1_SIZE32;
					shadowOAM[1].attr2 = (SPRITEOFFSET16(0,8));

					pollKeys();
					bigRow = playerRow + vOff;
					bigCol = playerCol + hOff;

				switch(spriteState)
				{
					case STILL:
					{
						shadowOAM[0].attr2 = (SPRITEOFFSET16(0,0));
						break;
					}

					case MOVING:
					{
						if((walkCounter%2)==1)
							shadowOAM[0].attr2 = (SPRITEOFFSET16(0,4));
						else if((walkCounter%2==0))
						{
						shadowOAM[0].attr2 = (SPRITEOFFSET16(0,0)); 
						}
						break;
					}

				}	
				

					if(BUTTON_HELD(A_BUTTON) && BUTTON_HELD(B_BUTTON))
					{
						//load tiles
						DMA_MEMORY[3].source = cheatbackgroundTiles;
						DMA_MEMORY[3].destination = &CHARBLOCK[0];
						DMA_MEMORY[3].control = 11456 | DMA_ON;

						//load map
						DMA_MEMORY[3].source = cheatbackgroundMap;
						DMA_MEMORY[3].destination = &SCREENBLOCK[27];
						DMA_MEMORY[3].control = 4096 | DMA_ON;

						//load pallette
						DMA_MEMORY[3].source = cheatbackgroundPal;
						DMA_MEMORY[3].destination = PAL_MEM;
						DMA_MEMORY[3].control = 256 | DMA_ON;
					}
					if (BUTTON_HELD(RIGHT_BUTTON))
					{
						spriteState=MOVING;
						walkCounter++;
						if(collisionmapBitmap[((bigRow+playerHeight)*collMapSize)+(bigCol+playerCVel+playerWidth)]==WHITE)
						{
							if(playerCol<(SCREEN_WIDTH-(playerWidth+5))){
								playerCol+=playerCVel;
							}
							else if(hOff<(collMapSize-SCREEN_WIDTH))
							{
								hOff+=playerCVel;
							}
						}
					}
					if (BUTTON_HELD(LEFT_BUTTON))
					{
						spriteState=MOVING;
						walkCounter++;
						if(collisionmapBitmap[((bigRow+playerHeight)*collMapSize)+(bigCol+playerCVel)]==WHITE)
						{
							if(playerCol>(0))
							{
								playerCol-=playerCVel;
							}
							else if(hOff>(SCREEN_WIDTH-collMapSize))
							{
								hOff-=playerCVel;
							}
						}
					}
					if (BUTTON_HELD(UP_BUTTON))
					{
						spriteState=MOVING;
						walkCounter++;
						//Check collision and move
						if((collisionmapBitmap[(((bigRow-playerRVel)*collMapSize)+(bigCol+playerWidth))]==WHITE)&&
							(collisionmapBitmap[(((bigRow-playerRVel)*collMapSize)+(bigCol))]==WHITE))
						{
							if(playerRow>30)
							{
								playerRow-=playerRVel;
							}
							else if(vOff>0)
							{
								vOff-=playerRVel;
							}
						}
						
					}
					if (BUTTON_HELD(DOWN_BUTTON))
					{
						spriteState=MOVING;
						walkCounter++;
						//Check collision and move
						if((collisionmapBitmap[(((bigRow+playerHeight+playerRVel)*collMapSize)+(bigCol+playerWidth))]==WHITE)&&
							(collisionmapBitmap[(((bigRow+playerHeight+playerRVel)*collMapSize)+(bigCol))]==WHITE))
						{

							if(playerRow<(SCREEN_HEIGHT-(playerHeight)))
							{
								playerRow+=playerRVel;
							}
							else if(vOff<(collMapSize-SCREEN_HEIGHT))
							{
								vOff+=playerRVel;
							}
						if((playerRow > 440) && (playerCol > 464))
						{
							state = WIN;
						}
						}


					}
					if (BUTTON_PRESSED(START_BUTTON))
					{
							REG_TM1CNT = 0;
							DMA[2].cnt = 0;
						
							REG_TM1D   = timerintervalB;       
							REG_TM1CNT = TIMER_ON;

							DMA[2].src = bark;
							DMA[2].dst = REG_FIFO_B;
							DMA[2].cnt = DMA_ON | START_ON_FIFO_EMPTY |
										 DMA_32 | DMA_REPEAT |
										 DMA_DESTINATION_FIXED;

							startB = vblankcountB;
					}
					if (BUTTON_PRESSED(SELECT_BUTTON))
					{
						//waitForNoKey();
						state = PAUSE;
					}
					
					waitForVBlank();
					OAM[0] = shadowOAM[0];
					OAM[1] = shadowOAM[1];

					REG_BG0HOFS = hOff;
					REG_BG0VOFS = vOff;

				}

			}

				case WIN:
				{
					while(1);
				}

				case PAUSE:
				{
					if(BUTTON_PRESSED(SELECT_BUTTON))
					{
						state=GAME;
					}
				}

		}

	}

    return 0;
}
Ejemplo n.º 2
0
//*****************************************************************************
//
// The interrupt handler for the PB4 pin interrupt.  When triggered, this will
// toggle the JTAG pins between JTAG and GPIO mode.
//
//*****************************************************************************
void
SysTickIntHandler(void)
{
    uint8_t ui8Buttons;
    uint8_t ui8ButtonsChanged;

    //
    // Grab the current, debounced state of the buttons.
    //
    ui8Buttons = ButtonsPoll(&ui8ButtonsChanged, 0);

    //
    // If the left button has been pressed, and was previously not pressed,
    // start the process of changing the behavior of the JTAG pins.
    //
    if(BUTTON_PRESSED(LEFT_BUTTON, ui8Buttons, ui8ButtonsChanged))
    {
        //
        // Toggle the pin mode.
        //
        g_ui32Mode ^= 1;

        //
        // See if the pins should be in JTAG or GPIO mode.
        //
        if(g_ui32Mode == 0)
        {
            //
            // Change PC0-3 into hardware (i.e. JTAG) pins.
            //
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x01;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) |= 0x01;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x02;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) |= 0x02;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x04;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) |= 0x04;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x08;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) |= 0x08;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x00;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = 0;

            //
            // Turn on the LED to indicate that the pins are in JTAG mode.
            //
            ROM_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3 | GPIO_PIN_1,
                             GPIO_PIN_3);
        }
        else
        {
            //
            // Change PC0-3 into GPIO inputs.
            //
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x01;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) &= 0xfe;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x02;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) &= 0xfd;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x04;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) &= 0xfb;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x08;
            HWREG(GPIO_PORTC_BASE + GPIO_O_AFSEL) &= 0xf7;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
            HWREG(GPIO_PORTC_BASE + GPIO_O_CR) = 0x00;
            HWREG(GPIO_PORTC_BASE + GPIO_O_LOCK) = 0;
            ROM_GPIOPinTypeGPIOInput(GPIO_PORTC_BASE, (GPIO_PIN_0 | GPIO_PIN_1 |
                                                       GPIO_PIN_2 | GPIO_PIN_3));

            //
            // Turn off the LED to indicate that the pins are in GPIO mode.
            //
            ROM_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_3 | GPIO_PIN_1,
                             GPIO_PIN_1);
        }
    }
}
Ejemplo n.º 3
0
//*****************************************************************************
//
// Initialize and operate the data logger.
//
//*****************************************************************************
int
main(void)
{
    tContext sDisplayContext, sBufferContext;
    uint32_t ui32HibIntStatus, ui32SysClock, ui32LastTickCount;
    bool bSkipSplash;
    uint8_t ui8ButtonState, ui8ButtonChanged;
    uint_fast8_t ui8X, ui8Y;

    //
    // Enable lazy stacking for interrupt handlers.  This allows floating-point
    // instructions to be used within interrupt handlers, but at the expense of
    // extra stack usage.
    //
    MAP_FPULazyStackingEnable();

    //
    // Set the clocking to run at 50 MHz.
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ |
                       SYSCTL_OSC_MAIN);
    ui32SysClock = MAP_SysCtlClockGet();

    //
    // Initialize locals.
    //
    bSkipSplash = false;
    ui32LastTickCount = 0;

    //
    // Check Board Revision, report if software / hardware are incompatible
    //
    CheckBoardRevision();

    //
    // Initialize the data acquisition module.  This initializes the ADC
    // hardware.
    //
    AcquireInit();

    // Enable interrupts to the processor.
    //
    ROM_IntMasterEnable();

    //
    // Enable access to  the hibernate peripheral.  If the hibernate peripheral
    // was already running then this will have no effect.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_HIBERNATE);

    //
    // Check to see if the hiberate module is already active and if so then
    // read the saved configuration state.  If both are okay, then proceed
    // to check and see if we are logging data using sleep mode.
    //
    if(HibernateIsActive() && !GetSavedState(&g_sConfigState))
    {
        //
        // Read the status of the hibernate module.
        //
        ui32HibIntStatus = HibernateIntStatus(1);

        //
        // If this is a pin wake, that means the user pressed the select
        // button and we should terminate the sleep logging.  In this case
        // we will fall out of this conditional section, and go through the
        // normal startup below, but skipping the splash screen so the user
        // gets immediate response.
        //
        if(ui32HibIntStatus & HIBERNATE_INT_PIN_WAKE)
        {
            //
            // Clear the interrupt flag so it is not seen again until another
            // wake.
            //
            HibernateIntClear(HIBERNATE_INT_PIN_WAKE);
            bSkipSplash = true;
        }

        //
        // Otherwise if we are waking from hibernate and it was not a pin
        // wake, then it must be from RTC match.  Check to see if we are
        // sleep logging and if so then go through an abbreviated startup
        // in order to collect the data and go back to sleep.
        //
        else if(g_sConfigState.ui32SleepLogging &&
                (ui32HibIntStatus & HIBERNATE_INT_RTC_MATCH_0))
        {
            //
            // Start logger and pass the configuration.  The logger should
            // configure itself to take one sample.
            //
            AcquireStart(&g_sConfigState);
            g_iLoggerState = eSTATE_LOGGING;

            //
            // Enter a forever loop to run the acquisition.  This will run
            // until a new sample has been taken and stored.
            //
            while(!AcquireRun())
            {
            }

            //
            // Getting here means that a data acquisition was performed and we
            // can now go back to sleep.  Save the configuration and then
            // activate the hibernate.
            //
            SetSavedState(&g_sConfigState);

            //
            // Set wake condition on pin-wake or RTC match.  Then put the
            // processor in hibernation.
            //
            HibernateWakeSet(HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC);
            HibernateRequest();

            //
            // Hibernating takes a finite amount of time to occur, so wait
            // here forever until hibernate activates and the processor
            // power is removed.
            //
            for(;;)
            {
            }
        }

        //
        // Otherwise, this was not a pin wake, and we were not sleep logging,
        // so just fall out of this conditional and go through the normal
        // startup below.
        //
    }
    else
    {
        //
        // In this case, either the hibernate module was not already active, or
        // the saved configuration was not valid.  Initialize the configuration
        // to the default state and then go through the normal startup below.
        //
        GetDefaultState(&g_sConfigState);
    }

    //
    // Enable the Hibernate module to run.
    //
    HibernateEnableExpClk(SysCtlClockGet());

    //
    // The hibernate peripheral trim register must be set per silicon
    // erratum 2.1
    //
    HibernateRTCTrimSet(0x7FFF);

    //
    // Start the RTC running.  If it was already running then this will have
    // no effect.
    //
    HibernateRTCEnable();

    //
    // In case we were sleep logging and are now finished (due to user
    // pressing select button), then disable sleep logging so it doesnt
    // try to start up again.
    //
    g_sConfigState.ui32SleepLogging = 0;
    SetSavedState(&g_sConfigState);

    //
    // Initialize the display driver.
    //
    CFAL96x64x16Init();

    //
    // Initialize the buttons driver.
    //
    ButtonsInit();

    //
    // Pass the restored state to the menu system.
    //
    MenuSetState(&g_sConfigState);

    //
    // Enable the USB peripheral
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0);

    //
    // Configure the required pins for USB operation.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
    MAP_GPIOPinConfigure(GPIO_PG4_USB0EPEN);
    MAP_GPIOPinTypeUSBDigital(GPIO_PORTG_BASE, GPIO_PIN_4);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Erratum workaround for silicon revision A1.  VBUS must have pull-down.
    //
    if(CLASS_IS_BLIZZARD && REVISION_IS_A1)
    {
        HWREG(GPIO_PORTB_BASE + GPIO_O_PDR) |= GPIO_PIN_1;
    }

    //
    // Initialize the USB stack mode and pass in a mode callback.
    //
    USBStackModeSet(0, eUSBModeOTG, ModeCallback);

    //
    // Initialize the stack to be used with USB stick.
    //
    USBStickInit();

    //
    // Initialize the stack to be used as a serial device.
    //
    USBSerialInit();

    //
    // Initialize the USB controller for dual mode operation with a 2ms polling
    // rate.
    //
    USBOTGModeInit(0, 2000, g_pui8HCDPool, HCD_MEMORY_SIZE);

    //
    // Initialize the menus module.  This module will control the user
    // interface menuing system.
    //
    MenuInit(WidgetActivated);

    //
    // Configure SysTick to periodically interrupt.
    //
    g_ui32TickCount = 0;
    MAP_SysTickPeriodSet(ui32SysClock / CLOCK_RATE);
    MAP_SysTickIntEnable();
    MAP_SysTickEnable();

    //
    // Initialize the display context and another context that is used
    // as an offscreen drawing buffer for display animation effect
    //
    GrContextInit(&sDisplayContext, &g_sCFAL96x64x16);
    GrContextInit(&sBufferContext, &g_sOffscreenDisplayA);

    //
    // Show the splash screen if we are not skipping it.  The only reason to
    // skip it is if the application was in sleep-logging mode and the user
    // just waked it up with the select button.
    //
    if(!bSkipSplash)
    {
        const uint8_t *pui8SplashLogo = g_pui8Image_TI_Black;

        //
        // Draw the TI logo on the display.  Use an animation effect where the
        // logo will "slide" onto the screen.  Allow select button to break
        // out of animation.
        //
        for(ui8X = 0; ui8X < 96; ui8X++)
        {
            if(ButtonsPoll(0, 0) & SELECT_BUTTON)
            {
                break;
            }
            GrImageDraw(&sDisplayContext, pui8SplashLogo, 95 - ui8X, 0);
        }

        //
        // Leave the logo on the screen for a long duration.  Monitor the
        // buttons so that if the user presses the select button, the logo
        // display is terminated and the application starts immediately.
        //
        while(g_ui32TickCount < 400)
        {
            if(ButtonsPoll(0, 0) & SELECT_BUTTON)
            {
                break;
            }
        }

        //
        // Extended splash sequence
        //
        if(ButtonsPoll(0, 0) & UP_BUTTON)
        {
            for(ui8X = 0; ui8X < 96; ui8X += 4)
            {
                GrImageDraw(&sDisplayContext,
                            g_ppui8Image_Splash[(ui8X / 4) & 3],
                            (int32_t)ui8X - 96L, 0);
                GrImageDraw(&sDisplayContext, pui8SplashLogo, ui8X, 0);
                MAP_SysCtlDelay(ui32SysClock / 12);
            }
            MAP_SysCtlDelay(ui32SysClock / 3);
            pui8SplashLogo = g_ppui8Image_Splash[4];
            GrImageDraw(&sDisplayContext, pui8SplashLogo, 0, 0);
            MAP_SysCtlDelay(ui32SysClock / 12);
        }

        //
        // Draw the initial menu into the offscreen buffer.
        //
        SlideMenuDraw(&g_sMenuWidget, &sBufferContext, 0);

        //
        // Now, draw both the TI logo splash screen (from above) and the initial
        // menu on the screen at the same time, moving the coordinates so that
        // the logo "slides" off the display and the menu "slides" onto the
        // display.
        //
        for(ui8Y = 0; ui8Y < 64; ui8Y++)
        {
            GrImageDraw(&sDisplayContext, pui8SplashLogo, 0, -ui8Y);
            GrImageDraw(&sDisplayContext, g_pui8OffscreenBufA, 0, 63 - ui8Y);
        }
    }

    //
    // Add the menu widget to the widget tree and send an initial paint
    // request.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sMenuWidget);
    WidgetPaint(WIDGET_ROOT);

    //
    // Set the focus handle to the menu widget.  Any button events will be
    // sent to this widget
    //
    g_ui32KeyFocusWidgetHandle = (uint32_t)&g_sMenuWidget;

    //
    // Forever loop to run the application
    //
    while(1)
    {

        //
        // Each time the timer tick occurs, process any button events.
        //
        if(g_ui32TickCount != ui32LastTickCount)
        {
            //
            // Remember last tick count
            //
            ui32LastTickCount = g_ui32TickCount;

            //
            // Read the debounced state of the buttons.
            //
            ui8ButtonState = ButtonsPoll(&ui8ButtonChanged, 0);

            //
            // Pass any button presses through to the widget message
            // processing mechanism.  The widget that has the button event
            // focus (probably the menu widget) will catch these button events.
            //
            if(BUTTON_PRESSED(SELECT_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_SELECT);
            }
            if(BUTTON_PRESSED(UP_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_UP);
            }
            if(BUTTON_PRESSED(DOWN_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_DOWN);
            }
            if(BUTTON_PRESSED(LEFT_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_LEFT);
            }
            if(BUTTON_PRESSED(RIGHT_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_RIGHT);
            }
        }

        //
        // Tell the OTG library code how much time has passed in milliseconds
        // since the last call.
        //
        USBOTGMain(GetTickms());

        //
        // Call functions as needed to keep the host or device mode running.
        //
        if(g_iCurrentUSBMode == eUSBModeDevice)
        {
            USBSerialRun();
        }
        else if(g_iCurrentUSBMode == eUSBModeHost)
        {
            USBStickRun();
        }

        //
        // If in the logging state, then call the logger run function.  This
        // keeps the data acquisition running.
        //
        if((g_iLoggerState == eSTATE_LOGGING) ||
                (g_iLoggerState == eSTATE_VIEWING))
        {
            if(AcquireRun() && g_sConfigState.ui32SleepLogging)
            {
                //
                // If sleep logging is enabled, then at this point we have
                // stored the first data item, now save the state and start
                // hibernation.  Wait for the power to be cut.
                //
                SetSavedState(&g_sConfigState);
                HibernateWakeSet(HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC);
                HibernateRequest();
                for(;;)
                {
                }
            }

            //
            // If viewing instead of logging then request a repaint to keep
            // the viewing window updated.
            //
            if(g_iLoggerState == eSTATE_VIEWING)
            {
                WidgetPaint(WIDGET_ROOT);
            }
        }

        //
        // If in the saving state, then save data from flash storage to
        // USB stick.
        //
        if(g_iLoggerState == eSTATE_SAVING)
        {
            //
            // Save data from flash to USB
            //
            FlashStoreSave();

            //
            // Return to idle state
            //
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // If in the erasing state, then erase the data stored in flash.
        //
        if(g_iLoggerState == eSTATE_ERASING)
        {
            //
            // Save data from flash to USB
            //
            FlashStoreErase();

            //
            // Return to idle state
            //
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // If in the flash reporting state, then show the report of the amount
        // of used and free flash memory.
        //
        if(g_iLoggerState == eSTATE_FREEFLASH)
        {
            //
            // Report free flash space
            //
            FlashStoreReport();

            //
            // Return to idle state
            //
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // If we are exiting the clock setting widget, that means that control
        // needs to be given back to the menu system.
        //
        if(g_iLoggerState == eSTATE_CLOCKEXIT)
        {
            //
            // Give the button event focus back to the menu system
            //
            g_ui32KeyFocusWidgetHandle = (uint32_t)&g_sMenuWidget;

            //
            // Send a button event to the menu widget that means the left
            // key was pressed.  This signals the menu widget to deactivate
            // the current child widget (which was the clock setting wigdet).
            // This will cause the menu widget to slide the clock set widget
            // off the screen and resume control of the display.
            //
            SendWidgetKeyMessage(WIDGET_MSG_KEY_LEFT);
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // Process any new messages that are in the widget queue.  This keeps
        // the user interface running.
        //
        WidgetMessageQueueProcess();
    }
}
Ejemplo n.º 4
0
//*****************************************************************************
//
// This is the main loop that runs the application.
//
//*****************************************************************************
int
main(void)
{
    uint_fast32_t ui32LastTickCount;
    bool bLastSuspend;


    //
    // Enable lazy stacking for interrupt handlers.  This allows floating-point
    // instructions to be used within interrupt handlers, but at the expense of
    // extra stack usage.
    //
    ROM_FPULazyStackingEnable();

    //
    // Set the clocking to run from the PLL at 50MHz.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Enable the GPIO port that is used for the on-board LED.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    //
    // Enable the GPIO pin for the Blue LED (PF2).
    //
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3);

    //
    // Enable the UART.
    //
    ConfigureUART();
    UARTprintf("Keyboard device application\n");

    // Configure USB0DM & USB0DP (PD4 & PD5)
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    SysCtlGPIOAHBEnable(SYSCTL_PERIPH_GPIOD);
    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTD_AHB_BASE, GPIO_PIN_4 | GPIO_PIN_5);

    //Configure USB0ID & USB0VBUS (PB0 & PB1)
//    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
//    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);


    //
    // Erratum workaround for silicon revision A1.  VBUS must have pull-down.
    //
    if(CLASS_IS_TM4C123 && REVISION_IS_A1)
    {
        HWREG(GPIO_PORTB_BASE + GPIO_O_PDR) |= GPIO_PIN_1;
    }


    //
    // Initialize the buttons driver
    //
    ButtonsInit();

    //
    // Not configured initially.
    //
    g_bConnected = false;
    g_bSuspended = false;
    bLastSuspend = false;

    //
    // Initialize the USB stack for device mode.
    //
    //USBStackModeSet(0, eUSBModeDevice, 0);
    USBStackModeSet(0, eUSBModeForceDevice, 0);
    //
    // Pass our device information to the USB HID device class driver,
    // initialize the USB
    // controller and connect the device to the bus.
    //
    USBDHIDKeyboardInit(0, &g_sKeyboardDevice);

    //
    // Set the system tick to fire 100 times per second.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND);
    ROM_SysTickIntEnable();
    ROM_SysTickEnable();

    //
    // The main loop starts here.  We begin by waiting for a host connection
    // then drop into the main keyboard handling section.  If the host
    // disconnects, we return to the top and wait for a new connection.
    //
    while(1)
    {
        uint8_t ui8Buttons;
        uint8_t ui8ButtonsChanged;

        //
        // Tell the user what we are doing and provide some basic instructions.
        //
        UARTprintf("Waiting for host...\n");

        //
        // Wait here until USB device is connected to a host.
        //
        while(!g_bConnected)
        {
        }

        //
        // Update the status.
        //
        UARTprintf("Host connected...\n");

        //
        // Enter the idle state.
        //
        g_eKeyboardState = STATE_IDLE;

        //
        // Assume that the bus is not currently suspended if we have just been
        // configured.
        //
        bLastSuspend = false;

        //
        // Keep transferring characters from the UART to the USB host for as
        // long as we are connected to the host.
        //
        while(g_bConnected)
        {
            //
            // Remember the current time.
            //
            ui32LastTickCount = g_ui32SysTickCount;

            //
            // Has the suspend state changed since last time we checked?
            //
            if(bLastSuspend != g_bSuspended)
            {
                //
                // Yes - the state changed so update the display.
                //
                bLastSuspend = g_bSuspended;
                UARTprintf(bLastSuspend ? "Bus suspended...\n" :"Host connected...\n");
            }

            //
            // See if the button was just pressed.
            //
            ui8Buttons = ButtonsPoll(&ui8ButtonsChanged, 0);
            if(BUTTON_PRESSED(LEFT_BUTTON, ui8Buttons, ui8ButtonsChanged))
            {
                //
                // If the bus is suspended then resume it.  Otherwise, type
                // some "random" characters.
                //
                if(g_bSuspended)
                {
                    USBDHIDKeyboardRemoteWakeupRequest(
                                                   (void *)&g_sKeyboardDevice);
                }
                else
                {
                    SendString("Make the Switch to TI Microcontrollers!");
                }
            }

            //
            // Wait for at least 1 system tick to have gone by before we poll
            // the buttons again.
            //
            while(g_ui32SysTickCount == ui32LastTickCount)
            {

            }
        }

        //
        // Dropping out of the previous loop indicates that the host has
        // disconnected so go back and wait for reconnection.
        //

        if(g_bConnected == false)
                {
                    UARTprintf("Host disconnected...\n");
                }

    }
}
//*****************************************************************************
//
// This is the main loop that runs the application.
//
//*****************************************************************************
int
main(void)
{
    unsigned long ulLastTickCount;
    tBoolean bLastSuspend;
    tRectangle sRect;
    tContext sContext;
    long lCenterX;

    //
    // Enable lazy stacking for interrupt handlers.  This allows floating-point
    // instructions to be used within interrupt handlers, but at the expense of
    // extra stack usage.
    //
    ROM_FPULazyStackingEnable();

    //
    // Set the clocking to run from the PLL at 50MHz.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Configure the required pins for USB operation.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
    ROM_GPIOPinConfigure(GPIO_PG4_USB0EPEN);
    ROM_GPIOPinTypeUSBDigital(GPIO_PORTG_BASE, GPIO_PIN_4);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);
    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    ROM_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Erratum workaround for silicon revision A1.  VBUS must have pull-down.
    //
    if(CLASS_IS_BLIZZARD && REVISION_IS_A1)
    {
        HWREG(GPIO_PORTB_BASE + GPIO_O_PDR) |= GPIO_PIN_1;
    }

    //
    // Enable the GPIO that is used for the on-board LED.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTG_BASE, GPIO_PIN_2);
    ROM_GPIOPinWrite(GPIO_PORTG_BASE, GPIO_PIN_2, 0);

    //
    // Initialize the buttons driver
    //
    ButtonsInit();

    //
    // Initialize the display driver.
    //
    CFAL96x64x16Init();

    //
    // Initialize the graphics context and find the middle X coordinate.
    //
    GrContextInit(&sContext, &g_sCFAL96x64x16);
    lCenterX = GrContextDpyWidthGet(&sContext) / 2;

    //
    // Fill the top part of the screen with blue to create the banner.
    //
    sRect.sXMin = 0;
    sRect.sYMin = 0;
    sRect.sXMax = GrContextDpyWidthGet(&sContext) - 1;
    sRect.sYMax = 9;
    GrContextForegroundSet(&sContext, ClrDarkBlue);
    GrRectFill(&sContext, &sRect);

    //
    // Change foreground for white text.
    //
    GrContextForegroundSet(&sContext, ClrWhite);

    //
    // Put the application name in the middle of the banner.
    //
    GrContextFontSet(&sContext, g_pFontFixed6x8);
    GrStringDrawCentered(&sContext, "usb-dev-keyboard", -1, lCenterX, 4, 0);

    //
    // Not configured initially.
    //
    g_bConnected = false;
    g_bSuspended = false;
    bLastSuspend = false;

    //
    // Initialize the USB stack for device mode.
    //
    USBStackModeSet(0, USB_MODE_DEVICE, 0);

    //
    // Pass our device information to the USB HID device class driver,
    // initialize the USB
    // controller and connect the device to the bus.
    //
    USBDHIDKeyboardInit(0, &g_sKeyboardDevice);

    //
    // Set the system tick to fire 100 times per second.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / SYSTICKS_PER_SECOND);
    ROM_SysTickIntEnable();
    ROM_SysTickEnable();

    //
    // The main loop starts here.  We begin by waiting for a host connection
    // then drop into the main keyboard handling section.  If the host
    // disconnects, we return to the top and wait for a new connection.
    //
    while(1)
    {
        unsigned char ucButtons;
        unsigned char ucButtonsChanged;

        //
        // Tell the user what we are doing and provide some basic instructions.
        //
        GrStringDrawCentered(&sContext, "    Waiting    ", -1, lCenterX, 22, 1);
        GrStringDrawCentered(&sContext, " for host ... ", -1, lCenterX, 32, 1);

        //
        // Wait here until USB device is connected to a host.
        //
        while(!g_bConnected)
        {
        }

        //
        // Update the status.
        //
        GrStringDrawCentered(&sContext, "     Host     ", -1, lCenterX, 22, 1);
        GrStringDrawCentered(&sContext, " connected ... ", -1, lCenterX, 32, 1);

        //
        // Enter the idle state.
        //
        g_eKeyboardState = STATE_IDLE;

        //
        // Assume that the bus is not currently suspended if we have just been
        // configured.
        //
        bLastSuspend = false;

        //
        // Keep transferring characters from the UART to the USB host for as
        // long as we are connected to the host.
        //
        while(g_bConnected)
        {
            //
            // Remember the current time.
            //
            ulLastTickCount = g_ulSysTickCount;

            //
            // Has the suspend state changed since last time we checked?
            //
            if(bLastSuspend != g_bSuspended)
            {
                //
                // Yes - the state changed so update the display.
                //
                bLastSuspend = g_bSuspended;
                if(bLastSuspend)
                {
                    GrStringDrawCentered(&sContext, "      Bus      ", -1,
                                         lCenterX, 22, 1);
                    GrStringDrawCentered(&sContext, " suspended ... ", -1,
                                         lCenterX, 32, 1);
                }
                else
                {
                    GrStringDrawCentered(&sContext, "     Host     ", -1,
                                         lCenterX, 22, 1);
                    GrStringDrawCentered(&sContext, " connected ... ",
                                         -1, lCenterX, 32, 1);
                }
            }

            //
            // See if the button was just pressed.
            //
            ucButtons = ButtonsPoll(&ucButtonsChanged, 0);
            if(BUTTON_PRESSED(SELECT_BUTTON, ucButtons, ucButtonsChanged))
            {
                //
                // If the bus is suspended then resume it.  Otherwise, type
                // some "random" characters.
                //
                if(g_bSuspended)
                {
                    USBDHIDKeyboardRemoteWakeupRequest(
                                                   (void *)&g_sKeyboardDevice);
                }
                else
                {
                    SendString("Make the Switch to TI Microcontrollers!");
                }
            }

            //
            // Wait for at least 1 system tick to have gone by before we poll
            // the buttons again.
            //
            while(g_ulSysTickCount == ulLastTickCount)
            {
            }
        }
    }
}
Ejemplo n.º 6
0
void nodeSleep(u16 tenthSeconds)
{

    // ************** Power down the other board peripherals
    Leds_off();

    // ************** Power down the radio
    // wait for radio to be done
    u8 state = BUSY_TX_ARET;
    while (state == BUSY_TX_ARET ||
           state == BUSY_RX_AACK)
        state = radioGetTrxState();

    // Now put radio to sleep
    radioEnterSleepMode();


// TODO: figure out what needs to be put to sleep to minimize current consumption
// ************** Power down the on-chip modules
// PRR = 0xbf; ??? 
// Disable ADC
//        ADCSRA &= ~(1 << ADEN);
// Turn off comparator
//        ACSR |= (1 << 
    
// turn off ports  etc

// Turn off BOD

// This should only be done once -- No need to do it over again
/*
        AVR_ENTER_CRITICAL_REGION();
#define BODS  6
#define BODSE 5
        MCUCR  |= (1 << BODSE) | (1<< BODS);
        MCUCR  &= ~(1 << BODSE);
        AVR_LEAVE_CRITICAL_REGION();
    
*/


    // ************** Set the timer to wake up
	// Set TIMER2 Asyncronous Mode.
	ASSR |= (1 << AS2);
	// Set TIMER2 Prescaler to 1024.
	TCCR2B |= ((1 << CS22)|(1 << CS21)|(1 << CS20));
	// Wait for TCNT2 write to finish.
	while(ASSR & (1 << TCR2BUB))
		;


    // Sleep as many times as needed to sleep for the full time
    while (tenthSeconds)
    {
		// This is to get the node manually out of sleeping mode --
    	// Might take up to 7.5Sec to detect button press
    	//
    	if (BUTTON_PRESSED() )
    	{
    		Led1_on();
    		macConfig.sleeping = false;
    		while (BUTTON_PRESSED())
    			;
    		Led1_off();
    		break;		//  exit the Sleeping loop
    	}
		// Set TIMER2 output compare register from user.
		if (tenthSeconds > 75)
		{
			// Just decrement by the max timeout
			OCR2A = 240; // 7.5 seconds, max timeout
			tenthSeconds -= 75;
		}
		else
		{
			// Can measure the remaining time in one timer cycle

			tenthSeconds = tenthSeconds * 16 / 5;
			if (!tenthSeconds)
				tenthSeconds++;
			OCR2A = tenthSeconds;
			tenthSeconds = 0;
		}
		// Wait for OCR2 write to finish.
		while(ASSR & (1 << OCR2AUB))
			;
		// Reset TIMER2 timer counter value.
		TCNT2 = 0;
		// Wait for TCNT2 write to finish before entering sleep.
		while(ASSR & (1 << TCN2UB))
			;

		// Clear interrupt flag
		TIFR2 |= (1 << OCF2A);
		// Enable TIMER2 output compare interrupt.
		TIMSK2 |= (1 << OCIE2A);


        // ************** Go to sleep
        AVR_ENTER_CRITICAL_REGION();
        set_sleep_mode( SLEEP_MODE_PWR_SAVE);
        sleep_enable();
        sei();
        sleep_cpu();   // sleeping right here
        sleep_disable();
        AVR_LEAVE_CRITICAL_REGION();

        wdt_disable();
    }

    // ************** Awake now, wake up everything

 //    PRR = 0x03; ??


    if (SERIAL)
        serial_init(NULL);

    debugMsgStr("\r\nNode slept");
    if ( macConfig.associated)
        HAL_ADC_INIT();

    // Bring SPI port back up (must re-init after sleep)
    radio_spi_init();

    // Wake up radio.
    radioLeaveSleepMode();

    // Set RF212 to 250KB mode.
// TODO: do I need to call this??
    //radioSetup900();

    radioSetTrxState(PLL_ON);
}