Example #1
0
/*超声波测距运行*/
void BSP_SonicRun(void *p_arg)
{
    BSP_SonicInit(1,100);
	BSP_SonicOpen();
    while(1)
	{
		 if(SONICDEVICE.active == 1)
		 {
		   if(SONICDEVICE.runstep == 0)
		   {
//		 	 GPIO_WriteBit(GPIOE, GPIO_Pin_5,(BitAction)1);
		     StartTimer(1);
			 SONICDEVICE.runstep = 1;
			 SONICDEVICE.step = 1;
		   }
		   else if(SONICDEVICE.runstep == 1)
		   {
		     if(CheckTimer() == TRUE)
			 {
//		       GPIO_WriteBit(GPIOE, GPIO_Pin_5,(BitAction)0);
			   SONICDEVICE.runstep = 2;
			   StartTimer(SONICDEVICE.timems);
			 }
		   }
		   else if(SONICDEVICE.runstep == 2)
		   {
		     if(CheckTimer() == TRUE)
			 {
			   SONICDEVICE.runstep = 0;
			 }
		   }
		 }
		OSTimeDlyHMSM(0, 0, 0, 1);
 	}
}
Example #2
0
void PI_DMA_WRITE (usf_state_t * state) {
	uint32_t i;
	PI_STATUS_REG |= PI_STATUS_DMA_BUSY;
	if ( PI_DRAM_ADDR_REG + PI_WR_LEN_REG + 1 > state->RdramSize) {
		PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
		MI_INTR_REG |= MI_INTR_PI;
		CheckInterrupts(state);
		return;
	}

	if ( PI_CART_ADDR_REG >= 0x08000000 && PI_CART_ADDR_REG <= 0x08010000) {
		return;
	}

	if ( PI_CART_ADDR_REG >= 0x10000000 && PI_CART_ADDR_REG <= 0x1FBFFFFF) {
		PI_CART_ADDR_REG -= 0x10000000;
		for (i = 0; i < PI_WR_LEN_REG + 1; i ++) {
			*(state->N64MEM+((PI_DRAM_ADDR_REG + i) ^ 3)) =  *PageROM(state, (PI_CART_ADDR_REG + i) ^ 3);
		}
		PI_CART_ADDR_REG += 0x10000000;

		PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
		MI_INTR_REG |= MI_INTR_PI;
		CheckInterrupts(state);
		CheckTimer(state);
		return;
	}

	PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
	MI_INTR_REG |= MI_INTR_PI;
	CheckInterrupts(state);
}
Example #3
0
// poll one adc channel every 25ms
static void PollAdc() {
  static long adc_timer = 0;

  if(CheckTimer(adc_timer)) {
    adc_timer = GetTimer(25);
    PollOneAdc();
  }
}
Example #4
0
// get key status
unsigned char OsdGetCtrl(void)
{
	static unsigned char c2;
	static unsigned short repeat;
	unsigned char c1,c;

	// send command and get current ctrl status
	c1 = OsdCommand(OSDCMDREAD);

	// add front menu button
	if (CheckButton())
	{	c1 = KEY_MENU;	}

	// generate normal "key-pressed" event
	c = 0;
	if (c1!=c2)
	{	c = c1;	}

	c2 = c1;

	/*generate repeat "key-pressed" events
	do not for menu button*/
	#if	defined(PGL100818)
		if (c1 & KEY_UPSTROKE)
		{	repeat = GetTimer(REPEATDELAY);		}
		else if (CheckTimer(repeat))
		{
			repeat = GetTimer(REPEATRATE);
			if (c1==KEY_UP || c1==KEY_DOWN || GetASCIIKey(c1))
			{	c = c1;	}
		}
	#else
		if (!c1)
		{	repeat = GetTimer(REPEATDELAY);		}
		else if (CheckTimer(repeat))
		{
			repeat = GetTimer(REPEATRATE);
			if (c1==KEY_UP || c1==KEY_DOWN || GetASCIIKey(c1))
			{	c = c1;	}
		}
	#endif

	// return events
	return(c);
}
Example #5
0
void ChangeTimer(usf_state_t * state, int32_t Type, int32_t Value) {
	if (Value == 0) {
		state->Timers->NextTimer[Type] = 0;
		state->Timers->Active[Type] = 0;
		return;
	}
	state->Timers->NextTimer[Type] = Value - state->Timers->Timer;
	state->Timers->Active[Type] = 1;
	CheckTimer(state);
}
Example #6
0
// send pending bytes if timer has run up
static void kbd_fifo_poll() {
  // timer enabled and runnig?
  if(kbd_timer && !CheckTimer(kbd_timer))
    return;
 
  kbd_timer = 0;  // timer == 0 means timer is not running anymore

  if(kbd_fifo_w == kbd_fifo_r)
    return;

  kbd_fifo_minimig_send(kbd_fifo[kbd_fifo_r]);
  kbd_fifo_r = (kbd_fifo_r + 1)&(KBD_FIFO_SIZE-1);
}
Example #7
0
static
VOID
TestTimerFunctional(
    IN PKTIMER Timer,
    IN TIMER_TYPE Type,
    IN KIRQL OriginalIrql)
{
    PKTHREAD Thread = KeGetCurrentThread();

    memset(Timer, 0x55, sizeof *Timer);
    KeInitializeTimerEx(Timer, Type);
    CheckTimer(Timer, TimerNotificationObject + Type, 0L, FALSE, OriginalIrql, (PVOID *)NULL, 0);
}
Example #8
0
void CIndicator::ShowFinal(void)
{
  if (CheckTimer())
    {
      ptr = Bar + (Counter = CurPos);
      while (Counter < BarSize)
        {
          *ptr = 0x2588;           //'Û'
          ++ptr;
          ++Counter;
        }
      FarMessage(&MainGuid, &IndicatorGuid, FMSG_LEFTALIGN, NULL, MsgData, Items, 0);
    }
}
Example #9
0
/*==============================================================================
* Function Name : fnLDCtrl_GetLoadKeyCheckFlag()
* Description   : Key Check counted
* Parameters    : None
* Return        : None
* Release       : Ver 1.0
* Notes			: 2010.04.01 Kim Gi Jin
* ============================================================================*/
int	CDevCmn::fnLDCtrl_GetLoadKeyCheckFlag(LPCTSTR lpSetOpenKey)
{
	static	int		nSaveReturn = FALSE;
	int				nReturn = FALSE;
	ULONG			nWaitTime = 0;
	int				nRet = FALSE;
	MsgDump(TRACE_DUMP_MODE, "Log", __FILE__, __LINE__, "fnLDCtrl_GetLoadKeyCheckFlag(%s)", lpSetOpenKey);

	if(fnAPL_GetDefineDevice(DEV_RDCTRL))
	{
		
		fnLDCtrl_OpenRpcLock(lpSetOpenKey, 0);
		nWaitTime = TimerSet(5);
		while (!CheckTimer(nWaitTime))
		{
			nRet = fnDll_GetLoadKeyCheckFlag();
			if(nRet == LOCK_STAT_CHECK_OK)
			{
				nReturn = LOCK_STAT_CHECK_OK;
				break;
			}
			else
			if(nRet == LOCK_STAT_CHECK_NG)
			{
				nReturn = LOCK_STAT_CHECK_NG;
				break;
			}
			Sleep(200);
		}

		
	}

	if (nReturn != nSaveReturn)
	{
		nSaveReturn = nReturn;
		MsgDump(TRACE_CODE_MODE, "Log", __FILE__, __LINE__, "fnLDCtrl_GetLoadKeyCheckFlag():return(%d)", nReturn);
	}

	return nReturn;
}
Example #10
0
void SP_DMA_READ (usf_state_t * state) {
	SP_DRAM_ADDR_REG &= 0x1FFFFFFF;

	if (SP_DRAM_ADDR_REG > state->RdramSize) {
		SP_DMA_BUSY_REG = 0;
		SP_STATUS_REG  &= ~SP_STATUS_DMA_BUSY;
		return;
	}

	if (SP_RD_LEN_REG + 1  + (SP_MEM_ADDR_REG & 0xFFF) > 0x1000) {
		return;
	}

	memcpy( state->DMEM + (SP_MEM_ADDR_REG & 0x1FFF), state->N64MEM + SP_DRAM_ADDR_REG,
		SP_RD_LEN_REG + 1 );

	SP_DMA_BUSY_REG = 0;
	SP_STATUS_REG  &= ~SP_STATUS_DMA_BUSY;
	MI_INTR_REG &= ~MI_INTR_SP;
	CheckInterrupts(state);
	CheckTimer(state);
}
Example #11
0
void TimerDone (usf_state_t * state) {
	switch (state->Timers->CurrentTimerType) {
	case CompareTimer:
		if(state->enablecompare)
			FAKE_CAUSE_REGISTER |= CAUSE_IP7;
		CheckInterrupts(state);
		ChangeCompareTimer(state);
		break;
	case ViTimer:
		RefreshScreen(state);
		MI_INTR_REG |= MI_INTR_VI;
		CheckInterrupts(state);
		*state->WaitMode=0;
		break;
	case AiTimer:
		ChangeTimer(state,AiTimer,0);
		AI_STATUS_REG=0;
        state->AudioIntrReg|=4;
		//CheckInterrupts(state);
		break;
	}
	CheckTimer(state);
}
Example #12
0
void CIndicator::ShowProgress(intptr_t Cur)
{
  if (CheckTimer())
    {
      Procent = (int)((Cur + 1) * 100 / (Total + 1));
      NewProcent = Procent * BarSize / 100;
      if (NewProcent > BarSize)
        NewProcent = BarSize;
      if (NewProcent > OldProcent)
        {
          OldProcent = NewProcent;
          ptr = Bar + (Counter = CurPos);
          while (Counter < NewProcent)
            {
              *ptr = 0x2588;       //'Û'
              ++ptr;
              ++Counter;
            }
          CurPos = Counter;
          FarMessage(&MainGuid, &IndicatorGuid, FMSG_LEFTALIGN, NULL, MsgData, Items,
                       0);
        }
    }
}
Example #13
0
/* 充放电结束后放置一小时 */
int delay_hour(void)
{

	FRESULT result;
	FATFS fs;
	FIL file;
	DIR DirInf;  
	uint32_t bw;


	char time_buf[TIME_MAX];
	char write_buf[WR_MAX];
	char tmp_buf[8];

	int sec = 0;
	int i = 0;
	int min_count = 0;
	double vol;


	result = f_mount(0, &fs);		
	if (result != FR_OK){
		printf("FileSystem Mounted Failed (%d)\r\n", result);
		goto ERROR;
	}

	result = f_opendir(&DirInf, "/");
	if (result != FR_OK){ 
		printf("Open Root Directory Error (%d)\r\n", result);
		goto ERROR;
	}
	
	result = f_open(&file, conf->file_name, FA_OPEN_ALWAYS | FA_READ | FA_WRITE);	
	if(result !=FR_OK){
		printf("open error, errornu:%d\n\r",result);
	 	goto ERROR;
	}

	if(f_lseek(&file,file.fsize) != FR_OK){
		printf("f_lseek error, errornu:%d\n\r",result);
		goto ERROR;
	}

	
	beeper_on();
	delay_ms(200);
	beeper_off();

	memset(time_buf,0,TIME_MAX);
	memset(write_buf,0,WR_MAX);

	printf("\n\r静置开始");
	Time_Display(RTC_GetCounter());
	printf("\n\r");

	bsp_LedOn(4);

	StartTimer(0,  1000);
//	Time_Display(RTC_GetCounter());
			
	do{
		if(jump)
			goto JMP;	
		
		if(CheckTimer(0) ) {	
			StartTimer(0,  1000);
			sec++;
			min_count ++;

			vol = ADC_SAMPLING();

			if(min_count >= 60){
				min_count = 0;

				record_time(time_buf);
				strcat(time_buf,",");						
	
	
				strcat(write_buf, time_buf);
				memset(time_buf,0,TIME_MAX);		
	
								
				sprintf(tmp_buf, "%.2f", vol);								      
				strcat(write_buf, tmp_buf);
				strcat(write_buf,",静置\n");
	
				if(i >= 9){
					result = f_write(&file,write_buf,sizeof(write_buf),&bw);			
					if(result != FR_OK){
						printf("file write faild, errornu:%d\n\r",result);
						goto ERROR;
					}
					
					memset(write_buf,0,WR_MAX);
					i = 0;
				}
	
				i++;
			}
		}	

	}while(sec < 3600);  /* 静置时间(单位:秒) */

JMP:
	jump = 0;
	if(i != 0){

		result = f_write(&file,write_buf,(15 + TIME_MAX)*i, &bw);			
		if(result != FR_OK){
			printf("file write faild, errornu:%d\n\r",result);
			goto ERROR;
			
		}
		i = 0;
	}
	memset(write_buf,0,WR_MAX);


	printf("静置结束");
	Time_Display(RTC_GetCounter());
	printf("\n\r");

	bsp_LedOff(4);

	f_close(&file);
	f_mount(0, NULL);
	return 0;
	

ERROR:
	bsp_LedOff(4);
	f_close(&file);
	f_mount(0, NULL);
	return 1;
}
Example #14
0
// Check that a screen can close if Opus disappears
BOOL check_closescreen(struct Screen *screen)
{
	ULONG lock;
	struct Window *window=0;
	TimerHandle *timer=0;
	short a;

	// Try this four times
	for (a=0;a<4;a++)
	{
		// Lock IntuitionBase
		lock=LockIBase(0);

		// Go through window list
		for (window=screen->FirstWindow;
			window;
			window=window->NextWindow)
		{
			// Not a Workbench tool window?
			if (!(window->Flags&WFLG_WBENCHWINDOW))
			{
				// If this is one of Opus', GetWindowID() should know about it
				if (GetWindowID(window)==WINDOW_UNKNOWN)
				{
					BOOL ok=0;
					struct Task *task=0;

					// Special case for IPrefs requester - get window's task
					if (window->UserPort)
						task=(struct Task *)window->UserPort->mp_SigTask;

					// Valid name?
					if (task && task->tc_Node.ln_Name)
					{
						// Owned by IPrefs?
						if (strcmp(task->tc_Node.ln_Name,"« IPrefs »")==0) ok=1;
					}

					// If not ok, fail
					if (!ok) break;
				}
			}
		}

		// Unlock IntuitionBase
		UnlockIBase(lock);

		// Ok to shut?
		if (!window) break;

		// Allocate timer if don't already have it
		if (!timer &&
			!(timer=AllocTimer(UNIT_VBLANK,0))) break;

		// Start timer and wait for it
		StartTimer(timer,0,250000);
		while (!CheckTimer(timer))
			WaitPort(timer->port);
	}

	// Free timer
	FreeTimer(timer);

	// If window==NULL we can shut
	return (BOOL)(!window);
}
Example #15
0
void menu(void)
{
    struct Solid cursor;
	char selection = 0;
	displayMenu(&cursor);
    StartTimer(0, 200);
    StartTimer(1, 200);


	for (;;)
	{
		if (CheckTimer(0))
		{
            if (GetUp())
            {
            	if (selection > 0)
            	{
            		solid_moveLocation(&cursor, cursor.x - 22, cursor.y);
            		selection--;
            		StartTimer(0, 200);
            	}
            }
            else if (GetDown())
            {
            	if (selection < 7)
            	{
               	   solid_moveLocation(&cursor, cursor.x + 22, cursor.y);
                   selection++;
                   StartTimer(0, 200);
            	}

            }
		}
		if (CheckTimer(1))
		{
			if (GetTopLeft())
			{
				if (selection == 0)
				{
					StarBattle();
					displayMenu(&cursor);
					selection = 0;
				}
				else if (selection == 1)
				{
				    BrickBreaker();
				    displayMenu(&cursor);
				    selection = 0;
				}
				else if (selection == 2)
				{
                    Debris();
                    displayMenu(&cursor);
                    selection = 0;
				}
				else if (selection == 3)
				{
				    Pong();
                    displayMenu(&cursor);
                    selection = 0;
				}
				else if (selection == 4)
				{
				    Draw();
				    displayMenu(&cursor);
				    selection = 0;
				}
				StartTimer(1, 200);
			}
		}

	}


}
Example #16
0
bool StandardMainLoop::doMainLoop()
{
   #ifdef TORQUE_DEBUG
   if( gStartupTimer )
   {
      Con::printf( "Started up in %.2f seconds...",
         F32( gStartupTimer->getElapsedMs() ) / 1000.f );
      SAFE_DELETE( gStartupTimer );
   }
   #endif
   
   bool keepRunning = true;
//   while(keepRunning)
   {
      tm->setBackgroundThreshold(mClamp(sgBackgroundProcessSleepTime, 1, 200));
      tm->setForegroundThreshold(mClamp(sgTimeManagerProcessInterval, 1, 200));
      // update foreground/background status
      if(WindowManager->getFirstWindow())
      {
         static bool lastFocus = false;
         bool newFocus = ( WindowManager->getFocusedWindow() != NULL );
         if(lastFocus != newFocus)
         {
#ifndef TORQUE_SHIPPING
            Con::printf("Window focus status changed: focus: %d", newFocus);
            if (!newFocus)
               Con::printf("  Using background sleep time: %u", Platform::getBackgroundSleepTime());
#endif

#ifdef TORQUE_OS_MAC
            if (newFocus)
               WindowManager->getFirstWindow()->show();
               
#endif
            lastFocus = newFocus;
         }
         
#ifndef TORQUE_OS_MAC         
         // under the web plugin do not sleep the process when the child window loses focus as this will cripple the browser perfomance
         if (!Platform::getWebDeployment())
            tm->setBackground(!newFocus);
         else
            tm->setBackground(false);
#else
         tm->setBackground(false);
#endif
      }
      else
      {
         tm->setBackground(false);
      }
      
      PROFILE_START(MainLoop);
      Sampler::beginFrame();

      if(!Process::processEvents())
         keepRunning = false;

      ThreadPool::processMainThreadWorkItems();
      Sampler::endFrame();
      PROFILE_END_NAMED(MainLoop);

	  #ifdef TORQUE_DEMO_PURCHASE
	  CheckTimer();
	  CheckBlocker();
	  #endif
   }
   
   return keepRunning;
}
Example #17
0
void Pong(void)
{
   int i;
   int closest_index = -1;
   int closest_value = 500;
   int wall_bounce = 0;
   unsigned int computerScore = 0;
   unsigned int playerScore = 0;
   unsigned int ball_speed = PONG_BALL_SPEED;

   struct Solid userPaddle;
   struct Solid computerPaddle;
   struct Solid balls[NUM_PONGBALLS];

   //By default, all pong balls are disabled.
   for (i = 0; i < NUM_PONGBALLS; i++)
   {
       balls[i].health = 0;
   }
   ILI9340_setBgColor(COLOR_YELLOW);
   printf_setFont_properties(2, 0, COLOR_BLUE, COLOR_YELLOW);
   printf_setFont_location(10, 300);
   _printf("Player %u", playerScore);
   printf_setFont_location(10, 150);
   _printf("Computer %u", computerScore);

   build_solid(&userPaddle, 100, 290, 30, 4, COLOR_BLUE);
   build_solid(&computerPaddle, 100, 30, 30, 4, COLOR_RED);
   build_moving_solid(&balls[0], 100, 100, 7, 7, COLOR_GREEN, SOLID_AUTOUP | SOLID_AUTOLEFT, 0x0f, 27, 4);
   build_moving_solid(&balls[1], 100, 200, 7, 7, COLOR_BLUE, SOLID_AUTODOWN | SOLID_AUTORIGHT, 0x0f, 27, 4);
   build_moving_solid(&balls[2], 150, 200, 7, 7, COLOR_RED, SOLID_AUTOUP | SOLID_AUTORIGHT, 0x0f, 27, 4);
   build_moving_solid(&balls[3], 200, 200, 7, 7, COLOR_CYAN, SOLID_AUTODOWN | SOLID_AUTOLEFT, 0x0f, 27, 4);
   StartTimer(0, PONG_PADDLE_SPEED);
   StartTimer(1, ball_speed);
   StartTimer(2, CHECK_PONG_PAUSE);

   for (;;)
   {
       if (CheckTimer(0))
       {
           if (GetUp())
           {
               solid_fastMoveUp(&userPaddle, GetJoystickYMag() + 5, 0);
           }
           else if (GetDown())
           {
               solid_fastMoveDown(&userPaddle, GetJoystickYMag() + 5, 0);
           }
           StartTimer(0, PONG_PADDLE_SPEED);
       }
       if (CheckTimer(1))
       {
           //By default we support multiple pong balls
           for (i = 0; i < NUM_PONGBALLS; i++)
           {
              if (solid_checkIntersectionPongPaddle(&balls[i], &userPaddle) || solid_checkIntersectionPongPaddle(&balls[i], &computerPaddle))
              {
                  playSound(0);
                  if (ball_speed > 20)
                  {
                      ball_speed--;
                  }
              }

              wall_bounce = solid_autoMove(&balls[i]);
              //Hit the left of the screen
              if (wall_bounce == 3)
              {
                  display_solid(&balls[i], 1);
                  printf_setFont_location(10, 44);
                  computerScore++;
                  _printf("%u", computerScore);
                  build_moving_solid(&balls[i], userPaddle.x + 4, 280, 7, 7, balls[i].color, SOLID_AUTOUP | SOLID_AUTORIGHT, 0x0f, 27, 4);

              }
              else if (wall_bounce == 4)
              {
                  display_solid(&balls[i], 1);
                  printf_setFont_location(10, 217);
                  playerScore++;
                  _printf("%u", playerScore);
                  build_moving_solid(&balls[i], computerPaddle.x + 4, 40, 7, 7, balls[i].color, SOLID_AUTOUP | SOLID_AUTOLEFT, 0x0f, 27, 4);
              }
              if (wall_bounce != 0)
              {
                  playSound(0);
              }
              if (balls[i].health > 0 && ((balls[i].autoMove & SOLID_AUTORIGHT) || (balls[i].autoMove & SOLID_FASTRIGHT)))
              {
                  if (balls[i].y < closest_value && balls[i].y > 22)
                  {
                      closest_index = i;
                      closest_value = balls[i].y;
                  }
              }
           }
           if (closest_index != -1)
           {
               solid_aiMovePaddle(&computerPaddle, &balls[closest_index]);
           }
           closest_index = -1;
           closest_value = 500;
           StartTimer(1, ball_speed);
       }
       if (CheckTimer(2))
       {
           if (GetJoystickBtn())
           {
               if (Pause() == 1)
               {
                   break;
               }
           }
           StartTimer(2, CHECK_PONG_PAUSE);
       }
   }






}
Example #18
0
void BrickBreaker(void)
{
    uint8_t temp;
    uint16_t i = 0;
    uint16_t j = 0;
    uint8_t level = 4;
    uint8_t random = 0;
    uint16_t non_paddle_hits = 0;
    uint16_t num_blocks = 0;
    struct Solid solids[NUM_BRICKS];
    uint16_t ballSpeed = BALL_SPEED;
    uint32_t score = 0;
    uint8_t balls = 4;
    uint16_t blocks_destroyed = 0;
    char vertical = 0;
    char horizontal = 0;
    char item_flame = 0;
    char item_long_paddle = 0;
    char item_short_paddle = 0;
    char ball_speed_fast = 0;
    char ball_speed_slow = 0;
    char item_bullets = 0;
    uint16_t bullet_index = 0;
    uint16_t paddle_width = 25;
    uint16_t item_buffer[200];
    struct DropItem items[10]; //Items that get dropped
    struct MovingSolid bullets[15];
    struct Solid paddle;
    struct MovingSolid ball;
    setBgColor(COLOR_GREEN);
    printf_setFont_properties(2, 0, COLOR_BLUE, COLOR_GREEN);
    printf_setFont_location(5, 300);
    _printf("Ball %d", balls);
    printf_setFont_location(5, 200);
    _printf("Score 0");
    for (i = 0; i < NUM_BRICKS; i++)
    {
    	solids[i].status = 0;
    }
    //Initialize the items
    for (i = 0; i < 10; i++)
    {
    	items[i].sprite.status = 0;
    	items[i].sprite.type = 0;
    }
    for (i = 0; i < 15; i++)
    {
    	bullets[i].solid.status = 0;
    }

#if READ_EEPROMLEVEL == 1
    //Load the last level from memory
	SetClockSpeed(0); //Clock Speed must be < 10Mhz to support EEProm
	__disable_interrupt();
    level = EEProm_Read(BRICK_BREAKER_LEVEL);

    if (level == 0 || level > 4)
    {
    	level = 1;
    	EEProm_Write(BRICK_BREAKER_LEVEL, level);
    }
    __enable_interrupt();
    SetClockSpeed(5); //Clock Speed must be < 10Mhz to support EEProm
#endif
    num_blocks = loadLevel(solids, level);
    build_solid(&paddle, 200, 160, 5, paddle_width, COLOR_DRKGREY);
    build_moving_solid(&ball, 200, 167, 7, 7, COLOR_DRKGREY, SOLID_AUTOUP | SOLID_AUTOLEFT, 4);
    solid_setScreenBounds(0x0f);


	StartTimer(0, PADDLE_SPEED + 21);
	StartTimer(1, ballSpeed + 31);
	StartTimer(2, PAUSE_CHECK);
	StartTimer(4, ITEM_DROP_SPEED);
	StartTimer(5, ITEM_RANDOM_DROP);

	for (;;)
	{
		//Check the joystick
        if (CheckTimer(0))
        {
        	if (GetLeft())
        	{
        	   solid_fastMoveLeft(&paddle, GetJoystickXMag() + 5, 0);
        	}
        	else if (GetRight())
        	{
        	   solid_fastMoveRight(&paddle, GetJoystickXMag() + 5, 0);
        	}
        	StartTimer(0, PADDLE_SPEED);
        }
        //Auto-move the ball, check if it has hit any bricks.
        if (CheckTimer(1))
        {
        	temp = solid_autoMove(&ball);
        	if (temp != 0)
        	{
        		play_sound(0);
        	}
        	if (temp == 3)
        	{
        		balls--;
        	    printf_setFont_location(5, 300);
        	    _printf("Ball %d", balls);
        	    display_moving_solid(&ball, 1);
        	    ballSpeed = BALL_SPEED;// Reset the ball speed
                build_moving_solid(&ball, 200, 167, 7, 7, COLOR_DRKGREY, SOLID_AUTOUP | SOLID_AUTOLEFT, 4);
        	    if (balls == 0)
        	    {
        	    	AddHighScore(score, BRICK_BREAKER_SCORE_ADDR);
        	    	setBgColor(COLOR_GREEN);
                    display_solid(&paddle, 1);
                    display_moving_solid(&ball, 1);
                    balls = 4;
                    score = 0;
                    printf_setFont_location(5, 300);
                    _printf("Ball %d", balls);
                    printf_setFont_location(5, 200);
                    _printf("Score 0");
                    build_solid(&paddle, 200, 160, 5, 25, COLOR_DRKGREY);
                    build_moving_solid(&ball, 200, 167, 7, 7, COLOR_DRKGREY, SOLID_AUTOUP | SOLID_AUTOLEFT, 4);
                    num_blocks = loadLevel(solids, level);
                    StartTimer(0, PADDLE_SPEED);
                    StartTimer(1, ballSpeed);
                    StartTimer(2, SCORE_UPDATE);
        	    }
        	}
        	if (solid_checkIntersectionPaddle(&ball, &paddle) != 0)
        	{
        		non_paddle_hits = 0;
        		play_sound(0);
        	}
        	for (i = 0; i < NUM_BRICKS; i++)
        	{
        	    if (solid_checkIntersectionBrick(&ball, &solids[i], &vertical, &horizontal, random) != 0)
        	    {
        	    	if (solids[i].color == 0x0000 || item_flame == 0)
        	    	{
        	    	   solid_verticalBounce(&ball, vertical, random);
        	    	   solid_horizontalBounce(&ball, horizontal, random);
        	    	}

        	    	StartTimer(3, 1011);//A block was hit, schedule a block redraw
            		if (random == 1)
            		{
            			random = 0;
            		}
            		if (solids[i].color == 0x0000)
            		{
            			non_paddle_hits++;
            			if (non_paddle_hits == 5)
            			{
            				random = 1;
            				non_paddle_hits = 0;
            			}
            			break;//Only allow one brick to be hit at once
            		}
            		else
            		{
            			blocks_destroyed = DropRandomItem(items, item_buffer, solids, blocks_destroyed, i);
            	    	blocks_destroyed++;
        	           display_solid(&solids[i], 1);
        	           solids[i].status = 0;

        	           score++;
        	           printf_setFont_location(5, 128);
        	           _printf("%d", score);
        	           num_blocks--;
        	           play_sound(0);
        	           if (ballSpeed > 20)
        	           {
        	              ballSpeed--;
        	           }
        	           //This game has been finished, reset for the next
        	           if (num_blocks == 0)
        	           {
        	        	   level = NextLevel(&ball, &paddle, solids, &balls, &num_blocks, &ballSpeed, level);
        	           }
        	           break; //Only allow one brick to be hit at once
            		}
        	    }
        	}
        	StartTimer(1, ballSpeed);
        }
        //Auto-move the bullets and check if bullets have intersected any bricks
        if (CheckTimer(7))
        {
        	for (i = 0; i < 15; i++)
        	{
        		if (bullets[i].solid.status > 0)
        		{
        	       if (solid_autoMove(&bullets[i]) == 2)
        	       {
               			bullets[i].solid.status = 0;
               		    display_moving_solid(&bullets[i], 0);
        	       }
        	       else
        	       {
        	          for (j = 0; j < NUM_BRICKS; j++)
        	          {
        	    	     if (solid_checkIntersectionSolid(&bullets[i].solid, &solids[j]) != 0)
        	    	     {
        	    		    bullets[i].solid.status = 0;
        	    		    //Black brick, do nothing
            	    	    if (solids[j].color == 0x0000)
            	    	    {

            	    	    }
            	    	    else
            	    	    {
            	    		   blocks_destroyed = DropRandomItem(items, item_buffer, solids, blocks_destroyed, i);
                	    	   blocks_destroyed++;
            	               display_solid(&solids[j], 1);
            	               solids[j].status = 0;
            	               score++;
            	               printf_setFont_location(5, 128);
            	               _printf("%d", score);
            	               num_blocks--;
            	               play_sound(0);
            	               if (ballSpeed > 20)
            	               {
            	                  ballSpeed--;
            	               }
            	               //This game has been finished, reset for the next
            	               if (num_blocks == 0)
            	               {
            	        	       level = NextLevel(&ball, &paddle, solids, &balls, &num_blocks, &ballSpeed, level);
            	               }
            	               break; //Only allow one brick to be hit at once
            	    	    }
        	    	     }
        	          }
        	       }
        		}
                //Re-display the bullet if it is still moving
        	    if (bullets[i].solid.status == 1)
        	    {
        	       display_moving_solid(&bullets[i], 0);
        	    }
        	}
        	StartTimer(7, 40);
        }
        //Launch a new bullet (if the bullet item is currently in use
        if (CheckTimer(6))
        {
        	build_moving_solid(&bullets[bullet_index], paddle.y_pos - 5, paddle.x_pos + 5, 4, 4, COLOR_BLACK, SOLID_AUTOUP, 4);
        	bullet_index++;
        	if (bullet_index == 15)
        	{
        		bullet_index = 0;
        	}
        	StartTimer(6, 400);
        }
        //Check for pause (center joystick) button
        if (CheckTimer(2))
        {
            if (GetJoystickBtn())
            {
                if (Pause(BRICK_BREAKER_SCORE_ADDR) == 1)
                {
                	AddHighScore(score, BRICK_BREAKER_SCORE_ADDR);
                    break;
                }
                printf_setFont_location(5, 300);
                _printf("Ball %d", balls);
                printf_setFont_location(5, 200);
                _printf("Score %d", score);
                StartTimer(3, 100); //Redraw the screen
            }
            StartTimer(2, PAUSE_CHECK);
        }
        //Redraw blocks timer
        if (CheckTimer(3))
        {
            for (i = 0; i < NUM_BRICKS; i++)
            {
                if (solids[i].status == 1)
                {
                    display_solid(&solids[i], 0);
                }
            }
            StopTimer(3);
        }
        //Auto-move items and check to see if the user has obtained one.
        if (CheckTimer(4))
        {
        	for (i = 0; i < 10; i++)
        	{
        		//Item was captured, enabled it
        		if (drop_item_autoMove(&items[i], &paddle) == 2)
        		{
        			if (items[i].sprite.type == 0)
        			{
        				//Easy break condition to prevent a lot of work on this
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMFLAMEBALL)
        			{
        				item_flame = 1;
        				ball.solid.color = COLOR_RED;
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMBULLET)
        			{
        				item_bullets = 1;
        				StartTimer(6, 300);
        				StartTimer(7, 40);
        				bullet_index = 0;
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMSHORTPADDLE)
        			{
        				item_short_paddle = 1;
        				display_solid(&paddle, 1); //Clear the old paddle
        				paddle_width = 15;
        				build_solid(&paddle, paddle.y_pos, paddle.x_pos, 5, paddle_width, COLOR_DRKGREY);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMLONGPADDLE)
        			{
        				item_long_paddle = 1;
        				display_solid(&paddle, 1); //Clear the old paddle
        				paddle_width = 40;
        				build_solid(&paddle, paddle.y_pos, paddle.x_pos, 5, paddle_width, COLOR_DRKGREY);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMFASTBALL)
        			{
        				ball_speed_fast = 1;
        				ballSpeed = 50; //(50ms per move)
        				StartTimer(1, ballSpeed + 31);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMSLOWBALL)
        			{
        				ball_speed_slow = 1;
        				ballSpeed = 200; //(50ms per move)
        				StartTimer(1, ballSpeed + 31);
        			}
        		}
        		//Item is not active, if it is, disable it
        		else if (items[i].sprite.status == 0)
        		{
        			if (items[i].sprite.type == 0)
        			{
        				//Easy break condition to prevent a lot of work on this
        			}
        			else if (item_flame == 1 && items[i].sprite.type == SPRITE_ITEMFLAMEBALL)
        			{
        	        	item_flame = 0;
        	        	items[i].sprite.type = 0;
        	        	ball.solid.color = COLOR_DRKGREY;
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMBULLET && item_bullets)
        			{
        				item_bullets = 0;
        				items[i].sprite.type = 0;
        				StopTimer(6);
        				//StopTimer(7);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMSHORTPADDLE && item_short_paddle)
        			{
        				item_short_paddle = 0;
        				items[i].sprite.type = 0;
        				display_solid(&paddle, 1); //Clear the old paddle
        				paddle_width = 25;
        				build_solid(&paddle, paddle.y_pos, paddle.x_pos, 5, paddle_width, COLOR_DRKGREY);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMLONGPADDLE && item_long_paddle)
        			{
        				item_long_paddle = 0;
        				items[i].sprite.type = 0;
        				display_solid(&paddle, 1); //Clear the old paddle
        				paddle_width = 25;
        				build_solid(&paddle, paddle.y_pos, paddle.x_pos, 5, paddle_width, COLOR_DRKGREY);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMFASTBALL && ball_speed_fast)
        			{
        				ball_speed_fast = 0;
        				items[i].sprite.type = 0;
        				ballSpeed = BALL_SPEED;
        				StartTimer(1, ballSpeed + 31);
        			}
        			else if (items[i].sprite.type == SPRITE_ITEMSLOWBALL && ball_speed_slow)
        			{
        				ball_speed_slow = 0;
        				items[i].sprite.type = 0;
        				ballSpeed = BALL_SPEED;
        				StartTimer(1, ballSpeed + 31);
        			}
        		}
        	}
        	StartTimer(4, ITEM_DROP_SPEED);
        }
	}


}
void main(void)
{

    IFR = 0x0000;
    IER = 0x0000;

    DisableWatchdog();
    InitSysParameters();                        // Initialization of system parameters
    InitSysTimer();                             // Initialization of system timer

#if (USE_TEST1_PIN)
    TEST_1_INI();
    TEST_1_OFF();
#endif
#if (USE_TEST2_PIN)
    TEST_2_INI();
    TEST_2_OFF();
#endif

    InitWatchdog();                             // Initialization of watchdog
    InitXWatchdog();                            // Initialization of extern watchdog

    InitIndicators();
//    InitSwitches();
    InitKeyboard();

    SetTimer(T_LED, T_LED_D);                   // Set Timers
    SetTimer(T_SEC, T_SEC_D);
    SetTimer(T_SWT, T_SWT_D);

    PieCtrlRegs.PIEACK.all = 0xFFFF;            // Enables PIE to drive a pulse into the CPU
    EINT;                                       // Enable Interrupts at the CPU level

    //--- Enable interrupts
    //SetDBGIER(IER);                             // Configure the DBGIER for realtime debug
    //asm(" CLRC INTM, DBGM");                    // Enable global interrupts and realtime debug

    TimeDev.second = 0;
    TimeDev.minute = 0;
    TimeDev.hour = 0;
    TimeDev.date = 0;

    EnableWatchdog();
//--------------------------------------------------------------------------------------------------
    for(;;)                                     // Main loop
    {
        ServiceWatchdog();                     // Reset Watchdog
//--------------------------------------------------------------------------------------------------
//----------------------------------------------// Time intervals
        if(CheckTimer(T_SEC))
        {
            SetTimer(T_SEC, T_SEC_D);
            if (++TimeDev.second > 59)
            {
                TimeDev.second = 0;
                if (++TimeDev.minute > 59)
                {
                    TimeDev.minute = 0;
                    if (++TimeDev.hour > 23)
                    {
                        TimeDev.hour = 0;
                        TimeDev.date++;
                    }
                }
            }
        }
//--------------------------------------------------------------------------------------------------
//----------------------------------------------// Indication
        if(CheckTimer(T_LED))
        {
            Debug[0]++;
            SetTimer(T_LED, T_LED_D);
//----------------------------------------------// Signaling the state of the system

//            ControlLedWork(TOGGLE);            // LED indicates normal work of the system
            //ControlIndicatorPower(TOGGLE);     // Indication of connection to the power line
//----------------------------------------------// Signaling presence of errors
            /*if (FlagDev.bit.ERR)
            {
                ControlLedError(TOGGLE);
                //ControlIndicatorError(TOGGLE);
            }
            else
            {
                ControlLedError(OFF);
                //ControlIndicatorError(OFF);
            }*/

#if (USE_INDICATOR1)
//----------------------------------------------// Indication of the device working
                                                // in the converter mode
            /*if (FlagDev.bit.WORK)
            {
                ControlIndicatorWork(ON);
            }
            else
            {
                ControlIndicatorWork(OFF);
            }*/
#endif

#if (USE_INDICATOR2)
//----------------------------------------------// Indication of the presence of communication
                                                // with the control device
            /*if (!ErrorDev.bit.CTR)
            {
                ControlIndicatorLink(ON);
            }
            else
            {
                ControlIndicatorLink(OFF);
            }*/
#endif
        }

        if(CheckTimer(T_SWT))
        {

#if (USE_SWT1)
            if (CheckButtonStop() && !CheckButtonStart())
            {
                FlagDev.bit.STOP = 1;
            }
#endif

#if (USE_SWT2)
            if (CheckButtonStart() && !CheckButtonStop())
            {
                FlagDev.bit.PUSK = 1;
            }
#endif

#if (USE_SWT3)
            if (CheckButtonReset())
            {
                FlagDev.bit.RESET = 1;
            }
#endif

#if (USE_ONB_BUT1)
            if (CheckButtonOnboard1())
            {
                ControlLedOnboard3(ON);
            }
            else
            {
                ControlLedOnboard3(OFF);
            }
#endif

#if (USE_KBRD)
            CheckKeyboard();
            if(KeyboardStat.bit.BUT1)
            {
                ControlLedWork(ON);
                Debug[1] = 1;
            }
            else
            {
                ControlLedWork(OFF);
                Debug[1] = 0;
            }
            if(KeyboardStat.bit.BUT2)
            {
                ControlLedError(ON);
                Debug[2] = 1;
            }
            else
            {
                ControlLedError(OFF);
                Debug[2] = 0;
            }
            if(KeyboardStat.bit.BUT4)
            {
                ControlLedOnboard3(ON);
                Debug[3] = 1;
            }
            else
            {
                ControlLedOnboard3(OFF);
                Debug[3] = 0;
            }
            if(KeyboardStat.bit.BUT5)
            {
                ControlLedOnboard4(ON);
                Debug[4] = 1;
            }
            else
            {
                ControlLedOnboard4(OFF);
                Debug[4] = 0;
            }
#endif
        }
//--------------------------------------------------------------------------------------------------
    }
}
Example #20
0
void user_io_poll() {

  if(user_io_dip_switch1()) {
    // check of core has changed from a good one to a not supported on
    // as this likely means that the user is reloading the core via jtag
    unsigned char ct;
    static unsigned char ct_cnt = 0;
    
    EnableIO();
    ct = SPI(0xff);
    DisableIO();
    SPI(0xff);      // needed for old minimig core
    
    if(ct == core_type) 
      ct_cnt = 0;        // same core type, everything is fine
    else {
      // core type has changed
      if(++ct_cnt == 255) {
	// wait for a new valid core id to appear
	while((ct &  0xf0) != 0xa0) {
	  EnableIO();
	  ct = SPI(0xff);
	  DisableIO();
	  SPI(0xff);      // needed for old minimig core
	}

	// reset io controller to cope with new core
	*AT91C_RSTC_RCR = 0xA5 << 24 | AT91C_RSTC_PERRST | AT91C_RSTC_PROCRST; // restart
	for(;;);
      }
    }
  }

  if((core_type != CORE_TYPE_MINIMIG) &&
     (core_type != CORE_TYPE_MINIMIG2) &&
     (core_type != CORE_TYPE_PACE) &&
     (core_type != CORE_TYPE_MIST) &&
     (core_type != CORE_TYPE_ARCHIE) &&
     (core_type != CORE_TYPE_8BIT)) {
    return;  // no user io for the installed core
  }

  if(core_type == CORE_TYPE_MIST) {
    char redirect = tos_get_cdc_control_redirect();

    ikbd_poll();

    // check for input data on usart
    USART_Poll();
      
    unsigned char c = 0;

    // check for incoming serial data. this is directly forwarded to the
    // arm rs232 and mixes with debug output. Useful for debugging only of
    // e.g. the diagnostic cartridge    
    if(!pl2303_is_blocked()) {
      spi_uio_cmd_cont(UIO_SERIAL_IN);
      while(spi_in() && !pl2303_is_blocked()) {
	c = spi_in();
	
	// if a serial/usb adapter is connected it has precesence over
	// any other sink
	if(pl2303_present()) 
	  pl2303_tx_byte(c);
	else {
	  if(c != 0xff) 
	    putchar(c);
	  
	  // forward to USB if redirection via USB/CDC enabled
	  if(redirect == CDC_REDIRECT_RS232)
	    cdc_control_tx(c);
	}
      }
      DisableIO();
    }
    
    // check for incoming parallel/midi data
    if((redirect == CDC_REDIRECT_PARALLEL) || (redirect == CDC_REDIRECT_MIDI)) {
      spi_uio_cmd_cont((redirect == CDC_REDIRECT_PARALLEL)?UIO_PARALLEL_IN:UIO_MIDI_IN);
      // character 0xff is returned if FPGA isn't configured
      c = 0;
      while(spi_in() && (c!= 0xff)) {
	c = spi_in();
	cdc_control_tx(c);
      }
      DisableIO();
      
      // always flush when doing midi to reduce latencies
      if(redirect == CDC_REDIRECT_MIDI)
	cdc_control_flush();
    }
  }

  // poll db9 joysticks
  static int joy0_state = JOY0;
  if((*AT91C_PIOA_PDSR & JOY0) != joy0_state) {
    joy0_state = *AT91C_PIOA_PDSR & JOY0;
    
    unsigned char joy_map = 0;
    if(!(joy0_state & JOY0_UP))    joy_map |= JOY_UP;
    if(!(joy0_state & JOY0_DOWN))  joy_map |= JOY_DOWN;
    if(!(joy0_state & JOY0_LEFT))  joy_map |= JOY_LEFT;
    if(!(joy0_state & JOY0_RIGHT)) joy_map |= JOY_RIGHT;
    if(!(joy0_state & JOY0_BTN1))  joy_map |= JOY_BTN1;
    if(!(joy0_state & JOY0_BTN2))  joy_map |= JOY_BTN2;

    user_io_joystick(joystick_renumber(0), joy_map);
  }
  
  static int joy1_state = JOY1;
  if((*AT91C_PIOA_PDSR & JOY1) != joy1_state) {
    joy1_state = *AT91C_PIOA_PDSR & JOY1;
    
    unsigned char joy_map = 0;
    if(!(joy1_state & JOY1_UP))    joy_map |= JOY_UP;
    if(!(joy1_state & JOY1_DOWN))  joy_map |= JOY_DOWN;
    if(!(joy1_state & JOY1_LEFT))  joy_map |= JOY_LEFT;
    if(!(joy1_state & JOY1_RIGHT)) joy_map |= JOY_RIGHT;
    if(!(joy1_state & JOY1_BTN1))  joy_map |= JOY_BTN1;
    if(!(joy1_state & JOY1_BTN2))  joy_map |= JOY_BTN2;
    
    user_io_joystick(joystick_renumber(1), joy_map);
  }

  user_io_send_buttons(0);

  // mouse movement emulation is continous 
  if(emu_mode == EMU_MOUSE) {
    if(CheckTimer(emu_timer)) {
      emu_timer = GetTimer(EMU_MOUSE_FREQ);
      
      if(emu_state & JOY_MOVE) {
	unsigned char b = 0;
	char x = 0, y = 0;
	if((emu_state & (JOY_LEFT | JOY_RIGHT)) == JOY_LEFT)  x = -1; 
	if((emu_state & (JOY_LEFT | JOY_RIGHT)) == JOY_RIGHT) x = +1; 
	if((emu_state & (JOY_UP   | JOY_DOWN))  == JOY_UP)    y = -1; 
	if((emu_state & (JOY_UP   | JOY_DOWN))  == JOY_DOWN)  y = +1; 
	
	if(emu_state & JOY_BTN1) b |= 1;
	if(emu_state & JOY_BTN2) b |= 2;
	
	user_io_mouse(b, x, y);
      }
    }
  }

  if((core_type == CORE_TYPE_MINIMIG) ||
     (core_type == CORE_TYPE_MINIMIG2)) {
    kbd_fifo_poll();

    // frequently check mouse for events
    if(CheckTimer(mouse_timer)) {
      mouse_timer = GetTimer(MOUSE_FREQ);

      // has ps2 mouse data been updated in the meantime
      if(mouse_flags & 0x80) {
	spi_uio_cmd_cont(UIO_MOUSE);

	// ----- X axis -------
	if(mouse_pos[X] < -128) {
	  spi8(-128);
	  mouse_pos[X] += 128;
	} else if(mouse_pos[X] > 127) {
	  spi8(127);
	  mouse_pos[X] -= 127;
	} else {
	  spi8(mouse_pos[X]);
	  mouse_pos[X] = 0;
	}

	// ----- Y axis -------
	if(mouse_pos[Y] < -128) {
	  spi8(-128);
	  mouse_pos[Y] += 128;
	} else if(mouse_pos[Y] > 127) {
	  spi8(127);
	  mouse_pos[Y] -= 127;
	} else {
	  spi8(mouse_pos[Y]);
	  mouse_pos[Y] = 0;
	}

	spi8(mouse_flags & 0x03);
	DisableIO();

	// reset flags
	mouse_flags = 0;
      }
    }
  }

  if(core_type == CORE_TYPE_MIST) {
    // do some tos specific monitoring here
    tos_poll();
  }

  if(core_type == CORE_TYPE_8BIT) {
    unsigned char c = 1, f, p=0;

    // check for input data on usart
    USART_Poll();
      
    // check for serial data to be sent

    // check for incoming serial data. this is directly forwarded to the
    // arm rs232 and mixes with debug output.
    spi_uio_cmd_cont(UIO_SIO_IN);
    // status byte is 1000000A with A=1 if data is available
    if((f = spi_in(0)) == 0x81) {
      iprintf("\033[1;36m");
      
      // character 0xff is returned if FPGA isn't configured
      while((f == 0x81) && (c!= 0xff) && (c != 0x00) && (p < 8)) {
	c = spi_in();
	if(c != 0xff && c != 0x00) 
	  iprintf("%c", c);

	f = spi_in();
	p++;
      }
      iprintf("\033[0m");
    }
    DisableIO();

    // sd card emulation
    {
      static char buffer[512];
      static uint32_t buffer_lba = 0xffffffff;
      uint32_t lba;
      uint8_t c = user_io_sd_get_status(&lba);

      // valid sd commands start with "5x" to avoid problems with
      // cores that don't implement this command
      if((c & 0xf0) == 0x50) {

	// debug: If the io controller reports and non-sdhc card, then
	// the core should never set the sdhc flag
	if((c & 3) && !MMC_IsSDHC() && (c & 0x04))
	  iprintf("WARNING: SDHC access to non-sdhc card\n");
 	
	// check if core requests configuration
	if(c & 0x08) {
	  iprintf("core requests SD config\n");
	  user_io_sd_set_config();
	}

	// check if system is trying to access a sdhc card from 
	// a sd/mmc setup

	// check if an SDHC card is inserted
	if(MMC_IsSDHC()) {
	  static char using_sdhc = 1;

	  // SD request and 
	  if((c & 0x03) && !(c & 0x04)) {
	    if(using_sdhc) {
	      // we have not been using sdhc so far? 
	      // -> complain!
	      ErrorMessage(" This core does not support\n"
			   " SDHC cards. Using them may\n"
			   " lead to data corruption.\n\n"
			   " Please use an SD card <2GB!", 0);
	      using_sdhc = 0;
	    }
	  } else
	    // SDHC request from core is always ok
	    using_sdhc = 1;
	}

	if((c & 0x03) == 0x02) {
	  // only write if the inserted card is not sdhc or
	  // if the core uses sdhc
	  if((!MMC_IsSDHC()) || (c & 0x04)) {  
	    uint8_t wr_buf[512];

	    if(user_io_dip_switch1())
	      iprintf("SD WR %d\n", lba);

	    // if we write the sector stored in the read buffer, then
	    // update the read buffer with the new contents
	    if(buffer_lba == lba) 
	      memcpy(buffer, wr_buf, 512);

	      buffer_lba = 0xffffffff;

	    // Fetch sector data from FPGA ...
	    spi_uio_cmd_cont(UIO_SECTOR_WR);
	    spi_block_read(wr_buf);
	    DisableIO();

	    // ... and write it to disk
	    DISKLED_ON;

	    if(sd_image.size) {
	      FileSeek(&sd_image, lba, SEEK_SET);
	      FileWrite(&sd_image, wr_buf);
	    } else
	      MMC_Write(lba, wr_buf);

	    DISKLED_OFF;
	  }
	}

	if((c & 0x03) == 0x01) {

	  if(user_io_dip_switch1())
	    iprintf("SD RD %d\n", lba);
	  
	  // are we using a file as the sd card image?
	  // (C64 floppy does that ...)
	  if(buffer_lba != lba) {
	    DISKLED_ON;
	    if(sd_image.size) {
	      FileSeek(&sd_image, lba, SEEK_SET);
	      FileRead(&sd_image, buffer);
	    } else {
	      // sector read
	      // read sector from sd card if it is not already present in
	      // the buffer
	      MMC_Read(lba, buffer);
	    }
	    buffer_lba = lba;
	    DISKLED_OFF;
	  }

	  if(buffer_lba == lba) {
	    // data is now stored in buffer. send it to fpga
	    spi_uio_cmd_cont(UIO_SECTOR_RD);
	    spi_block_write(buffer);
	    DisableIO();

	    // the end of this transfer acknowledges the FPGA internal
	    // sd card emulation
	  }

	  // just load the next sector now, so it may be prefetched
	  // for the next request already
	  DISKLED_ON;
	  if(sd_image.size) {
	    FileSeek(&sd_image, lba+1, SEEK_SET);
	    FileRead(&sd_image, buffer);
	  } else {
	    // sector read
	    // read sector from sd card if it is not already present in
	    // the buffer
	    MMC_Read(lba+1, buffer);
	  }
	  buffer_lba = lba+1;
	  DISKLED_OFF;
	}
      }
    }

    // frequently check ps2 mouse for events
    if(CheckTimer(mouse_timer)) {
      mouse_timer = GetTimer(MOUSE_FREQ);

      // has ps2 mouse data been updated in the meantime
      if(mouse_flags & 0x08) {
	unsigned char ps2_mouse[3];

	// PS2 format: 
	// YOvfl, XOvfl, dy8, dx8, 1, mbtn, rbtn, lbtn
	// dx[7:0]
	// dy[7:0]
	ps2_mouse[0] = mouse_flags;

	// ------ X axis -----------
	// store sign bit in first byte
	ps2_mouse[0] |= (mouse_pos[X] < 0)?0x10:0x00;
	if(mouse_pos[X] < -255) {
	  // min possible value + overflow flag
	  ps2_mouse[0] |= 0x40;
	  ps2_mouse[1] = -128;
	} else if(mouse_pos[X] > 255) {
	  // max possible value + overflow flag
	  ps2_mouse[0] |= 0x40;
	  ps2_mouse[1] = 255;
	} else 
	  ps2_mouse[1] = mouse_pos[X];

	// ------ Y axis -----------
	// store sign bit in first byte
	ps2_mouse[0] |= (mouse_pos[Y] < 0)?0x20:0x00;
	if(mouse_pos[Y] < -255) {
	  // min possible value + overflow flag
	  ps2_mouse[0] |= 0x80;
	  ps2_mouse[2] = -128;
	} else if(mouse_pos[Y] > 255) {
	  // max possible value + overflow flag
	  ps2_mouse[0] |= 0x80;
	  ps2_mouse[2] = 255;
	} else 
	  ps2_mouse[2] = mouse_pos[Y];
	
	// collect movement info and send at predefined rate
	iprintf("PS2 MOUSE: %x %d %d\n", 
		ps2_mouse[0], ps2_mouse[1], ps2_mouse[2]);

	spi_uio_cmd_cont(UIO_MOUSE);
	spi8(ps2_mouse[0]);
	spi8(ps2_mouse[1]);
	spi8(ps2_mouse[2]);
	DisableIO();

	// reset counters
	mouse_flags = 0;
	mouse_pos[X] = mouse_pos[Y] = 0;
      }
    }

    // --------------- THE FOLLOWING IS DEPRECATED AND WILL BE REMOVED ------------
    // ------------------------ USE SD CARD EMULATION INSTEAD ---------------------

    // raw sector io for the atari800 core which include a full
    // file system driver usually implemented using a second cpu
    static unsigned long bit8_status = 0;
    unsigned long status;

    /* read status byte */
    EnableFpga();
    SPI(UIO_GET_STATUS);
    status = SPI(0);
    status = (status << 8) | SPI(0);
    status = (status << 8) | SPI(0);
    status = (status << 8) | SPI(0);
    DisableFpga();

    if(status != bit8_status) {
      unsigned long sector = (status>>8)&0xffffff;
      char buffer[512];

      bit8_status = status;
      
      // sector read testing 
      DISKLED_ON;

      // sector read
      if(((status & 0xff) == 0xa5) || ((status & 0x3f) == 0x29)) {

	// extended command with 26 bits (for 32GB SDHC)
	if((status & 0x3f) == 0x29) sector = (status>>6)&0x3ffffff;

	bit8_debugf("SECIO rd %ld", sector);

	if(MMC_Read(sector, buffer)) {
	  // data is now stored in buffer. send it to fpga
	  EnableFpga();
	  SPI(UIO_SECTOR_SND);     // send sector data IO->FPGA
	  spi_block_write(buffer);
	  DisableFpga();
	} else
	  bit8_debugf("rd %ld fail", sector);
      }

      // sector write
      if(((status & 0xff) == 0xa6) || ((status & 0x3f) == 0x2a)) {

	// extended command with 26 bits (for 32GB SDHC)
	if((status & 0x3f) == 0x2a) sector = (status>>6)&0x3ffffff;

	bit8_debugf("SECIO wr %ld", sector);

	// read sector from FPGA
	EnableFpga();
	SPI(UIO_SECTOR_RCV);     // receive sector data FPGA->IO
	spi_block_read(buffer);
	DisableFpga();

	if(!MMC_Write(sector, buffer)) 
	  bit8_debugf("wr %ld fail", sector);
      }

      DISKLED_OFF;
    }
Example #21
0
void cdc_control_poll(void) {
  // flush out queue every now and then
  if(flush_timer && CheckTimer(flush_timer)) {
    cdc_control_flush();
    flush_timer = 0;
  }

  // low level usb handling happens inside usb_cdc_poll
  if(usb_cdc_poll()) {
    uint16_t read, i;
    char data[AT91C_EP_OUT_SIZE];

    // check for user input
    if((read = usb_cdc_read(data, AT91C_EP_OUT_SIZE)) != 0) {
      
      switch(tos_get_cdc_control_redirect()) {
      case CDC_REDIRECT_RS232:
	iprintf("RS232 forward:\n");
	hexdump(data, read, 0);

	user_io_serial_tx(data, read);
	break;
	
      case CDC_REDIRECT_CONTROL:
	for(i=0;i<read;i++) {
	  // force lower case
	  if((data[i] >= 'A') && (data[i] <= 'Z'))
	    data[i] = data[i] - 'A' + 'a';
	  
	  switch(data[i]) {
	  case '\r':
	    cdc_puts("\n\033[7m <<< MIST board controller >>> \033[0m");
	    cdc_puts("Firmware version ATH" VDATE);
	    cdc_puts("Commands:");
	    cdc_puts("\033[7mR\033[0meset");
	    cdc_puts("\033[7mC\033[0moldreset");
	    cdc_puts("\033[7mD\033[0mebug output redirect");
	    cdc_puts("R\033[7mS\033[0m232 redirect");
	    cdc_puts("\033[7mP\033[0marallel redirect");
	    cdc_puts("\033[7mM\033[0mIDI redirect");
	    cdc_puts("");
	    break;
	    
	  case 'r':
	    cdc_puts("Reset ...");
	    tos_reset(0);
	    break;
	    
	  case 'c':
	    cdc_puts("Coldreset ...");
	    tos_reset(1);
	    break;
	    
	  case 'd':
	    cdc_puts("Debug output redirect enabled");
	    tos_set_cdc_control_redirect(CDC_REDIRECT_DEBUG);
	    break;
	    
	  case 's':
	    cdc_puts("RS232 redirect enabled");
	    tos_set_cdc_control_redirect(CDC_REDIRECT_RS232);
	    break;
	    
	  case 'p':
	    cdc_puts("Parallel redirect enabled");
	    tos_set_cdc_control_redirect(CDC_REDIRECT_PARALLEL);
	    break;
	    
	  case 'm':
	    cdc_puts("MIDI redirect enabled");
	    tos_set_cdc_control_redirect(CDC_REDIRECT_MIDI);
	    break;
	    
	  }
	  break;
	}
  
	default:
	  break;
      }
    }
  }
}
Example #22
0
bool AntiCheat::_DoAntiCheatCheck(AntiCheatCheck checktype)
{
    m_currentConfig = _FindConfig(checktype);

    if (!m_currentConfig)
        return true;

    AntiCheatCheckEntry* _check = _FindCheck(checktype);

    if (!_check)
        return true;

    bool checkpassed = true;

    if (_check->active && CheckTimer(checktype) && CheckNeeded(checktype))
    {
        if (m_counters.find(checktype) == m_counters.end())
            m_counters.insert(std::make_pair(checktype, 0));

        if (!(this->*(_check->Handler))() && !isImmune())
        {
            if (m_currentConfig->disableOperation)
                checkpassed = false;
            ++m_counters[checktype];

            if (m_lastalarmtime.find(checktype) == m_lastalarmtime.end())
                m_lastalarmtime.insert(std::make_pair(checktype, 0));

            m_lastalarmtime[checktype] = WorldTimer::getMSTime();

            if (m_counters[checktype] >= m_currentConfig->alarmsCount)
            {
                m_currentCheckResult.insert(0,m_currentConfig->description.c_str());
                DoAntiCheatAction(checktype, m_currentCheckResult);
                m_counters[checktype] = 0;
                m_currentCheckResult.clear();
            }
        }
        else
        {
            if (WorldTimer::getMSTimeDiff(m_lastalarmtime[checktype],WorldTimer::getMSTime()) > sWorld.getConfig(CONFIG_UINT32_ANTICHEAT_ACTION_DELAY)
                    || (m_currentConfig->checkParam[0] > 0 && m_currentConfig->alarmsCount > 1 && WorldTimer::getMSTimeDiff(m_lastalarmtime[checktype],WorldTimer::getMSTime()) > m_currentConfig->checkParam[0]))
            {
                m_counters[checktype] = 0;
            }
        }
        m_oldCheckTime[checktype] = WorldTimer::getMSTime();
    }


    // Subchecks, if exist
    if (checktype < 100 && _check->active && CheckNeeded(checktype))
    {
        for (int i=1; i < 99; ++i )
        {
            uint32 subcheck = checktype * 100 + i;

            if (AntiCheatConfig const* config = _FindConfig(AntiCheatCheck(subcheck)))
            {
                checkpassed |= _DoAntiCheatCheck(AntiCheatCheck(subcheck));
            }
            else
                break;
        }
    }
    // If any of checks fail, return false
    return checkpassed;
};
Example #23
0
int __asm __saveds L_Module_Entry(
	register __a0 struct List *files,
	register __a1 struct Screen *callback1,
	register __a2 IPCData *callback2,
	register __a3 IPCData *main_ipc,
	register __d0 ULONG mod_id,
	register __d1 ULONG mod_data)
{
	NewConfigWindow newwin;
	struct Window *window;
	ObjectList *objlist;
	Att_List *list;
	TimerHandle *timer;
	short count=0;
	struct Task *task;
	rego_data test={0};

	// Call back to main program
	((void __asm (*)
		(register __a0 struct List *,
		register __a1 rego_data *,
		register __a2 rego_data *,
		register __a3 void **,
		register __d0 ULONG))callback2)(files,&test,&rego,&newwin.parent,global_checksum);

	// Won't work with DOpus library > 55
	if (DOpusBase->lib_Version>55)
		return 0;

	// Fix IPC
	main_ipc->proc=(struct Process *)FindTask(0);
	main_ipc->proc->pr_Task.tc_UserData=main_ipc;
	main_ipc->list=0;
	if (!main_ipc->command_port)
		main_ipc->command_port=CreateMsgPort();

	// Fill out new window
	newwin.parent=0;
	newwin.dims=&serial_window;
	newwin.title=GetString(locale,MSG_TITLE);
	newwin.locale=locale;
	newwin.port=0;
	newwin.flags=WINDOW_VISITOR|WINDOW_NO_CLOSE|WINDOW_REQ_FILL|WINDOW_AUTO_KEYS;
	newwin.font=0;

	// Initialise timer
	if (!(timer=AllocTimer(UNIT_VBLANK,0)))
		return 0;

	// Open window
	if (!(window=OpenConfigWindow(&newwin)) ||
		!(objlist=AddObjectList(window,serial_objects)))
	{
		CloseConfigWindow(window);
		FreeTimer(timer);
		return 0;
	}

	// Set ok flag
	*((ULONG *)mod_data)|=(1<<28);

	// Display text
	list=build_text_display(window,objlist,message0);

	// Start timer
	StartTimer(timer,DELAY,0);

	// Event loop
	FOREVER
	{
		struct IntuiMessage *msg;
		BOOL break_flag=0;

		// Timer returned?
		if (CheckTimer(timer))
		{
			// Exit
			break_flag=1;
		}

		// Any Intuition messages?
		while (msg=GetWindowMsg(window->UserPort))
		{
			struct IntuiMessage copy_msg;

			// Copy message and reply
			copy_msg=*msg;
			ReplyWindowMsg(msg);

			// Gadget?
			if (copy_msg.Class==IDCMP_GADGETUP)
			{
				struct Gadget *gadget;

				// Get gadget
				gadget=(struct Gadget *)copy_msg.IAddress;

				// Look at gadget ID
				switch (gadget->GadgetID)
				{
					// Ok
					case GAD_SERIAL_OKAY:

						break_flag=1;
						break;
				}
			}
		}

		if (break_flag) break;

		Wait(1<<window->UserPort->mp_SigBit|1<<timer->port->mp_SigBit);
	}

	// Close window
	CloseConfigWindow(window);

	// Free list and timer
	Att_RemList(list,0);
	FreeTimer(timer);

	// Success
	return 1;
}
Example #24
0
void WaitTimer(unsigned long time)
{
    time = GetTimer(time);
    while (!CheckTimer(time));
}
Example #25
0
bool LineInControl(void)
{
	uint16_t Msg = 0;
	SW_TIMER LineInTimer;

	APP_DBG("Enter LineInControl...\n");

	if(!IsLineInLink())
	{
		APP_DBG("Exit LineInControl...\n");
		return TRUE;
	}

#ifndef FUNC_MIXER_SRC_EN
	AudioSampleRateSet(44100);
#endif	
	
	SoundRemind(SOUND_LINEIN); 
    
#ifdef FUNC_TREB_BASS_EN
	if(gSys.EqStatus == 0)
	{
		TrebBassSet(gSys.TrebVal, gSys.BassVal);
	}
#endif
	
	if(gSys.MicEnable)
	{
		MixerMute(MIXER_SOURCE_ANA_MONO);	
		MixerMute(MIXER_SOURCE_MIC);
	}
	else
	{
		MixerMute(MIXER_SOURCE_ANA_STERO);
	}
	WaitMs(20);
	
	AudioAnaSetChannel(gSys.MicEnable ? AUDIO_CH_MIC_LINEIN : AUDIO_CH_LINEIN);
	
	if(gSys.MicEnable)
	{
		MixerUnmute(MIXER_SOURCE_ANA_MONO);	
		MixerUnmute(MIXER_SOURCE_MIC);
	}
	else
	{
		MixerUnmute(MIXER_SOURCE_ANA_STERO);
	}
	
	// ÏûÏ¢×¢²á
    if(gSys.MuteFlag)
	{
    	gSys.MuteFlag = 0;
		AudioPlayerMute(gSys.MuteFlag);
	} 

	InitTimer(&LineInTimer, 250, LineInLedCb);
	StartTimer(&LineInTimer);
	AudioSysInfoSetBreakPoint();

	SetModeSwitchState(MODE_SWITCH_STATE_DONE);
	
	while(Msg != MSG_COMMON_CLOSE)
	{
		//led light timer
		CheckTimer(&LineInTimer);
		
		Msg = MsgRecv(5);

		switch(Msg)
		{			
			case MSG_MODE:        //working mode changing
				Msg = MSG_COMMON_CLOSE;
				break;
			
			case MSG_POWER:
				gSys.NextModuleID = MODULE_ID_STANDBY;
				Msg = MSG_COMMON_CLOSE;
				break;
			
#ifdef FUNC_RECORD_EN
			case MSG_REC:  //¼Òô
				gSys.ModuleIDBackUp = gSys.CurModuleID;
				gSys.NextModuleID = MODULE_ID_RECORDER;
				gSys.RecordState = RECORD_STATE_REC;
				gSys.RecordSource = RECORD_SOURCE_LINEIN;
				Msg = MSG_COMMON_CLOSE;
				break;
#endif
           
#ifdef FUNC_REC_PLAYBACK_EN
			case MSG_REC_PLAYBACK:
				EnterRecBackPlay(gSys.CurModuleID, IsUDiskLink() ? DEV_ID_USB : DEV_ID_SD, TRUE, 0, 0);
				break;
#endif

			default:
				CommonMsgProccess(Msg);
				break;

		}
	}
#if (defined(FUNC_BREAKPOINT_EN) && (defined(FUNC_USB_EN) || defined(FUNC_CARD_EN)))
	{
		BP_SYS_INFO *pBpSysInfo;
		pBpSysInfo = (BP_SYS_INFO *)BP_GetInfo(BP_SYS_INFO_TYPE);
		BP_SET_ELEMENT(pBpSysInfo->Volume, gSys.Volume);
        BP_SET_ELEMENT(pBpSysInfo->Eq, gSys.Eq);
		BP_SaveInfo(BP_SAVE2NVM);
	}
#endif
	AudioAnaSetChannel(gSys.MicEnable ? AUDIO_CH_MIC : AUDIO_CH_NONE);	
	APP_DBG("leave LineInControl...\n");
	return TRUE;//OK
}
Example #26
0
/******************************************************
* PONG
* DESCRIPTION: JConsole2 Portable implementation of pong
* Created: 8/28/2013
******************************************************/
void Pong(char autoAi)
{
   char hit = 0;
   char pong_ball_start = 0;
   unsigned int userScore = 0;
   unsigned int compScore = 0;
   unsigned int highScore = EEProm_Read_16(pongHighScore);
   unsigned int ballSpeed = PONG_INITIALBALLSPEED;
   struct Paddle playerPaddle;
   struct Paddle aiPaddle;
   struct Solid ball;
   LcdClear();

   //Construct game objects
   constructPaddle2(&aiPaddle, 74, 1, 10);
   constructPaddle2(&playerPaddle, 7, 1, 10);
   displayPaddle(&playerPaddle, 0);
   displayPaddle(&aiPaddle, 0);
   displayPongScore(&userScore, &compScore);
   reset(&ball, 15, 1, 3, 3, 1);

   //Start timers
   StartTimer(0, PONG_PLAYERMOVETIME);  //Move player timer
   StartTimer(1, ballSpeed);  //Move player timer

   for (;;)
   {
	  if (CheckTimer(0))
	  {
		  if (GetDown())
		  {
		     paddle_moveDown(&playerPaddle);
		  }
		  else if (GetUp())
		  {
			  paddle_moveUp(&playerPaddle);
		  }
		  else if (GetEnterButton()) //Pause
		  {
			 if (Pause(showPongScore, userScore,  compScore, highScore) == 1)
			 {
			     return;
			 }
			 displayPaddle(&playerPaddle, 0);
			 displayPaddle(&aiPaddle, 0);
			 displaySolid(&ball, 0);
			 displayPongScore(&userScore, &compScore);
		  }
		  StartTimer(0, PONG_PLAYERMOVETIME);  //Move player timer
	  }
      if (CheckTimer(1))
      {
         //If ball moves and hits a wall, make a sound
         if (autoMoveSolid(&ball) > 1)
         {
        	 SendData(SOUND_BLOCK_DESTROYED);
         }
         aiMove(&aiPaddle, &ball); //Move computer players paddle
         if (autoAi == 1)
         {
            aiMove(&playerPaddle, &ball);
         }
         hit = checkForHit(&aiPaddle, &ball) + checkForHit(&playerPaddle, &ball);   //Check to see if ball hit either paddle
         if (hit != 0)
         {
        	 SendData(SOUND_BLOCK_DESTROYED);
        	displayPongScore(&userScore, &compScore);
        	if (ballSpeed > 10)
        	{
        	   ballSpeed = ballSpeed - 1;
        	}
         }
         //Ball hit on players side
         if (ball.xLocation == 1)
         {
            compScore++;
            displayPongScore(&userScore, &compScore);
            displayPaddle(&playerPaddle, 0);
            displayPaddle(&aiPaddle, 0);
            randomBallStart(&ball, &pong_ball_start);
         }
         //Ball hit on computers side
         else if (ball.xLocation == 76)
         {
            userScore++;
            displayPongScore(&userScore, &compScore);
            displayPaddle(&playerPaddle, 0);
            displayPaddle(&aiPaddle, 0);
            randomBallStart(&ball, &pong_ball_start);
            if (userScore > highScore)
            {
               highScore = userScore;
               EEProm_Write_16(highScore, pongHighScore);
            }
         }
         StartTimer(1, ballSpeed);  //Move player timer
      }
   }

}
Example #27
0
bool SdHandshake(void)
// Tries to talk to the inserted SD card and set up an SPI interface.
// Since this is a micro SD slot, we don't need to support MMC cards (they wouldn't fit in the slot).
// We also do not support SDHC, since it costs more, we have orders of magnitude more storage than necessary as is, and the interface is a BIT different.  Could fix this if people whine.
// Returns true if we successfully initialize the all the stuff we need to do to talk to the card.
// NOTE -- this process takes time, and will hang operation for hundreds of milliseconds on a successful call.
{
	unsigned char
		ocr[4],
		i;
	unsigned int
		n;
	bool
		cardValid;	// Is this a micro SD card or some random bit of plastic and silicon?

	// Card starts in SD mode, and needs a bunch of clocks (74 at least) to reach "idle" state.  CS must be high.  ChaN suggest MOSI stays high too which makes sense.

	EndSdTransfer();	// Bring CS high
	for(i=0;i<20;i++)
	{
		UCSR1A|=(1<<TXC1);			// Clear transmit complete flag
		TransferSdByte(DUMMY_BYTE);	// Transfer ten dummy bytes (80 clocks).
	}	
	while(!(UCSR1A&(1<<TXC1)))	// Spin until the last clocks go out
		;


	// Jacked from SD Fat lib, which suggests doing the following to prevent "re-init hang from cards in partial read".  Makes sense.

	StartSdTransfer();						
	for(n=0;n<SD_BLOCK_LENGTH;n++)
	{
		UCSR1A|=(1<<TXC1);			// Clear transmit complete flag
		TransferSdByte(0xFF);	
	}
	while(!(UCSR1A&(1<<TXC1)))	// Spin until the last clocks go out
		;
	EndSdTransfer();

	// Should be in "idle mode" now.  Set SPI mode by asserting the CS and sending CMD 0.
	cardValid=false;			// Card not valid until we say it is.	
	SendSdCommand(CMD0,0);		// Send first time for good measure, also to make sure onboard pullups get to where they need to be.
	while(!(UCSR1A&(1<<TXC1)))	// Spin until the last clocks go out
		;
	EndSdTransfer();

	// Send CMD0 again, actually check response now.
	if(SendSdCommand(CMD0,0)==0x01)		// Tell card to enter idle state.  If we get the right response, keep going.
	{
		EndSdTransfer();					// Bring CS high

		if(SendSdCommand(CMD8,0x1AA)==1)	// Check card voltage.  This is only supported in SDC v2, so we're either a v2 standard density card or an SDHC card
		{
			for(i=0;i<4;i++)						// This is an "R7" response, so we need to grab four more bytes.
			{
				ocr[i]=TransferSdByte(DUMMY_BYTE);	// Inhale OCR bytes
			}

			SendDummyByte();		// Send extra FF after multibyte response. 
			EndSdTransfer();		// Bring CS high

			if(ocr[2] == 0x01 && ocr[3] == 0xAA)	// The card can work at vdd range of 2.7-3.6V (bail if it can't)
			{				
				SetTimer(TIMER_SD,SECOND);

				while((!(CheckTimer(TIMER_SD)))&&(SendSdCommand(ACMD41,0)!=0))	// Initialize card, disable high capacity.  If this returns 0, we're good to go (0 is the result once the card is done initializing, takes a long time (we give it a second per the SD spec))
				{
					EndSdTransfer();	// Bring CS high. NOTE -- Sending an ACMD41 with the HCS bit set will tell the card we're cool with HIGH CAPACITY SD cards.  If we don't set this bit, and we're talking to an SDHC card, the card will always return busy.  This is what we want.
					HandleSoftclock();	// Keep the timer timing.
				}		
				
				if(!(CheckTimer(TIMER_SD)))		// Initialized! (didn't time out)
				{
					while((!(CheckTimer(TIMER_SD)))&&(SendSdCommand(CMD58,0)!=0))	// Read card capacity -- I think we might need to do this even though we throw out the results.
					{
						SendDummyByte();		// Send extra FF (it's busy)
						HandleSoftclock();	// Keep the timer timing.
						EndSdTransfer();		// Bring CS high.
					}
					if(!(CheckTimer(TIMER_SD)))		// Didn't time out.
					{
						for(i=0;i<4;i++)						// This is an "R3" response, so we need to grab four more bytes.
						{
							ocr[i]=TransferSdByte(DUMMY_BYTE);	// Inhale OCR bytes
						}

						SendDummyByte();			// Send extra FF after multibyte response. 
						EndSdTransfer();			// Bring CS high.

						SendSdCommand(CMD16,SD_BLOCK_LENGTH);	// Set block length to 512.
						EndSdTransfer();						// Bring CS high.
						SendDummyByte();						
						cardValid=true;				// SD card present, and standard capacity.
					}
				}
			}
		}
		else	// We're either an SDC v1 card or an MMC.  SDC v1 is OK.
		{
			SendDummyByte();					// Send extra FF after multibyte response. 
			EndSdTransfer();					// Bring CS high
			if(SendSdCommand(ACMD41,0)<=1)		// If we don't get an error trying to initialize the SD card, keep going (MMC will bail)	
			{
				EndSdTransfer();			// Bring CS high.
				SetTimer(TIMER_SD,SECOND);

				while((!(CheckTimer(TIMER_SD)))&&(SendSdCommand(ACMD41,0)!=0))	// Initialize card, disable high capacity.  If this returns 0, we're good to go 
				{
					HandleSoftclock();	// Keep the timer timing.
					EndSdTransfer();	// Bring CS high. NOTE -- Sending an ACMD41 with the HCS bit set will tell the card we're cool with HIGH CAPACITY SD cards.  If we don't set this bit, and we're talking to an SDHC card, the card will always return busy.  This is what we want.
				}		

				if(!(CheckTimer(TIMER_SD)))		// Initialized!
				{
					SendSdCommand(CMD16,SD_BLOCK_LENGTH);	// Set block length to 512.
					EndSdTransfer();						// Bring CS high.
					cardValid=true;							// SDC v1 card, good to go
				}
			}
		}
	}

	EndSdTransfer();	// Bring CS high
	return(cardValid);	// Report success or failure of initialization -- fails on timeout or bad response.  Bad response is an invalid card or no card, timeout means card didn't initialize (which might mean it's high capacity).
}
Example #28
0
// Group handler
void __saveds backdrop_group_handler(void)
{
	IPCData *ipc;
	GroupData *group=0;

	// Do group
	if (ipc=IPC_ProcStartup((ULONG *)&group,backdrop_group_init))
	{
		// Read objects
		SetBusyPointer(group->window);
		backdrop_read_group_objects(group);
		ClearPointer(group->window);

		// Event loop
		FOREVER
		{
			IPCMessage *msg;
			BOOL quit_flag=0;

			// Got an AppWindow?
			if (group->appwindow)
			{
				DOpusAppMessage *amsg;
				BOOL beep=0;

				// AppMessages?
				while (amsg=(DOpusAppMessage *)GetMsg(group->appport))
				{
					short arg;
					char path[256];
					BackdropObject *drop_obj;

					// Lock backdrop list
					lock_listlock(&group->info->objects,1);

					// Set busy pointer
					if (group->window) SetBusyPointer(group->window);

					// Dropped on an object?
					if (drop_obj=backdrop_get_object(group->info,amsg->da_Msg.am_MouseX,amsg->da_Msg.am_MouseY,0))
					{
						USHORT qual;

						// Get qualifiers
						qual=(InputBase)?PeekQualifier():0;
	
						// Is shift/alt down?
						if (qual&(IEQUALIFIER_LSHIFT|IEQUALIFIER_LALT)==(IEQUALIFIER_LSHIFT|IEQUALIFIER_LALT))
						{
							// Get path of first file
							GetWBArgPath(&amsg->da_Msg.am_ArgList[0],path,256);

							// Replace the image
							backdrop_replace_icon_image(group->info,path,drop_obj);
						}

						// Run program with args
						else
						backdrop_object_open(
							group->info,
							drop_obj,
							0,
							0,
							amsg->da_Msg.am_NumArgs,
							amsg->da_Msg.am_ArgList);
					}

					// Otherwise, adding objects to the group
					else
					for (arg=0;arg<amsg->da_Msg.am_NumArgs;arg++)
					{
						// Valid name?
						if (*amsg->da_Msg.am_ArgList[arg].wa_Name)
						{
							short x,y;

							// Get full path name
							GetWBArgPath(&amsg->da_Msg.am_ArgList[arg],path,256);

							// Default to no position
							x=-1;
							y=-1;

							// Dopus app message?
							if (CheckAppMessage(amsg))
							{
								// Get icon position
								x=amsg->da_DragOffset.x+amsg->da_Msg.am_MouseX+amsg->da_DropPos[arg].x;
								y=amsg->da_DragOffset.y+amsg->da_Msg.am_MouseY+amsg->da_DropPos[arg].y;
							}

							// Add group object
							backdrop_group_add_object(group->name,group->info,path,x,y);
						}

						// Otherwise, set beep flag for error
						else
						if (!beep)
						{
							beep=1;
							DisplayBeep(group->window->WScreen);
						}
					}

					// Clear busy pointer
					if (group->window) ClearPointer(group->window);

					// Unlock backdrop list
					unlock_listlock(&group->info->objects);

					// Reply to message
					ReplyMsg((struct Message *)amsg);
				}
			}

			// Icon notification
			if (group->info->notify_req)
			{
				DOpusNotify *notify;

				// Get notify message	
				if (notify=(DOpusNotify *)GetMsg(group->info->notify_port))
					backdrop_check_notify(group->info,notify,0);
			}

			// IPC messages?
			while (msg=(IPCMessage *)GetMsg(ipc->command_port))
			{
				// Look at message
				switch (msg->command)
				{
					// Activate
					case IPC_ACTIVATE:

						// Bring window to front
						if (group->window)
							backdrop_show_group(group);
						break;


					// Quit
					case IPC_QUIT:
						quit_flag=1;
						group->got_quit=1;
						break;


					// Hide
					case IPC_HIDE:
						backdrop_hide_group(group);
						break;


					// Show
					case IPC_SHOW:
						group->screen=(struct Screen *)msg->data;
						backdrop_show_group(group);
						break;


					// Reset (menus)
					case IPC_RESET:

						// Gotta window?
						if (group->window)
						{
							// Reset menus?
							if (msg->flags)
							{
								display_free_menu(group->window);
								display_get_menu(group->window);
							}

							// Fix menus
							display_fix_menu(group->window,WINDOW_GROUP,0);
						}
						break;


					// New font
					case GROUP_NEW_FONT:

						// Get new font
						backdrop_get_font(group->info);

						// Redraw objects
						backdrop_show_objects(group->info,BDSF_CLEAR|BDSF_RESET);
						break;


					// New name
					case GROUP_NEW_NAME:

						// Copy name
						strcpy(group->name,msg->data_free);

						// Update window title
						if (group->window) SetWindowTitles(group->window,group->name,(char *)-1);
						break;


					// Add a new icon
					case GROUP_ADD_ICON:

						// Lock backdrop list
						lock_listlock(&group->info->objects,1);

						// Set busy pointer
						if (group->window) SetBusyPointer(group->window);

						// Add object
						backdrop_group_add_object(group->name,group->info,msg->data_free,-1,-1);

						// Clear busy pointer
						if (group->window) ClearPointer(group->window);

						// Unlock backdrop list
						unlock_listlock(&group->info->objects);
						break;


					// New backfill pattern
					case LISTER_BACKFILL_CHANGE:

						// Window open?
						if (group->window)
						{
							// Install appropriate hook
							InstallLayerHook(
								group->window->WLayer,
								(msg->flags)?&group->pattern.hook:LAYERS_BACKFILL);

							// Redraw window
							erase_window(group->window);

							// Redraw icons
							backdrop_show_objects(group->info,0);
						}
						break;


					// Delete from group
					case GROUP_DELETE:
						SetBusyPointer(group->window);
						backdrop_remove_group_objects(group,(BackdropObject *)msg->data);
						ClearPointer(group->window);
						break;


					// Help
					case IPC_HELP:

						// Show help for group
						help_show_help(HELP_PROGRAM_GROUP,0);
						break;


					// Do a function
					case LISTER_DO_FUNCTION:

						// Arrange icons?
						if (msg->data>=(APTR)MENU_LISTER_ARRANGE_NAME &&
							msg->data<=(APTR)MENU_LISTER_ARRANGE_SIZE)
						{
							// Do cleanup
							backdrop_cleanup(group->info,BSORT_NAME+(((ULONG)msg->data)-MENU_LISTER_ARRANGE_NAME),0);
						}
						break;
				}

				// Reply to message
				IPC_Reply(msg);
			}

			// Is window open?
			if (group->window)
			{
				struct IntuiMessage *imsg;

				// Check timer
				if (CheckTimer(group->timer))
				{
					// Dragging something?
					if (group->info->flags&BDIF_DRAGGING)
					{
						// Check for deadlocks
						if (group->info->last_tick==group->info->tick_count)
						{
							// Stop drag
							backdrop_stop_drag(group->info);
						}

						// Remember tick count
						group->info->last_tick=group->info->tick_count;
					}

					// Re-start timer
					StartTimer(group->timer,0,500000);
				}

				// Window messages
				while (imsg=(struct IntuiMessage *)GetMsg(group->window->UserPort))
				{
					struct IntuiMessage msg_copy;
					struct MenuItem *item;

					// Copy message
					msg_copy=*imsg;

					// Menu verify?
					if (imsg->Class==IDCMP_MENUVERIFY)
					{
						// See if we want to swallow it
						if (!backdrop_test_rmb(group->info,imsg,&msg_copy,TRUE))
						{
							// Did event happen over the window?
							if (imsg->MouseX>=0 &&
								imsg->MouseY>=0 &&
								imsg->MouseX<group->window->Width &&
								imsg->MouseY<group->window->Height &&
								imsg->Qualifier&IEQUALIFIER_RBUTTON)
							{
								// Cancel menu event
								imsg->Code=MENUCANCEL;

								// Change our copy to MOUSEBUTTONS
								msg_copy.Class=IDCMP_MOUSEBUTTONS;
								msg_copy.Code=MENUDOWN;

								// Kludge for MagicMenu
								if (msg_copy.Seconds==0)
									CurrentTime(&msg_copy.Seconds,&msg_copy.Micros);
							}
						}
					}

					// Resize/refresh?
					if (imsg->Class==IDCMP_NEWSIZE ||
						imsg->Class==IDCMP_REFRESHWINDOW)
					{
						// Handle message
						backdrop_idcmp(group->info,imsg,0);

						// Reply to message
						ReplyMsg((struct Message *)imsg);
						continue;
					}

					// Reply to message
					ReplyMsg((struct Message *)imsg);

					// Is it a backdrop message?
					if (backdrop_idcmp(group->info,&msg_copy,0))
						continue;

					// Look at message class
					switch (msg_copy.Class)
					{
						// Window closed
						case IDCMP_CLOSEWINDOW:
							quit_flag=1;
							break;


						// Window is inactive
						case IDCMP_INACTIVEWINDOW:

							// Abort timer if running
							StopTimer(group->timer);
							break;


						// Window is active
						case IDCMP_ACTIVEWINDOW:

							// Start timer if not running
							StartTimer(group->timer,1,0);
							break;


						// Key press
						case IDCMP_RAWKEY:

							// Help?
							if (msg_copy.Code==0x5f &&
								!(msg_copy.Qualifier&VALID_QUALIFIERS))	
							{
								help_get_help(
									msg_copy.MouseX+group->window->LeftEdge,
									msg_copy.MouseY+group->window->TopEdge,
									msg_copy.Qualifier);
							}

							// Close?
							else
							if (msg_copy.Code==0x45 &&
								msg_copy.Qualifier&IEQUAL_ANYSHIFT) quit_flag=1;
							break;


						// Button pressed
						case IDCMP_MOUSEBUTTONS:

							// Right button?
							if (msg_copy.Code==MENUDOWN)
							{
								USHORT res;

								// Do popup menu
								if (group->popup &&
									(res=DoPopUpMenu(group->window,&group->popup->ph_Menu,NULL,MENUDOWN))!=(USHORT)-1)
								{
									// Help?
									if (res&POPUP_HELPFLAG)
									{
										// Get help ID
										res&=~POPUP_HELPFLAG;

										// Do help
										help_menu_help(res,0);
										break;
									}

									// Do the function
									quit_flag=backdrop_group_do_function(group,res,0);
								}
							}
							break;


						// Menu event
						case IDCMP_MENUPICK:
						case IDCMP_MENUHELP:
							{
								struct Menu *oldstrip=group->window->MenuStrip;
								USHORT nextselect;

								// Get item
								nextselect=msg_copy.Code;
								while (item=ItemAddress(group->window->MenuStrip,nextselect))
								{
									// get next
									nextselect=item->NextSelect;

									// Help?
									if (msg_copy.Class==IDCMP_MENUHELP)
									{
										help_menu_help((long)GTMENUITEM_USERDATA(item),0);
										break;
									}

									// Do the function
									quit_flag=backdrop_group_do_function(group,(ULONG)GTMENUITEM_USERDATA(item),item);

									// Check valid next
									if (!nextselect || !group->window || oldstrip!=group->window->MenuStrip)
										break;
								}
							}
							break;
					}
				}
			}

			// Check quit flag
			if (quit_flag) break;

			// Wait for event
			Wait(	1<<ipc->command_port->mp_SigBit|
					1<<group->timer->port->mp_SigBit|
					((group->info->notify_req)?(1<<group->info->notify_port->mp_SigBit):0)|
					((group->window)?(1<<group->window->UserPort->mp_SigBit):0)|
					((group->appwindow)?(1<<group->appport->mp_SigBit):0));
		}

		// Close window
		backdrop_free_group(group);

		// Send goodbye
		IPC_Goodbye(ipc,&main_ipc,0);
	}
Example #29
0
void PI_DMA_WRITE (void) {
	DWORD i;	

	PI_STATUS_REG |= PI_STATUS_DMA_BUSY;
	if ( PI_DRAM_ADDR_REG + PI_WR_LEN_REG + 1 > RdramSize) {
#ifndef EXTERNAL_RELEASE
		DisplayError("PI_DMA_WRITE not in Memory");
#endif	
		PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
		MI_INTR_REG |= MI_INTR_PI;
		CheckInterrupts();
		return;
	}

	if ( PI_CART_ADDR_REG >= 0x08000000 && PI_CART_ADDR_REG <= 0x08010000) {
		if (SaveUsing == Auto) { SaveUsing = Sram; }
		if (SaveUsing == Sram) {
			DmaFromSram(
				N64MEM+PI_DRAM_ADDR_REG,
				PI_CART_ADDR_REG - 0x08000000,
				PI_WR_LEN_REG + 1
			);
			PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
			MI_INTR_REG |= MI_INTR_PI;
			CheckInterrupts();
			return;
		}
		if (SaveUsing == FlashRam) {
			DmaFromFlashram(
				N64MEM+PI_DRAM_ADDR_REG,
				PI_CART_ADDR_REG - 0x08000000,
				PI_WR_LEN_REG + 1
			);
			PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
			MI_INTR_REG |= MI_INTR_PI;
			CheckInterrupts();
		}
		return;
	}

	if ( PI_CART_ADDR_REG >= 0x10000000 && PI_CART_ADDR_REG <= 0x1FBFFFFF) {
#ifdef ROM_IN_MAPSPACE
		if (WrittenToRom) { 
			DWORD OldProtect;
			VirtualProtect(ROM,RomFileSize,PAGE_READONLY, &OldProtect);
		}
#endif
		PI_CART_ADDR_REG -= 0x10000000;
		if (PI_CART_ADDR_REG + PI_WR_LEN_REG + 1 < RomFileSize) {
			for (i = 0; i < PI_WR_LEN_REG + 1; i ++) {
				*(N64MEM+((PI_DRAM_ADDR_REG + i) ^ 3)) =  *(ROM+((PI_CART_ADDR_REG + i) ^ 3));
			}
		} else {
			DWORD Len;
			Len = RomFileSize - PI_CART_ADDR_REG;
			for (i = 0; i < Len; i ++) {
				*(N64MEM+((PI_DRAM_ADDR_REG + i) ^ 3)) =  *(ROM+((PI_CART_ADDR_REG + i) ^ 3));
			}
			for (i = Len; i < PI_WR_LEN_REG + 1 - Len; i ++) {
				*(N64MEM+((PI_DRAM_ADDR_REG + i) ^ 3)) =  0;
			}
		}
		PI_CART_ADDR_REG += 0x10000000;

		if (!DMAUsed) { 
			DMAUsed = TRUE;
			FirstDMA(); 
		}
		PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
		MI_INTR_REG |= MI_INTR_PI;
		CheckInterrupts();
		//ChangeTimer(PiTimer,(int)(PI_WR_LEN_REG * 8.9) + 50);
		//ChangeTimer(PiTimer,(int)(PI_WR_LEN_REG * 8.9));
		CheckTimer();
		return;
	}
	
#ifndef EXTERNAL_RELEASE
	if (ShowUnhandledMemory) { DisplayError("PI_DMA_WRITE not in ROM"); }
#endif
	PI_STATUS_REG &= ~PI_STATUS_DMA_BUSY;
	MI_INTR_REG |= MI_INTR_PI;
	CheckInterrupts();

}
Example #30
0
/***********************************************
电池放电

***********************************************/
int dis_charge(void)
{

	FRESULT result;
	FATFS fs;
	FIL file;
	DIR DirInf;  
	uint32_t bw;


	char time_buf[TIME_MAX];
	char write_buf[WR_MAX];
	char tmp_buf[8];

	int dis_time = 0;
	int i = 0;
	int min_count = 0;
	
	double vol;


	result = f_mount(0, &fs);		
	if (result != FR_OK){
		printf("FileSystem Mounted Failed (%d)\r\n", result);
		goto ERROR;
	}

	result = f_opendir(&DirInf, "/");
	if (result != FR_OK){ 
		printf("Open Root Directory Error (%d)\r\n", result);
		goto ERROR;
	}
	
	result = f_open(&file, conf->file_name, FA_OPEN_ALWAYS | FA_READ | FA_WRITE);	
	if(result !=FR_OK){
		printf("open error, errornu:%d\n\r",result);
	 	goto ERROR;
	}

	if(f_lseek(&file,file.fsize) != FR_OK){
		printf("f_lseek error, errornu:%d\n\r",result);
		goto ERROR;
	}
	 	
	load_con_on();		//打开负载通道LOAD_CON
	bsp_LedOn(3); 
	
	beeper_on();
	delay_ms(200);
	beeper_off(); 
	
	memset(time_buf,0,TIME_MAX);
	memset(write_buf,0,WR_MAX);


	StartTimer(0,  1000);  	
//	Time_Display(RTC_GetCounter());
//	vol = ADC_SAMPLING();	

	do{
		if(jump)
			goto JMP;
		if(CheckTimer(0)) {	
			dis_time ++;
			StartTimer(0,  1000);
			min_count ++;
			vol = ADC_SAMPLING();

			if(min_count >=60){
				min_count = 0;
			
				memset(time_buf,0,TIME_MAX);	
				record_time(time_buf);
				strcat(time_buf,",");						
	
				strcat(write_buf, time_buf);
				memset(time_buf,0,TIME_MAX);		
	
								
				sprintf(tmp_buf, "%.2f", vol);	
				strcat(write_buf, tmp_buf);							      
				strcat(write_buf,",放电\n");
	
				if(i > 9){
					result = f_write(&file,write_buf,sizeof(write_buf),&bw);			
					if(result != FR_OK){
						printf("file write faild, errornu:%d\n\r",result);
						goto ERROR;
					}
					
					memset(write_buf,0,WR_MAX);
					i = 0;
				}
	
				i++;
			}
		}
	
	}while(dis_charge_timeout(vol));

JMP:
	record[rec]= dis_time/60;
	rec++;

	

	jump = 0;
	if(i != 0){

		result = f_write(&file,write_buf,35*i, &bw);			
		if(result != FR_OK){
			printf("file write faild, errornu:%d\n\r",result);
			goto ERROR;
			
		}
		i = 0;
	}
	memset(write_buf,0,WR_MAX);


	bsp_LedOff(3);							//放电结束

	load_con_off();
	
	f_close(&file);
	f_mount(0, NULL);
	return 0;						//关闭负载通道LOAD_CON

ERROR:
	bsp_LedOff(3);
	f_close(&file);
	f_mount(0, NULL);
	return 1;



}