コード例 #1
0
ファイル: main_gh60.c プロジェクト: brucetsao/ukbdc
int main(void)
{
	clock_prescale_set(clock_div_1);
	SYSTEM_init();
	TIMER_init();

	USB_init();

	/* initialize with 65 keys */
	LAYOUT_init(65);
	LAYOUT_set((struct layout*)LAYOUT_BEGIN);
	LAYOUT_set_callback(&HID_set_scancode_state);

	MATRIX_init(5, rows, 14, cols, (const uint8_t*)matrix, &on_key_press);

	HID_init();
	HID_commit_state();

	LED_init();

	SYSTEM_subscribe(USB_SOF, ANY, MAIN_handle_sof);
	int sleep_tmr = TIMER_add(32, true);
	SYSTEM_subscribe(TIMER, sleep_tmr, MAIN_sleep_timer_handler);

	SYSTEM_add_task(main_task, 0);
	SYSTEM_add_task(RAWHID_PROTOCOL_task, 0);

	SYSTEM_main_loop();
}
コード例 #2
0
ファイル: composite_app.c プロジェクト: Btar/HEXIWEAR
void USB_Task() {

//	FLASH_Run_Test();

	USB_init();

	while (1) {
		msc_disk_task();
		cdc_vcom_task();
	}
}
コード例 #3
0
ファイル: main_alpha.c プロジェクト: brucetsao/ukbdc
int main(void)
{
	clock_prescale_set(clock_div_1);

	for (int i = 0; i < NUM_IO; ++i) {
		IO_config(i, INPUT);
		IO_set(i, true);
	}

	PORTB |= _BV(PB0);
	DDRB |= _BV(PB2) | _BV(PB1) | _BV(PB0); // MOSI, SCK, MEMCS
	DDRC |= _BV(PC7) | _BV(PC6); // LATCH, BUFEN
	DDRB &= ~_BV(PB3); // MISO
	PORTB &= ~_BV(PB3);


	USB_init();
	while (USB_get_configuration() == 0)
		;

	HID_commit_state();

	int size;
	DATAFLASH_read_page(1, sizeof(size), &size);
	if (size != -1) {
		uint8_t *layout = malloc(size);
		DATAFLASH_read_page(2, (uint16_t)size, layout);
		RAWHID_send(layout);
		LAYOUT_set(layout);
	}
	DATAFLASH_read_page(0, sizeof(matrix), matrix);

	TCCR0A = 0x00;
	TCCR0B = 0x03; /* clk_io / 64 */
	TIMSK0 = _BV(TOIE0);
	while(1) {
		RAWHID_PROTOCOL_task();
	}

	while (1)
		;
}
コード例 #4
0
ファイル: main.c プロジェクト: k-code/k-car
/**
 * @brief  Main program.
 * @param  None
 * @retval None
 */
int main(void) {
	LEDS_init();
	TIME_init();
	US_init();
	MOTORS_init();
	USB_init();
	//int x = 500;

	do {
		//TIME_delay(1000);

		for (int i=0; i < 10000000; i++) {}
		LEDS_live(!LEDS_live_state());
		/*if (US_distance > 30) {
			MOTORS_forward(1000);
		}
		else {
			MOTORS_right(100);
		}*/
		/*PROTOCOL_data data = {0,0,0,0,0};//PROTOCOL_emptyData;
		data.id = 1;
		data.cmd = 2;
		data.type = 0;
		data.bData = 3;
		USB_write(data);*/
		/*LEDS_live(LEDS_On);
		TIME_delay(US_distance*10);
		LEDS_live(LEDS_Off);
		TIME_delay(US_distance*10);*/

		/*if (x > 1000) x = 600;
		TIME_delay(1000);
		MOTORS_forward(x);
		x+= 10;*/
		USB_power(1);
		//TIME_delay(100);
		for (int i=0; i < 10000000; i++) {}
		USB_power(0);

	} while (1);
}
コード例 #5
0
ファイル: usb_printf.c プロジェクト: pyrovski/usb-mspgcc
void usb_printf_init(void) {
    SetVCore(3);
    init_clock();
    //Init USB
    USB_init();                 
    //Enable various USB event handling routines
    USB_setEnabledEvents(kUSB_VbusOnEvent + 
                         kUSB_VbusOffEvent + 
                         kUSB_receiveCompletedEvent + 
                         kUSB_dataReceivedEvent + 
                         kUSB_UsbSuspendEvent + 
                         kUSB_UsbResumeEvent +
                         kUSB_UsbResetEvent);
    // See if we're already attached physically to USB, and if so, 
    // connect to it. Normally applications don't invoke the event 
    // handlers, but this is an exception.
    if(USB_connectionInfo() & kUSB_vbusPresent) {
        usb_printf_state = USB_ENABLED;
        USB_handleVbusOnEvent();
    }
}
コード例 #6
0
//----------------------------------------------------------------------------
VOID ConfigUSB(VOID)
{
    USB_init();                     // Init USB

    // Enable various USB event handling routines

    USB_setEnabledEvents(kUSB_VbusOnEvent+kUSB_VbusOffEvent+kUSB_receiveCompletedEvent
                          +kUSB_dataReceivedEvent+kUSB_UsbSuspendEvent+kUSB_UsbResumeEvent+kUSB_UsbResetEvent);
    
    
    // See if we're already attached physically to USB, and if so, connect to it
    // Normally applications don't invoke the event handlers, but this is an exception.  
  
    if (USB_connectionInfo() & kUSB_vbusPresent)
    {
        if (USB_enable() == kUSB_succeed)
        {
            USB_reset();
            USB_connect();
        }
    }
	
}
コード例 #7
0
ファイル: main.c プロジェクト: alkyl1978/stm32samples
int main(){
	uint32_t Old_timer = 0;

	// RCC clocking: 8MHz oscillator -> 72MHz system
	rcc_clock_setup_in_hse_8mhz_out_72mhz();

	GPIO_init();

	usb_disconnect(); // turn off USB while initializing all
	steppers_init();

	// USB
	usbd_dev = USB_init();

	// SysTick is a system timer with 1ms period
	SysTick_init();

	// wait a little and then turn on USB pullup
//	for (i = 0; i < 0x800000; i++)
//		__asm__("nop");

	usb_connect(); // turn on USB

	while(1){
		usbd_poll(usbd_dev);
		if(usbdatalen){ // there's something in USB buffer
			usbdatalen = parce_incoming_buf(usbdatabuf, usbdatalen);
		}
		//check_and_parce_UART(USART1); // also check data in UART buffers
		if(Timer - Old_timer > 999){ // one-second cycle
			Old_timer += 1000;
		}else if(Timer < Old_timer){ // Timer overflow
			Old_timer = 0;
		}
	}
}
コード例 #8
0
ファイル: main.c プロジェクト: libcg/XtreamLua-Player
int main(int argc, char** argv)
{
	pspDebugScreenInit();
	pspDebugScreenEnableBackColor(0);
	
	SetupCallbacks();
	
	char* scriptFilename = "script.lua";
	
	lua_State *L;
	L = lua_open();
	luaL_openlibs(L);
	
	Aalib_init(L);
	Color_init(L);
	g2D_init(L);
	intraFont_init(L);
	Ctrl_init(L);
	Power_init(L);
	Time_init(L);
	Timer_init(L);
	Savedata_init(L);
	sceIo_init(L);
	Utility_init(L);
	USB_init(L);
	Xtream_init(L);
	
	
	SceCtrlData keys, oldkeys;
	int status = 0, i;
	
	while (1)
	{
	status = luaL_loadfile(L, scriptFilename);
		
	if (status == 0) 
		status = lua_pcall(L, 0, LUA_MULTRET, 0);
	

		if (status != 0) //If an error has occured
		{
		sceCtrlReadBufferPositive(&oldkeys, 1);
		
		pspDebugScreenInit();
		pspDebugScreenEnableBackColor(1);
		
			while (1)
			{			
				sceCtrlReadBufferPositive(&keys, 1);
			
				pspDebugScreenSetXY(0,0);
				printf("Lua Error:\n%s\n", lua_tostring(L, -1));
				printf("Press Start to reset.\n");
				
				if ((keys.Buttons &PSP_CTRL_START) && !(oldkeys.Buttons &PSP_CTRL_START))
					break;
				
				oldkeys = keys;
				
				for (i = 0; i < 10; i++)
					sceDisplayWaitVblankStart();
			}
			
		pspDebugScreenInit();
		pspDebugScreenEnableBackColor(0);
		
		lua_pop(L, 1);
		}
	}
		
	lua_close(L);

	intraFontShutdown();
	g2dTerm();
	cleanUSBDrivers();

	sceKernelExitGame();

	return 0;
}
コード例 #9
0
ファイル: main.c プロジェクト: Chloe880810/OpenTag
/*  
 * ======== main ========
 */
VOID main (VOID)
{
    WDTCTL = WDTPW + WDTHOLD;                                   //Stop watchdog timer

    Init_Ports();                                               //Init ports (do first ports because clocks do change ports)
    SetVCore(3);
    Init_Clock();                                               //Init clocks
	
    USB_init();                 //Init USB

    Init_TimerA1();
	
    //Enable various USB event handling routines
    USB_setEnabledEvents(
        kUSB_VbusOnEvent + kUSB_VbusOffEvent + kUSB_receiveCompletedEvent
        + kUSB_dataReceivedEvent + kUSB_UsbSuspendEvent + kUSB_UsbResumeEvent +
        kUSB_UsbResetEvent);

    //See if we're already attached physically to USB, and if so, connect to it
    //Normally applications don't invoke the event handlers, but this is an exception.
    if (USB_connectionInfo() & kUSB_vbusPresent){
        USB_handleVbusOnEvent();
    }

	__enable_interrupt();                           //Enable interrupts globally
    while (1)
    {
        BYTE i;
        //Check the USB state and directly main loop accordingly
        switch (USB_connectionState())
        {
            case ST_USB_DISCONNECTED:
                __bis_SR_register(LPM3_bits + GIE);                                 //Enter LPM3 w/ interrupts enabled
                _NOP();                                                             //For Debugger
                break;

            case ST_USB_CONNECTED_NO_ENUM:
                break;

            case ST_ENUM_ACTIVE:
                __bis_SR_register(LPM0_bits + GIE);                                 //Enter LPM0 (can't do LPM3 when active)
                _NOP();                                                             //For Debugger

                                                                                    //Exit LPM on USB receive and perform a receive
                                                                                    //operation
                if (bCDCDataReceived_event){                                        //Some data is in the buffer; begin receiving a
                                                                                    //command
                    char pieceOfString[MAX_STR_LENGTH] = "";                        //Holds the new addition to the string
                    char outString[MAX_STR_LENGTH] = "";                            //Holds the outgoing string

                                                                                    //Add bytes in USB buffer to theCommand
                    cdcReceiveDataInBuffer((BYTE*)pieceOfString,
                        MAX_STR_LENGTH,
                        CDC0_INTFNUM);                                                         //Get the next piece of the string
                    strcat(wholeString,pieceOfString);
                    cdcSendDataInBackground((BYTE*)pieceOfString,
                        strlen(pieceOfString),CDC0_INTFNUM,0);                      //Echoes back the characters received (needed
                                                                                    //for Hyperterm)

                    if (retInString(wholeString)){                                  //Has the user pressed return yet?
                        if (!(strcmp(wholeString, "LED ON"))){                      //Compare to string #1, and respond
                            TA1CTL &= ~MC_1;                                        //Turn off Timer
                            P1OUT |= BIT0;                                          //Turn on LED P1.0
                            strcpy(outString,"\r\nLED is ON\r\n\r\n");              //Prepare the outgoing string
                            cdcSendDataInBackground((BYTE*)outString,
                                strlen(outString),CDC0_INTFNUM,0);                  //Send the response over USB
                        } else if (!(strcmp(wholeString, "LED OFF"))){              //Compare to string #2, and respond
                            TA1CTL &= ~MC_1;                                        //Turn off Timer
                            P1OUT &= ~BIT0;                                         //Turn off LED P1.0
                            strcpy(outString,"\r\nLED is OFF\r\n\r\n");             //Prepare the outgoing string
                            cdcSendDataInBackground((BYTE*)outString,
                                strlen(outString),CDC0_INTFNUM,0);                  //Send the response over USB
                        } else if (!(strcmp(wholeString,
                                         "LED TOGGLE - SLOW"))){                    //Compare to string #3, and respond
                            TA1CTL &= ~MC_1;                                        //Turn off Timer
                            TA1CCR0 = SlowToggle_Period;                            //Set Timer Period for slow LED toggle
                            TA1CTL |= MC_1;                                         //Start Timer
                            strcpy(outString,
                                "\r\nLED is toggling slowly\r\n\r\n");              //Prepare the outgoing string
                            cdcSendDataInBackground((BYTE*)outString,
                                strlen(outString),CDC0_INTFNUM,0);                  //Send the response over USB
                        } else if (!(strcmp(wholeString,
                                         "LED TOGGLE - FAST"))){                    //Compare to string #4, and respond
                            TA1CTL &= ~MC_1;                                        //Turn off Timer
                            TA1CCR0 = FastToggle_Period;                            //Set Timer Period for fast LED toggle
                            TA1CTL |= MC_1;
                            strcpy(outString,"\r\nLED is toggling fast\r\n\r\n");   //Prepare the outgoing string
                            cdcSendDataInBackground((BYTE*)outString,
                                strlen(outString),CDC0_INTFNUM,0);                  //Send the response over USB
                        } else {                                                    //Handle other
                            strcpy(outString,"\r\nNo such command!\r\n\r\n");       //Prepare the outgoing string
                            cdcSendDataInBackground((BYTE*)outString,
                                strlen(outString),CDC0_INTFNUM,0);                  //Send the response over USB
                        }
                        for (i = 0; i < MAX_STR_LENGTH; i++){                       //Clear the string in preparation for the next
                                                                                    //one
                            wholeString[i] = 0x00;
                        }
                    }
                    bCDCDataReceived_event = FALSE;
                }
                break;

            case ST_ENUM_SUSPENDED:
                P1OUT &= ~BIT0;                                                     //When suspended, turn off LED
                __bis_SR_register(LPM3_bits + GIE);                                 //Enter LPM3 w/ interrupts
                _NOP();
                break;

            case ST_ENUM_IN_PROGRESS:
                break;

            case ST_NOENUM_SUSPENDED:
                P1OUT &= ~BIT0;
                __bis_SR_register(LPM3_bits + GIE);
                _NOP();
                break;

            case ST_ERROR:
                _NOP();
                break;

            default:;
        }
    }  //while(1)
} //main()
コード例 #10
0
ファイル: main.c プロジェクト: TECHNOTICSROBOTICS/mspdev
void main(void)
{
    WDTCTL = WDTPW + WDTHOLD;                // Stop the watchdog
    __enable_interrupt();                    // Enable general interrupts
    Board_init();                            // Configure's the F5529 EXP board's I/Os
    
    // Initialize power/clocks for use with USB
    SetVCore(3);                             // The USB module requires that VCore be set to highest setting, independent of MCLK freq
    ClockUSB();
    
    disk_initialize(0);                      // SD-cards must go through a setup sequence after powerup.  This FatFs call does this.  
    USB_init();                              // Initializes the USB API, and prepares the USB module to detect USB insertion/removal events
    USB_setEnabledEvents(kUSB_allUsbEvents); // Enable all USB events
      
    // The data interchange buffer (used when handling SCSI READ/WRITE) is declared by the application, and 
    // registered with the API using this function.  This allows it to be assigned dynamically, giving 
    // the application more control over memory management.  
    USBMSC_registerBufInfo(&RW_dataBuf[0], NULL, sizeof(RW_dataBuf));
 
    
    // The API maintains an instance of the USBMSC_RWbuf_Info structure.  If double-buffering were used, it would
    // maintain one for both the X and Y side.  (This version of the API only supports single-buffering,
    // so only one structure is maintained.)  This is a shared resource between the API and application; the 
    // application must request the pointers.    
    RWbuf_info = USBMSC_fetchInfoStruct();
  
    
    // USBMSC_updateMediaInfo() must be called prior to USB connection.  We check if the card is present, and if so, pull its size
    // and bytes per block.  
    // LUN0
    mediaInfo.mediaPresent = 0x01;        // The medium is present, because internal flash is non-removable.  
    mediaInfo.mediaChanged = 0x00;        // It can't change, because it's in internal memory, which is always present.  
    mediaInfo.writeProtected = 0x00;      // It's not write-protected
    mediaInfo.lastBlockLba = 774;         // 774 blocks in the volume. (This number is also found twice in the volume itself; see mscFseData.c. They should match.)
    mediaInfo.bytesPerBlock = BYTES_PER_BLOCK; // 512 bytes per block. (This number is also found in the volume itself; see mscFseData.c. They should match.)
    USBMSC_updateMediaInfo(0, &mediaInfo); 
    
    // LUN1
    if(detectCard())
      mediaInfo.mediaPresent = kUSBMSC_MEDIA_PRESENT;
    else mediaInfo.mediaPresent = kUSBMSC_MEDIA_NOT_PRESENT;
    mediaInfo.mediaChanged = 0x00;
    mediaInfo.writeProtected = 0x00;
    disk_ioctl(0,GET_SECTOR_COUNT,&mediaInfo.lastBlockLba);   // Returns the number of blocks (sectors) in the media. 
    mediaInfo.bytesPerBlock = BYTES_PER_BLOCK;                // Block size will always be 512
    USBMSC_updateMediaInfo(1, &mediaInfo); 
    
    
    // At compile-time for this demo, there will be one file on the volume.  The root directory and data cluster
    // for this file need to be initialized.  
    //flashWrite_LBA(Root_Dir, (BYTE*)Root_Dir_init); 
    //flashWrite_LBA(Data559, (BYTE*)Data559_init); 
    
    
    // Configure Timer_A0 to prompt detection of the SD card every second
    TA0CCTL0 = CCIE;                          // Enable interrupt
    TA0CCR0 = 32768;                          // Clock will be 32kHz, so we set the int to occur when it counts to 32768
    TA0CTL = TASSEL_1 + MC_1 + TACLR;         // ACLK = 32kHz, up mode, clear TAR... go!

  
    // If USB is already connected when the program starts up, then there won't be a USB_handleVbusOnEvent(). 
    // So we need to check for it, and manually connect if the host is already present.   
    if (USB_connectionInfo() & kUSB_vbusPresent)
    {
      if (USB_enable() == kUSB_succeed)
      {
        USB_reset();
        USB_connect();      
      }
    }
  
    while(1)
    {
      BYTE ReceiveError=0, SendError=0;
      WORD count;
      switch(USB_connectionState())
      {
        case ST_USB_DISCONNECTED:
                 __bis_SR_register(LPM3_bits + GIE); 	       // Enter LPM3 until VBUS-on event
                
                 // Check if the reason we woke was a button press; and if so, log a new piece of data.  
                 if(fS1ButtonEvent)
                 {
                   // Build string
                   char str[14] = "Data entry #0\n";
                   str[12] = logCnt++;                             // Number the entries 0 through....?
                   
                   memcpy(RW_dataBuf, Data559, BYTES_PER_BLOCK);  // Copy data block 559 from flash to RAM buffer
                   memcpy(&RW_dataBuf[DataCnt], str, sizeof(str)); // Write the new entry to the RAM buffer
                   flashWrite_LBA((PBYTE)Data559, RW_dataBuf);    // Copy it back to flash
                   
                   DataCnt += sizeof(str);                         // Increment the index past the new entry
                   if((DataCnt + sizeof(str)>= BYTES_PER_BLOCK))   // Roll index back to 0, if no more room in the block
                     DataCnt = 0;
        
                   fS1ButtonEvent = 0;
                 }
                break;
          
        case ST_USB_CONNECTED_NO_ENUM:
                break;
          
        case ST_ENUM_ACTIVE:             

                // Call USBMSC_poll() to initiate handling of any received SCSI commands.  Disable interrupts 
                // during this function, to avoid conflicts arising from SCSI commands being received from the host
                // AFTER decision to enter LPM is made, but BEFORE it's actually entered (in other words, avoid
                // sleeping accidentally).  
                __disable_interrupt();
                if((USBMSC_poll() == kUSBMSC_okToSleep) && (!bDetectCard))
                {
                    __bis_SR_register(LPM0_bits + GIE);  // Enable interrupts atomically with LPM0 entry
                }
                __enable_interrupt();
                
                                               
                // If the API needs the application to process a buffer, it will keep the CPU awake by returning kUSBMSC_processBuffer
                // from USBMSC_poll().  The application should then check the 'operation' field of all defined USBMSC_RWbuf_Info
                // structure instances.  If any of them is non-null, then an operation needs to be processed.  A value of 
                // kUSBMSC_READ indicates the API is waiting for the application to fetch data from the storage volume, in response 
                // to a SCSI READ command from the USB host.  After the application does this, it must indicate whether the 
                // operation succeeded, and then close the buffer operation by calling USBMSC_bufferProcessed().  
                
                while(RWbuf_info->operation == kUSBMSC_READ)
                {
                  switch(RWbuf_info->lun)
                  {
                    case 0:
                      RWbuf_info->returnCode = Read_LBA(RWbuf_info->lba, RWbuf_info->bufferAddr, RWbuf_info->lbCount); // Fetch a block from the medium, using file system emulation
                      USBMSC_bufferProcessed();                           // Close the buffer operation
                      break;
                      
                    case 1:
                      read_LUN1();
                      break;
                  }
                }
                
                // Everything in this section is analogous to READs.  Reference the comments above.   
                while(RWbuf_info->operation == kUSBMSC_WRITE)
                {                  
                  switch(RWbuf_info->lun)
                  {
                    case 0:
                      RWbuf_info->returnCode = Write_LBA(RWbuf_info->lba, RWbuf_info->bufferAddr, RWbuf_info->lbCount); // Write the block to the medium, using file system emulation
                      USBMSC_bufferProcessed();                            // Close the buffer operation
                      break;
                    case 1:
                      write_LUN1();
                      break;
                  }
                }
                
                // Every second, the Timer_A ISR sets this flag.  The checking can't be done from within the timer ISR, because the
                // checking enables interrupts, and this is not a recommended practice due to the risk of nested interrupts.  
                if(bDetectCard)
                {
                  checkInsertionRemoval();
                  bDetectCard = 0x00;                          // Clear the flag, until the next timer ISR
                }
                
                if(bHID_DataReceived_event) //Message is received from HID application
                {
                	bHID_DataReceived_event = FALSE;          // Clear flag early -- just in case execution breaks below because of an error
                	count = hidReceiveDataInBuffer((BYTE*)dataBuffer,BUFFER_SIZE,HID0_INTFNUM);
                	strncat(wholeString," \r\nRx->",7);
                    strncat(wholeString,(char*)dataBuffer,count);
                  	strncat(wholeString," \r\n ",4);
                	if(cdcSendDataInBackground((BYTE*)wholeString,strlen(wholeString),CDC0_INTFNUM,1)) // Send message to other CDC App
                	{
                		SendError = 0x01;
                		break;
                	}
                	memset(wholeString,0,MAX_STR_LENGTH);           // Clear wholeString
                }
                if(bCDC_DataReceived_event)  //Message is received from CDC application 
                {
                  bCDC_DataReceived_event = FALSE;                  // Clear flag early -- just in case execution breaks below because of an error
                  cdcReceiveDataInBuffer((BYTE*)wholeString,MAX_STR_LENGTH,CDC0_INTFNUM);
                  ASCII(wholeString);
                  if(hidSendDataInBackground((BYTE*)wholeString,strlen(wholeString),HID0_INTFNUM,1))  // Send message to HID App
                  {
                    SendError = 0x01;                          // Something went wrong -- exit
                    break;
                  }
                  memset(wholeString,0,MAX_STR_LENGTH);  // Clear wholeString
                }
                                               
                break;
                
            case ST_ENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE);            // Enter LPM3, until a resume or VBUS-off event
                break;
              
          case ST_ENUM_IN_PROGRESS:
                break;
              
          case ST_ERROR:
                break;           
          default:;
      }
      if(ReceiveError || SendError)
      { 
          //TO DO: User can place code here to handle error
      }    
    }
}
コード例 #11
0
ファイル: iUSB.cpp プロジェクト: miiicmueller/SmartWater
/**
 * Macro d'initialisation de l'USB
 */
void iUSB::initUSB()
    {
    USB_init();
    }
コード例 #12
0
ファイル: main.c プロジェクト: TECHNOTICSROBOTICS/mspdev
/*----------------------------------------------------------------------------+
| Main Routine                                                                |
+----------------------------------------------------------------------------*/
VOID main(VOID)
{
    WDTCTL = WDTPW + WDTHOLD;	    // Stop watchdog timer
    Init_StartUp();
    
    USB_init();
    
    USB_setEnabledEvents(kUSB_VbusOnEvent+kUSB_VbusOffEvent+kUSB_receiveCompletedEvent
                          +kUSB_dataReceivedEvent+kUSB_UsbSuspendEvent+kUSB_UsbResumeEvent+kUSB_UsbResetEvent);
    
    // Check if we're already physically attached to USB, and if so, connect to it
    // This is the same function that gets called automatically when VBUS gets attached.  
    if (USB_connectionInfo() & kUSB_vbusPresent)
      USB_handleVbusOnEvent();
      //PWRVBUSonHandler();
                 
    while(1)
    {
        switch(USB_connectionState())
        {
           case ST_USB_DISCONNECTED:
                 __bis_SR_register(LPM3_bits + GIE); 	  // Enter LPM3 w/interrupt
                break;
                
           case ST_USB_CONNECTED_NO_ENUM:
                break;
                
           case ST_ENUM_ACTIVE:
                if(!bCommandBeingProcessed)                  // If no command is being processed, then make sure there's a rcv operation 
                {                                            // open to receive the start of the "packet"
                  if(!(USBCDC_intfStatus(0,&x,&y) & kUSBCDC_waitingForReceive))      // Only open it if we haven't already done so
                    if(USBCDC_receiveData(buffer,1,0) == kUSBCDC_busNotAvailable) // Start a receive operation for a single byte -- the "size" byte of the "packet"
                    {
                      USBCDC_abortReceive(&x,0);                                     // Abort receive
                      break;                                 // If bus is no longer available, escape out of the loop
                    }
                }
                
                __bis_SR_register(LPM0_bits + GIE);          // Wait in LPM0 until a receive operation has completed
                //__bis_SR_register(LPM0_bits + GIE);
                if(bDataReceiveCompleted_event)
                {
                  bDataReceiveCompleted_event = FALSE;
                  if(!bCommandBeingProcessed)                // This means that the incoming byte is the start of the "packet" -- the "size" byte
                  {
                    if ((buffer[0]>=0x31) &&  (buffer[0]<= 0x39))
                    {
                        size = buffer[0]-0x30;                 // It's in ASCII, so convert it to a number
                        
                        if(USBCDC_receiveData(buffer,size,0) == kUSBCDC_busNotAvailable)  // And then open a rcv operation for that size
                        {
                          USBCDC_abortReceive(&x,0);                                      // Abort receive
                          break;                                 // If bus is no longer available, escape out of the loop
                        }
                        bCommandBeingProcessed = TRUE;           // Now we're waiting for the "data" part of the "packet"
                    }
                    
                    else 
                    {
                       strcpy(outString,"\r\nEnter a valid number between 1 and 9\r\n\r\n");     // Prepare the outgoing string
                       if(cdcSendDataInBackground((BYTE*)outString,strlen(outString),0,0)) // Send the response over USB
                       {
                          USBCDC_abortSend(&x,0);                                         // Operation may still be open; cancel it
                          break;                                                          // If the send fails, escape the main loop
                        }
                        bCommandBeingProcessed = FALSE;                                   // Now we're back to waiting for the "size" byte
                    }
                  }
                  else                                       // This means that the incoming data is the "data" part of the "packet"
                  {
                    strcpy(outString,"\r\nI received your packet with size of ");     // Prepare the outgoing string
                    buffer[bufferLen-1]= 0;
                    c[0] = (char)(size+'0');   
                    c[1] = 0;
                    outString[64] = 0;                                      // Convert the size back to ASCII
                    strcat(outString,c);
                    strcat(outString," bytes.\r\n\r\n");                              
                    if(cdcSendDataInBackground((BYTE*)outString,strlen(outString),0,0)) // Send the response over USB
                    {
                      USBCDC_abortSend(&x,0);                                         // Operation may still be open; cancel it
                      break;                                                          // If the send fails, escape the main loop
                    }
                    bCommandBeingProcessed = FALSE;                                   // Now we're back to waiting for the "size" byte
                  }
                }
                break;
                
           case ST_ENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE); 	// Enter LPM3 w/interrupt
                break;
           
           case ST_ENUM_IN_PROGRESS:
                break;
           
           case ST_NOENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE);  
                _NOP();
                break;
          
           case ST_ERROR:
                _NOP();
                break;
                
           default:;
        }
    }  // while(1) 
} //main()
コード例 #13
0
ファイル: usb.c プロジェクト: psucurran/NoiseNinjas
/*
 *  usb_test()
 *    USB Bulk transfer test. Device is detected as an eZDSP5535 when
 *    connected to PC while test is running. Bulk transfers can be
 *    made using USB_55xx program.
 *
 */
CSL_Status usb_test(void)
{
	CSL_IRQ_Config    config;
	CSL_Status        result;
	Uint16            eventMask;

	result = CSL_USB_TEST_FAILED;

	usbConfig.opMode             = CSL_USB_OPMODE_POLLED;
    usbConfig.devNum             = CSL_USB0;
	usbConfig.maxCurrent         = CSL_USB_MAX_CURRENT;
	usbConfig.appSuspendCallBack = (CSL_USB_APP_CALLBACK)CSL_suspendCallBack;
	usbConfig.appWakeupCallBack  = (CSL_USB_APP_CALLBACK)CSL_selfWakeupCallBack;
	usbConfig.startTransferCallback  = CSL_startTransferCallback;
	usbConfig.completeTransferCallback = CSL_completeTransferCallback;

	hEpObjArray[0] = &usbCtrlOutEpObj;
	hEpObjArray[1] = &usbCtrlInEpObj;
	hEpObjArray[2] = &usbBulkOutEpObj;
	hEpObjArray[3] = &usbBulkInEpObj;

	/* Set the interrupt vector start address */
	IRQ_setVecs((Uint32)(&VECSTART));

	/* Plug the USB Isr into vector table */
	config.funcAddr = &usb_isr;
	IRQ_plug(USB_EVENT, config.funcAddr);

	/* Enable USB Interrupts */
	IRQ_enable(USB_EVENT);
	/* Enable CPU Interrupts */
	IRQ_globalEnable();

	/* Initialize the USB module */
	status = USB_init(&usbConfig);
	if(status != CSL_SOK)
	{
		printf("USB init failed\n");
		return(result);
	}

	/* Reset the USB device */
	status = USB_resetDev(CSL_USB0);
	if(status != CSL_SOK)
	{
		printf("USB Reset failed\n");
		return(result);
	}

	/* Initialize the Control Endpoint OUT 0 */
	eventMask = (CSL_USB_EVENT_RESET | CSL_USB_EVENT_SETUP |
				 CSL_USB_EVENT_SUSPEND | CSL_USB_EVENT_RESUME |
				 CSL_USB_EVENT_RESET | CSL_USB_EVENT_EOT);

	status = USB_initEndptObj(CSL_USB0, hEpObjArray[0],
	                          CSL_USB_OUT_EP0,CSL_USB_CTRL,
					          CSL_USB_EP0_PACKET_SIZE, eventMask, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Initialize the Control Endpoint IN 0 */
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[1], CSL_USB_IN_EP0,
	                          CSL_USB_CTRL, CSL_USB_EP0_PACKET_SIZE,
	                          CSL_USB_EVENT_EOT, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Initialize the Bulk Endpoint IN 1 */
	eventMask = (CSL_USB_EVENT_RESET | CSL_USB_EVENT_EOT);
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[2], CSL_USB_IN_EP1,
	                          CSL_USB_BULK, CSL_USB_EP1_PACKET_SIZE_FS,
	                          eventMask, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Initialize the Bulk Endpoint OUT 2 */
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[3], CSL_USB_OUT_EP1,
	                          CSL_USB_BULK, CSL_USB_EP1_PACKET_SIZE_FS,
	                          CSL_USB_EVENT_EOT, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Set the parameters */
	status = USB_setParams(CSL_USB0, hEpObjArray, FALSE);
	if(status != CSL_SOK)
	{
		printf("USB Set params failed\n");
		return(result);
	}

	/* Connect the USB device */
	status = USB_connectDev(CSL_USB0);
	if(status != CSL_SOK)
	{
		printf("USB Connect failed\n");
		return(result);
	}

	deviceDescPtr = (Uint16 *)deviceDesc;
	cfgDescPtr    = (Uint16 *)cfgDesc;
	strDescPtr    = (Uint16 *)strDesc;
	dataReadBuffPtr  = (Uint16 *)dataReadBuff;
	dataWriteBuffPtr = (Uint16 *)dataWriteBuff;
	
	while(stopRunning != TRUE);

	result = CSL_USB_TEST_PASSED;
	return(result);
}
コード例 #14
0
/**
 *  \brief  Audio Class intialization function
 *
 *  \param  None
 *
 *  \return None
 */
void CSL_acTest(void)
{
    I2sInitPrms i2sInitPrms;
    CSL_UsbConfig usbConfig;
    PSP_Result result;
    Int16 status;
    HWI_Attrs attrs;


    LOG_printf(&trace, "USB ISO FULL SPEED MODE\n");

    /* Initialize audio module */
    result = AIC3254_init();
    if(result != 0)
    {
        LOG_printf(&trace, "ERROR: Unable to configure audio codec");
    }
    else
    {
#if !defined(SAMPLE_BY_SAMPLE_PB) || !defined(SAMPLE_BY_SAMPLE_REC)
        DMA_HwInit();
        DMA_DrvInit();
#endif

        /* Initialize I2S and associated DMA channels for Playback and Record */
        i2sInitPrms.enablePlayback = TRUE;
        i2sInitPrms.enableStereoPb = TRUE;
#ifdef SAMPLE_BY_SAMPLE_PB
        i2sInitPrms.sampleBySamplePb = TRUE;
#else /* Configuration untested since ASRC only works with I2S in sample-by-sample mode */
        i2sInitPrms.sampleBySamplePb = FALSE;
        i2sInitPrms.enableDmaPingPongPb = FALSE;
        i2sInitPrms.pingI2sTxLeftBuf = ping_i2sTxLeftBuf;
        i2sInitPrms.pongI2sTxLeftBuf = pong_i2sTxLeftBuf;
        i2sInitPrms.pingI2sTxRightBuf = ping_i2sTxRightBuf;
        i2sInitPrms.pongI2sTxRightBuf = pong_i2sTxRightBuf;
        i2sInitPrms.zeroBuf = ZeroBuf;
#endif
        i2sInitPrms.i2sPb = PSP_I2S_TX_INST_ID;
        i2sInitPrms.enableRecord = TRUE;
        i2sInitPrms.enableStereoRec = FALSE;
#ifdef SAMPLE_BY_SAMPLE_REC
        i2sInitPrms.sampleBySampleRec = TRUE;
#else
        i2sInitPrms.sampleBySampleRec = FALSE;
        i2sInitPrms.enableDmaPingPongRec = TRUE;
        i2sInitPrms.pingI2sRxLeftBuf = (Int16 *)ping_pong_i2sRxLeftBuf;
        i2sInitPrms.pongI2sRxLeftBuf = NULL;
        i2sInitPrms.pingI2sRxRightBuf = (Int16 *)ping_pong_i2sRxRightBuf;
        i2sInitPrms.pongI2sRxRightBuf = NULL;
#endif
        i2sInitPrms.i2sRec = PSP_I2S_RX_INST_ID;
        status = i2sInit(&i2sInitPrms);
        if (status != I2SSAMPLE_SOK)
        {
            LOG_printf(&trace, "ERROR: Unable to initialize I2S");
        }

#ifdef C5535_EZDSP_DEMO
		// initialize the OLED display        
        oled_init();
#endif
        
        /* Initialising the Pointer to the Audio Class Handle to the Buffer Allocated */
        AC_AppHandle.pAcObj = &ACAppBuffer[0];

        usbConfig.devNum                = CSL_USB0;
        usbConfig.opMode                = CSL_USB_OPMODE_POLLED;
#ifdef APP_USB_SELF_POWERED
        usbConfig.selfPowered           = TRUE;
#else
        usbConfig.selfPowered           = FALSE;
#endif
        usbConfig.maxCurrent            = APP_USB_MAX_CURRENT;
        usbConfig.appSuspendCallBack    = (CSL_USB_APP_CALLBACK)CSL_suspendCallBack;
        usbConfig.appWakeupCallBack     = (CSL_USB_APP_CALLBACK)CSL_selfWakeupCallBack;
        usbConfig.startTransferCallback  = StartTransfer;
        usbConfig.completeTransferCallback = CompleteTransfer;

        USB_init(&usbConfig);

        USB_setFullSpeedMode(0x40); /* parameter is EP0 data size in bytes */

        USB_resetDev(CSL_USB0);

        /* Calling init routine */
        /* Giving all the table hanldes and the buffers to the Audio Class module */
        AC_AppHandle.strDescrApp = (char **)&string_descriptor[0];
        AC_AppHandle.lbaBufferPbApp = &lbaBufferPbApp[0];
        AC_AppHandle.lbaBufferRecApp = &lbaBufferRecApp[0];
        AC_AppHandle.lbaBufferHidReportApp = &lbaBufferHidReportApp[0];
        AC_AppHandle.acReqTableApp = USB_ReqTable;
        AC_AppHandle.pId = pId;
        AC_AppHandle.vId = vId;

#ifndef ENABLE_PLAYBACK_TWO_SAMPLE_RATES
        #ifdef SAMPLE_RATE_TX_48kHz
        LOG_printf(&trace, "PLAYBACK: 48KHZ ");
        #ifdef ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "STEREO\n");
        AC_AppHandle.rxPktSize = EP_PB_MAXP; // max packet size for 48K stereo
        #else // ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "MONO\n");
        AC_AppHandle.rxPktSize = 0x60; // max packet size for 48K mono
        #endif // ENABLE_STEREO_PLAYBACK
        #endif // SAMPLE_RATE_TX_48kHz

        #ifdef SAMPLE_RATE_TX_44_1kHz
        LOG_printf(&trace, "PLAYBACK: 44.1KHZ ");
        #ifdef ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "STEREO\n");
        AC_AppHandle.rxPktSize = 0xB0; // max packet size for 44.1 stereo
        #else // ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "MONO\n");
        AC_AppHandle.rxPktSize = 0x58; // max packet size for 44.1 mono
        #endif // ENABLE_STEREO_PLAYBACK
        #endif // SAMPLE_RATE_TX_44_1kHz

        #ifdef SAMPLE_RATE_TX_32kHz
        LOG_printf(&trace, "PLAYBACK: 32KHZ ");
        #ifdef ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "STEREO\n");
        AC_AppHandle.rxPktSize = 0x80; // max packet size for 32K stereo
        #else // ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "MONO\n");
        AC_AppHandle.rxPktSize = 0x40; // max packet size for 32K mono
        #endif // ENABLE_STEREO_PLAYBACK
        #endif // SAMPLE_RATE_TX_32kHz

        #ifdef SAMPLE_RATE_TX_16kHz
        LOG_printf(&trace, "PLAYBACK: 16KHZ ");
        #ifdef ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "STEREO\n");
        AC_AppHandle.rxPktSize = RX_PKT_SIZE_16K_PLAYBACK_STEREO; // max packet size for 16K stereo
        rx_pkt_size_16K_playback = RX_PKT_SIZE_16K_PLAYBACK_STEREO; // max packet size for 16K stereo
        #else // ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "MONO\n");
        AC_AppHandle.rxPktSize = RX_PKT_SIZE_16K_PLAYBACK_MONO; // max packet size for 16K mono
        rx_pkt_size_16K_playback = RX_PKT_SIZE_16K_PLAYBACK_MONO;  // max packet size for 16K mono
        #endif // ENABLE_STEREO_PLAYBACK
        #endif // SAMPLE_RATE_TX_16kHz

#else /* ENABLE_PLAYBACK_TWO_SAMPLE_RATES */
        LOG_printf(&trace, "PLAYBACK: 48KHZ ");
        #ifdef ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "STEREO\n");
        AC_AppHandle.rxPktSize = EP_PB_MAXP; // max packet size for 48K stereo
        #else // ENABLE_STEREO_PLAYBACK
        LOG_printf(&trace, "MONO\n");
        AC_AppHandle.rxPktSize = 0x60; // max packet size for 48K mono
        #endif // ENABLE_STEREO_PLAYBACK

        LOG_printf(&trace, "PLAYBACK: 16KHZ ");
        #ifdef ENABLE_STEREO_PLAYBACK
        rx_pkt_size_16K_playback = RX_PKT_SIZE_16K_PLAYBACK_STEREO; // max packet size for 16K stereo
        LOG_printf(&trace, "STEREO\n");
        #else // ENABLE_STEREO_PLAYBACK
        rx_pkt_size_16K_playback = RX_PKT_SIZE_16K_PLAYBACK_MONO;  // max packet size for 16K mono
        LOG_printf(&trace, "MONO\n");
        #endif // ENABLE_STEREO_PLAYBACK
#endif /* ENABLE_PLAYBACK_TWO_SAMPLE_RATES */

        AC_AppHandle.txPktSize = EP_REC_MAXP; // max packet size for 16K mono
        AC_AppHandle.hidTxPktSize = EP_HID_MAXP; // max packet size for HID output report

        /* All Function Handlers need to be Initialised */
        AC_AppHandle.playAudioApp = appPlayAudio;
        AC_AppHandle.recordAudioApp = appRecordAudio;
        AC_AppHandle.initPlayAudioApp = appInitPlayAudio;
        AC_AppHandle.initRecordAudioApp = appInitRecordAudio;
        AC_AppHandle.stopPlayAudioApp = appStopPlayAudio;
        AC_AppHandle.stopRecordAudioApp = appStopRecordAudio;
        AC_AppHandle.mediaGetPresentStateApp = AppGetMediaStatus;
        AC_AppHandle.mediaInitApp = AppMediaInit;
        AC_AppHandle.mediaEjectApp = AppMediaEject;
        AC_AppHandle.mediaLockUnitApp = AppLockMedia;
        AC_AppHandle.getMediaSizeApp = AppGetMediaSize;
        AC_AppHandle.getHidReportApp = appGetHidReport;
        AC_AppHandle.ctrlHandler  = appCtrlFxn;
        AC_AppHandle.isoHandler   = appIsoFxn;
        AC_AppHandle.hidHandler = appHidFxn;

        AC_AppHandle.numLun = 2;

        /* Initialize End point descriptors */
        AC_initDescriptors(AC_AppHandle.pAcObj, (Uint16 *)deviceDescriptorB,
                            CSL_AC_DEVICE_DESCR, sizeof(deviceDescriptorB));

        AC_initDescriptors(AC_AppHandle.pAcObj, (Uint16 *)deviceQualifierDescr,
                            CSL_AC_DEVICE_QUAL_DESCR, 10);

        AC_initDescriptors(AC_AppHandle.pAcObj, (Uint16 *)configDescriptor,
                            CSL_AC_CONFIG_DESCR, sizeof(configDescriptor));

        AC_initDescriptors(AC_AppHandle.pAcObj, (Uint16 *)stringLanId,
                            CSL_AC_STRING_LANGID_DESC, 6);

        AC_initDescriptors(AC_AppHandle.pAcObj, (Uint16 *)acHidReportDescriptor,
                            CSL_AC_HID_REPORT_DESC, sizeof(acHidReportDescriptor));

        /* Initialize HID */
        AC_AppHandle.acHidIfNum = IF_NUM_HID; // HID interface number
        AC_AppHandle.acHidReportId = HID_REPORT_ID; // HID report ID
        AC_AppHandle.acHidReportLen = HID_REPORT_SIZE_BYTES; // HID report length (bytes)
        genHidReport(UI_PUSH_BUTTON_NONE, gHidReport); // init. HID report for Get Report 

        /* Call Init API */
        AC_Open(&AC_AppHandle);

        /* Enable CPU USB interrupts */
        CSL_FINST(CSL_CPU_REGS->IER1, CPU_IER1_USB, ENABLE);

        /* Initialize active sample rate */
        initSampleRate(RATE_48_KHZ, &active_sample_rate, 
            &i2sTxBuffSz);

        /* Initialize ASRC */ 
        Init_Sample_Rate_Converter(active_sample_rate);

        /* Reset codec output buffer */
        reset_codec_output_buffer();

        #ifdef ENABLE_RECORD
        #ifdef SAMPLE_RATE_RX_48kHz
        LOG_printf(&trace, "RECORD: 48KHZ ");
        #else
        LOG_printf(&trace, "RECORD: 16KHZ ");
        #endif // SAMPLE_RATE_RX_48kHz
        // start the rx DMAs
        DMA_StartTransfer(hDmaRxLeft);

        #ifdef ENABLE_STEREO_RECORD
        LOG_printf(&trace, "STEREO  NOT SUPPORTED - RECORD WILL BE MONO\n");
        DMA_StartTransfer(hDmaRxRight);
         #else
        LOG_printf(&trace, "MONO\n");
        #endif

        #endif // ENABLE_RECORD

#ifdef STORE_PARAMETERS_TO_SDRAM
        initSdram(FALSE, 0x0000);
#endif // STORE_PARAMETERS_TO_SDRAM
#ifdef SAMPLE_BY_SAMPLE_PB
        /* SampleBySample, init interrupt */       
        /* Use with compiler "interrupt" keyword */
        //IRQ_plug(I2S_TX_EVENT, i2s_txIsr);
        
        /* Use with dispatcher, no "interrupt" keyword */
        attrs.ier0mask = 0xFFFF;
        attrs.ier1mask = 0xFFFF;
        HWI_dispatchPlug(I2S_TX_EVENT, (Fxn)i2s_txIsr, &attrs);

        IRQ_enable(I2S_TX_EVENT);   /* SampleBySample, enable IRQ for I2S Tx */
#endif
#if defined(SAMPLE_BY_SAMPLE_REC) && !defined(COMBINE_I2S_TX_RX_ISR)
        /* SampleBySample, init interrupt */
        /* Use with compiler "interrupt" keyword */
        IRQ_plug(I2S_RX_EVENT, i2s_rxIsr);
        
        /* Use with dispatcher, no "interrupt" keyword */
        //attrs.ier0mask = 0xFFFF;
        //attrs.ier1mask = 0xFFFF;
        //HWI_dispatchPlug(I2S_RX_EVENT, (Fxn)i2s_rxIsr, &attrs);

        IRQ_enable(I2S_RX_EVENT);    /* SampleBySample, enable IRQ for I2S Rx */
#endif
#if defined(SAMPLE_BY_SAMPLE_PB) || defined(SAMPLE_BY_SAMLE_REC)
        DDC_I2S_transEnable((DDC_I2SHandle)i2sHandleTx, TRUE);    /* SampleBySample, enable I2S transmit and receive */
#endif
#ifndef SAMPLE_BY_SAMPLE_PB
        i2sTxStart(); // - moved from appPlayAudio()
#endif

#ifdef C5535_EZDSP_DEMO
        // clock gating usused peripherals
		ClockGating();
#endif
    }
}
コード例 #15
0
ファイル: MassStorage.c プロジェクト: jlhonora/pendrive
void MassStorage(void)
{
    buttonsPressed = 0;

    SFRIE1 &= ~OFIE;
    disk_initialize(0);                   // Initialize Disk Drive #0

    SFRIE1 |= OFIE;

    DEBUG("Init clock\r\n");
    ClockUSB();

    DEBUG("Init USB\r\n");
    USB_init();                           // Initialize the USB module
    P1OUT |= BIT1;

    // Enable all USB events
    USB_setEnabledEvents(kUSB_allUsbEvents);

    // Clal Initialization Function
    DEBUG("Init MSC\r\n");
    msc_Init();
    P1OUT |= BIT2;

    // If USB is already connected when the program starts up, then there won't be a
    // USB_handleVbusOnEvent().
    // So we need to check for it, and manually connect if the host is already present.
    if (USB_connectionInfo() & kUSB_vbusPresent)
    {
        if (USB_enable() == kUSB_succeed)
        {
            USB_reset();
            USB_connect();
            P1OUT |= BIT3;
        }
    }

    while (1)
    {
        switch (USB_connectionState())
        {
            DEBUG("Connection state: %u\r\n", USB_connectionState());
            case ST_USB_DISCONNECTED:
                //__bis_SR_register(LPM3_bits + GIE);    // Enter LPM3 until VBUS-on event
                _NOP();
                break;

            case ST_USB_CONNECTED_NO_ENUM:
                break;

            case ST_ENUM_ACTIVE:

                msc_Loop();
                break;

            case ST_ENUM_SUSPENDED:
                //__bis_SR_register(LPM3_bits + GIE);    // Enter LPM3, until a resume or VBUS-off
                                                       // event
                break;

            case ST_ENUM_IN_PROGRESS:
                break;

            case ST_ERROR:
                break;
            default:;
        }
    }

    DEBUG("Done with MassStorage\r\n");
    buttonsPressed = 0;
    Board_ledOff(LED_ALL);
    USB_disable();
    SFRIE1 &= ~OFIE;
    Init_FLL_Settle(25000, 762);          // Return to normal clock settings
    SFRIE1 |= OFIE;
}
コード例 #16
0
ファイル: usb_int.c プロジェクト: yfang1644/DSP55X
/**
 *  \brief  Tests USB interrupt mode operation
 *
 *  \param  none
 *
 *  \return Test result
 */
Int16 BoardUSB_init(void)
{
	Uint16 eventMask;
	Int16 looper;
	CSL_UsbConfig usbConfig;

	usbConfig.opMode             = CSL_USB_OPMODE_POLLED;
    usbConfig.devNum             = CSL_USB0;
	usbConfig.maxCurrent         = CSL_USB_MAX_CURRENT;
	usbConfig.appSuspendCallBack = (CSL_USB_APP_CALLBACK)NULL;
	usbConfig.appWakeupCallBack  = (CSL_USB_APP_CALLBACK)NULL;
	usbConfig.startTransferCallback  = CSL_startTransferCallback;
	usbConfig.completeTransferCallback = NULL;

	hEpObjArray[0] = &usbCtrlOutEpObj;
	hEpObjArray[1] = &usbCtrlInEpObj;
	hEpObjArray[2] = &usbBulkOutEpObj;
	hEpObjArray[3] = &usbBulkInEpObj;

	CSL_CPU_REGS->IER1 |= 0x0010;		// enable USB interrupt

	/* Initialize the USB module */
	status = USB_init(&usbConfig);	// never fail

	/* Reset the USB device */
	status = USB_resetDev(CSL_USB0);	// never fail when CSL_USB0

	/* Initialize the Control Endpoint OUT 0 */
	eventMask = CSL_USB_EVENT_RESET |
				CSL_USB_EVENT_SETUP |
				CSL_USB_EVENT_SUSPEND |
				CSL_USB_EVENT_RESUME |
				CSL_USB_EVENT_EOT;

	status = USB_initEndptObj(CSL_USB0, hEpObjArray[0], CSL_USB_OUT_EP0,
							  CSL_USB_CTRL, CSL_USB_EP0_PACKET_SIZE,
							  eventMask, NULL);
	if(status != CSL_SOK)	// USB End point init failed
		return status;

	/* Initialize the Control Endpoint IN 0 */
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[1], CSL_USB_IN_EP0,
							  CSL_USB_CTRL, CSL_USB_EP0_PACKET_SIZE,
							  CSL_USB_EVENT_EOT, NULL);
	if(status != CSL_SOK)	// USB End point init failed
		return status;

	/* Initialize the Bulk Endpoint IN 1 */
	eventMask = CSL_USB_EVENT_RESET | CSL_USB_EVENT_EOT;
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[2], CSL_USB_IN_EP1,
							  CSL_USB_BULK, CSL_USB_EP1_PACKET_SIZE_HS,
							  eventMask, NULL);
	if(status != CSL_SOK)	// USB End point init failed
		return status;

	/* Initialize the Bulk Endpoint OUT 2 */
	eventMask = CSL_USB_EVENT_RESET | CSL_USB_EVENT_EOT;
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[3], CSL_USB_OUT_EP2,
							  CSL_USB_BULK, CSL_USB_EP2_PACKET_SIZE_HS,
							  eventMask, NULL);
	if(status != CSL_SOK)	//  USB End point init failed
		return status;

	/* Set the parameters */
	USB_setParams(CSL_USB0, hEpObjArray, TRUE);
/*
	for(looper = 0; looper < CSL_USB_ENDPOINT_COUNT; looper++) {
		gUsbEpHandle[looper] = hEpObjArray[looper];
		if(hEpObjArray[looper] == NULL)
			break;
	}
*/

	/* Connect the USB device */
	CSL_FINS(usbRegisters->FADDR_POWER, USB_FADDR_POWER_SOFTCONN, TRUE);

	return CSL_SOK;
}
コード例 #17
0
ファイル: main.c プロジェクト: TECHNOTICSROBOTICS/mspdev
VOID main(VOID) 
{
    WDTCTL = WDTPW + WDTHOLD;	    // Stop watchdog timer
    
    Init_StartUp();                 //initialize device
    USB_init();
    
    USB_setEnabledEvents(USBEVIE);
    
    // See if we're already attached physically to USB, and if so, connect to it
    // Normally applications don't invoke the event handlers, but this is an exception.  
    if (USB_connectionInfo() & kUSB_vbusPresent)
      USB_handleVbusOnEvent();
    
    
    while(1)
    {
        switch(USB_connectionState())
        {
           case ST_USB_DISCONNECTED:
                 __bis_SR_register(LPM3_bits + GIE); 	  // Enter LPM3 w/interrupt
                _NOP();
                break;
                
           case ST_USB_CONNECTED_NO_ENUM:
                break;
                
           case ST_ENUM_ACTIVE:
                __bis_SR_register(LPM0_bits + GIE); 	  // Enter LPM0 until an event occurs.  


                // This flag would have been set by the handleDataReceived event; this event is only enabled when waiting
                // for 'press any key'
                if(bCDCDataReceived_event) 
                {
                  bCDCDataReceived_event = FALSE;            

                  // Change the event flags, in preparation for receiving 1K data
                  USBEVIE &= ~kUSB_dataReceivedEvent;      // No more data-received.  We only used this for 'press any key'
                  USBEVIE |= kUSB_receiveCompletedEvent;   // But enable receive-completed; we want to be prompted when 1K data has been received
                  USB_setEnabledEvents(USBEVIE);
                  USBCDC_rejectData(0);                    // We don't care what char the key-press was

                  // Prompt user for 1K data
                  strcpy(outString,"I'm ready to receive 1K of data.\r\n");           // Prepare the outgoing string
                  
                  if(cdcSendDataWaitTilDone((BYTE*)outString,strlen(outString),0,0)) // Send it over USB
                  {
                    USBCDC_abortSend(&x,0);                                           // It failed for some reason; abort and leave the main loop
                    break;
                  }
                 
                  // Set up rcv operation for 1K data
                  if(USBCDC_receiveData(dataBuff,1024,0) == kUSBCDC_busNotAvailable) //first USBCDC_receiveData
                  {
                    USBCDC_abortReceive(&x,0);                                       // It failed because of surprise removal or suspended by host; 
                    break;                                                           // abort and leave the main loop
                  }                  
                }
                
                // This flag would have been set by the handleReceiveCompleted event; this event is only enabled  
                // while receiving 1K data, and signals that all 1K has been received
                if(bDataReceiveCompleted_event) 
                {
                  bDataReceiveCompleted_event = FALSE;
                  strcpy(outString,"Thanks for the data.\r\n");                     // Prepare the outgoing string
                  if(cdcSendDataInBackground((BYTE*)outString,strlen(outString),0,0)) //Send the response over USB
                  {
                    USBCDC_abortSend(&x,0);                                         // It failed for some reason; abort and leave the main loop
                    break;
                  }
                  
                  // Change the event flags, in preparation for 'press any key'
                  USBEVIE &= ~kUSB_receiveCompletedEvent;  // No more receive-completed.  
                  USBEVIE |= kUSB_dataReceivedEvent;       // This will tell us that data -- any data -- has arrived (i.e., a key-press)
                  USB_setEnabledEvents(USBEVIE);                
                } 
                    
                break;
                
           case ST_ENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE); 	        // Enter LPM3 w/ interrupts
                _NOP();
                break;
                
           case ST_ENUM_IN_PROGRESS:
                break;
                
          case ST_NOENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE);  
                _NOP();
                break;
                
           case ST_ERROR:
                _NOP();
                break;
                
           default:;
        } 
    
    }  // while(1) 
} //main()
コード例 #18
0
ファイル: main.c プロジェクト: TECHNOTICSROBOTICS/mspdev
/*----------------------------------------------------------------------------+
| Main Routine                                                                |
+----------------------------------------------------------------------------*/
VOID main(VOID)
{
    WDTCTL = WDTPW + WDTHOLD;	    // Stop watchdog timer
    
    Init_StartUp();
    USB_init();
    USB_setEnabledEvents(kUSB_VbusOnEvent + kUSB_VbusOffEvent + kUSB_UsbSuspendEvent + kUSB_UsbResumeEvent + kUSB_dataReceivedEvent);
   
    // Check if we're already physically attached to USB, and if so, connect to it
    // This is the same function that gets called automatically when VBUS gets attached.  
    if (USB_connectionInfo() & kUSB_vbusPresent)
      USB_handleVbusOnEvent();
              
    // Pre-fill the buffers with visible ASCII characters (0x21 to 0x7E)

    for(x=0;x<BUF_SIZE;x++)
    {
      dataBuf[x] = y++;
      if(y>0x7E)
        y = 0x21;
    }
    
    
    while(1)
    {
        switch(USB_connectionState())
        {
           case ST_USB_DISCONNECTED:
                 __bis_SR_register(LPM3_bits + GIE); 	  // Enter LPM3 w/interrupt
                break;
                
           case ST_USB_CONNECTED_NO_ENUM:
                break;
                
           case ST_ENUM_ACTIVE:
                if(!bHIDDataReceived_event)                          // Do this until a key is pressed
                {
                  strcpy(outString,"Press any key.\r");                             // Prepare the outgoing string
                  if(hidSendDataWaitTilDone((BYTE*)outString,strlen(outString),0,0))  // Send it; no timeout
                  {                      
                    USBHID_abortSend(&x,0);               // Operation may still be open; cancel it
                    break;                                
                  }
                }
                else
                {
                 bHIDDataReceived_event = FALSE;
                  USBHID_rejectData(0);
                  for(rounds=0;rounds<300;rounds++)
                  {
                    if(hidSendDataWaitTilDone(dataBuf,BUF_SIZE,0,0))     // Send all of RAM
                    {
                      USBHID_abortSend(&x,0);               // Operation probably still open; cancel it
                      break;
                    }
                  }
                  strcpy(outString,"\r\n\r\n\r\nThe test is completed.\r\n");       // Prepare the outgoing string
                  if(hidSendDataWaitTilDone((BYTE*)outString,strlen(outString),0,0))  // Send it; no timeout
                  {
                    USBHID_abortSend(&x,0);                 // Operation may still be open; cancel it
                    break;                                 
                  }
                }
                break;
                
           case ST_ENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE); 	 // Enter LPM3 w/interrupt
                break;
                
           case ST_ENUM_IN_PROGRESS:
                break;
                
           case ST_NOENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE);                
                break;                
                
           case ST_ERROR:
                _NOP();
                break;
                
           default:;
        }
    }  // while(1) 
} //main()
コード例 #19
0
ファイル: main.c プロジェクト: TECHNOTICSROBOTICS/mspdev
/*----------------------------------------------------------------------------+
| Main Routine                                                                |
+----------------------------------------------------------------------------*/
VOID main(VOID)
{
    BYTE y;
    WDTCTL = WDTPW + WDTHOLD;	    // Stop watchdog timer
    
    Init_StartUp();
    USB_init();
 
    USB_setEnabledEvents(kUSB_VbusOnEvent+kUSB_VbusOffEvent+kUSB_receiveCompletedEvent
                          +kUSB_dataReceivedEvent+kUSB_UsbSuspendEvent+kUSB_UsbResumeEvent+kUSB_UsbResetEvent);
    
    // Check if we're already physically attached to USB, and if so, connect to it
    // This is the same function that gets called automatically when VBUS gets attached.  
    if (USB_connectionInfo() & kUSB_vbusPresent)
      USB_handleVbusOnEvent();

    // Pre-fill the buffers with visible ASCII characters (0x21 to 0x7E)
    y=0x21;
    for(w=0;w<MEGA_DATA_LENGTH;w++)
    {
      bufferX[w] = y;
      bufferY[w] = y++;
      if(y>0x7E)
        y = 0x21;
    }
    
                 
    while(1)
    {
        switch(USB_connectionState())
        {
           case ST_USB_DISCONNECTED:
                 __bis_SR_register(LPM3_bits + GIE); 	  // Enter LPM3 w/interrupt
                break;
                
           case ST_USB_CONNECTED_NO_ENUM:
                break;
                
           case ST_ENUM_ACTIVE:
                if(!bCDCDataReceived_event)                         // Do this until a key is pressed
                {
                  strcpy(pakOutString,"Press any key.\r");                                 // Prepare the outgoing string
                  if(cdcSendDataInBackground((BYTE*)pakOutString,strlen(pakOutString),0,0))   // Send it
                  {
                    USBCDC_abortSend(&w,0);              // Operation probably still open; cancel it
                    break;                               // The break isn't really necessary since it'll go to the end of the loop anyway, but it's shown for completeness
                  }
                }
                else
                {
                  if(cdcSendDataInBackground((BYTE*)bufferX,MEGA_DATA_LENGTH,0,0))
                  {
                    bCDCDataReceived_event = FALSE;
                    USBCDC_abortSend(&w,0);              // Operation probably still open; cancel it
                    break;
                  }
                  // Between these functions, don't modify bufferX.  However, bufferY can be modified.  
                  if(cdcSendDataInBackground((BYTE*)bufferY,MEGA_DATA_LENGTH,0,0))
                  {
                    bCDCDataReceived_event = FALSE;
                    USBCDC_abortSend(&w,0);              // Operation probably still open; cancel it
                    break;
                  }
                  // Until the next call to sendData_inBackground(), don't modify bufferY.  However, bufferX can be modified.  
                  
                  if(rounds++>=500)
                  {
                    strcpy(outString,"\r\n\r\nThe test is completed.\r\n\r\n");                  // Prepare the outgoing string
                    if(cdcSendDataInBackground((BYTE*)outString,strlen(outString),0,0))  // Send it
                    {
                      USBCDC_abortSend(&w,0);            // Operation may still be open; cancel it
                      break;
                    }
                    bCDCDataReceived_event= FALSE;
                    rounds = 0;
                    USBCDC_rejectData(0);                // Reject data from previous keypress, in preparation for another one
                  }                                      // It's been in the USB buffer all this time...
                }
                break;
                
           case ST_ENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE); 	// Enter LPM3 w/interrupt
                break;
                
          	case ST_ENUM_IN_PROGRESS:
                break;
           
           case ST_NOENUM_SUSPENDED:
                __bis_SR_register(LPM3_bits + GIE);  
                _NOP();
                break;
                
           case ST_ERROR:
                _NOP();
                break;
                
           default:;
        }
    }  // while(1) 
} //main()
コード例 #20
0
ファイル: main.c プロジェクト: eddyem/IR-controller
int main(){
	//int i;
	uint32_t Shtr_blink_timer = 0, Old_timer = 0, lastTRDread = 0, lastTmon = 0, OW_timer = 0;
	int oldusbdatalen = 0;
	//SPI_read_status SPI_stat;

	// RCC clocking: 8MHz oscillator -> 72MHz system
	rcc_clock_setup_in_hse_8mhz_out_72mhz();

	// turn off SWJ/JTAG
	AFIO_MAPR = AFIO_MAPR_SWJ_CFG_JTAG_OFF_SW_OFF;

	// GPIO
	GPIO_init();
	usb_disconnect(); // turn off USB while initializing all

	// init USART3 (master) & USART1 (slave)
	UART_init(USART3);
	UART_init(USART1);

	// USB
	usbd_dev = USB_init();

	// SysTick is a system timer with 1mc period
	SysTick_init();

	// instead of SPI1 we use those pins to control shutter and system state
	// SPI2 used for working with external ADC
	switch_SPI(SPI2); // init SPI2
	SPI_init();

	// wait a little and then turn on USB pullup
//	for (i = 0; i < 0x800000; i++)
//		__asm__("nop");

	// init ADC
	ADC_init();
	ADC_calibrate_and_start();

	steppers_init();

	usb_connect(); // turn on USB
	shutter_init();

	read_stored_data(); // copy stored data into RAM

	init_ow_dmatimer();
	//OW_send_read_seq();

	LED_STATUS_OK(); // All initialized - light up LED
	while(1){
		init_on_poweron_proc();
		usbd_poll(usbd_dev);
		if(oldusbdatalen != usbdatalen){ // there's something in USB buffer
			usbdatalen = parce_incoming_buf(usbdatabuf, usbdatalen, usb_send);
			oldusbdatalen = usbdatalen;
		}
		check_and_parce_UART(USART3); // check data in master UART buffers
		check_and_parce_UART(USART1); // also check data in slave UART buffers
		if(ad7794_on){
			if(Timer != lastTRDread){ // run this not more than once in 1ms
				lastTRDread = Timer;
				read_next_TRD();
			}
		}
		OW_process(); // process 1-wire commands
		// scan 1-wire each 1 second
		if(OW_scan && (Timer - OW_timer > 999 || Timer < OW_timer)){
			OW_timer = Timer;
			scan_onewire();
		}
		process_stepper_motors(); // check flags of motors' timers
		process_shutter(); // shutter state machine

		if(Timer - Shtr_blink_timer > 500 ||  Timer < Shtr_blink_timer){
			Shtr_blink_timer = Timer;
			// shutter LED will be blinking until init occurs
			if(Shutter_State == SHUTTER_NOTREADY)
				gpio_toggle(LED_SHUTTER_PORT, LED_SHUTTER_PIN);
		}

		if(Timer - Old_timer > 999){ // one-second cycle
			Old_timer += 1000;
			// init shutter if error occurs
			if(Shutter_State == SHUTTER_NOTREADY){
				shutter_init();
			}
		}else if(Timer < Old_timer){ // Timer overflow
			Old_timer = 0;
			tOVRFL++; // this is an overflow counter - for workinkg in long-long time interval
		}

		if((Timer - lastTmon > 9999) || (Timer < lastTmon)){ // run constant monitoring of ADC values each 10 seconds
			lastTmon += 10000;
			if(ADC_monitoring){
				print_time(lastsendfun);
				print_int_ad_vals(lastsendfun);
				print_ad_vals(lastsendfun);
			}
		}
	}
}
コード例 #21
0
CSL_Status CSL_usbPollTest(void)
{
	CSL_Status        status;
	CSL_Status        result;
	pUsbContext       pContext;
	pUsbEpHandle      hEPx;
	CSL_UsbBoolean    txRxStatus;
	Uint16            bytesRem;
	Uint16            eventMask;
	Uint16            saveIndex;
	Uint16            endpt;
	pUsbEpHandle tempEpH;

	pContext = &gUsbContext;
	result   = CSL_USB_TEST_FAILED;

	usbConfig.opMode             = CSL_USB_OPMODE_POLLED;
    usbConfig.devNum             = CSL_USB0;
	usbConfig.maxCurrent         = CSL_USB_MAX_CURRENT;
	usbConfig.appSuspendCallBack = (CSL_USB_APP_CALLBACK)CSL_suspendCallBack;
	usbConfig.appWakeupCallBack  = (CSL_USB_APP_CALLBACK)CSL_selfWakeupCallBack;
	usbConfig.startTransferCallback  = CSL_startTransferCallback;
	usbConfig.completeTransferCallback = CSL_completeTransferCallback;

	hEpObjArray[0] = &usbCtrlOutEpObj;
	hEpObjArray[1] = &usbCtrlInEpObj;
	hEpObjArray[2] = &usbBulkOutEpObj;
	hEpObjArray[3] = &usbBulkInEpObj;

#ifdef CSL_USB_SELFWAKEUP_TEST

	/* Configure SAR to generate event for self wakeup */
	/* NOTE: Self Wakeup is interfaced to the STOP key of the EVM keypad */
	status = CSL_configSarForSelfWakeup();
	if(status != CSL_SOK)
	{
		printf("SAR Configuration failed\n");
		return(result);
	}

#endif  // CSL_USB_SELFWAKEUP_TEST

	/* Initialize the USB module */
	status = USB_init(&usbConfig);
	if(status != CSL_SOK)
	{
		printf("USB init failed\n");
		return(result);
	}

	/* Reset the USB device */
	status = USB_resetDev(CSL_USB0);
	if(status != CSL_SOK)
	{
		printf("USB Reset failed\n");
		return(result);
	}

	/* Initialized the Control Endpoint OUT 0 */
	eventMask = (CSL_USB_EVENT_RESET | CSL_USB_EVENT_SETUP |
				 CSL_USB_EVENT_SUSPEND | CSL_USB_EVENT_RESUME |
				 CSL_USB_EVENT_RESET | CSL_USB_EVENT_EOT);

	status = USB_initEndptObj(CSL_USB0, hEpObjArray[0],
	                          CSL_USB_OUT_EP0,CSL_USB_CTRL,
					          CSL_USB_EP0_PACKET_SIZE, eventMask, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Initialized the Control Endpoint IN 0 */
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[1], CSL_USB_IN_EP0,
	                          CSL_USB_CTRL, CSL_USB_EP0_PACKET_SIZE,
	                          CSL_USB_EVENT_EOT, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Initialize the Bulk Endpoint IN 1 */
	eventMask = (CSL_USB_EVENT_RESET | CSL_USB_EVENT_EOT);
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[2], CSL_USB_IN_EP1,
	                          CSL_USB_BULK, CSL_USB_EP1_PACKET_SIZE_FS,
	                          eventMask, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Initialize the Bulk Endpoint OUT 2 */
	status = USB_initEndptObj(CSL_USB0, hEpObjArray[3], CSL_USB_OUT_EP2,
	                          CSL_USB_BULK, CSL_USB_EP2_PACKET_SIZE_FS,
	                          CSL_USB_EVENT_EOT, NULL);
	if(status != CSL_SOK)
	{
		printf("USB End point init failed\n");
		return(result);
	}

	/* Set the parameters */
	status = USB_setParams(CSL_USB0, hEpObjArray, FALSE);
	if(status != CSL_SOK)
	{
		printf("USB Set params failed\n");
		return(result);
	}

	/* Connect the USB device */
	status = USB_connectDev(CSL_USB0);
	if(status != CSL_SOK)
	{
		printf("USB Connect failed\n");
		return(result);
	}

	deviceDescPtr = (Uint16 *)deviceDesc;
	cfgDescPtr    = (Uint16 *)cfgDesc;
	strDescPtr    = (Uint16 *)strDesc;
	selfWakeupServiced = TRUE;

	while(stopRunning != TRUE)
	{
    	/* Read the masked interrupt status register */
		pContext->dwIntSourceL = usbRegisters->INTMASKEDR1;
		pContext->dwIntSourceH = usbRegisters->INTMASKEDR2;

		/* Clear the interrupts */
		if(pContext->dwIntSourceL != FALSE)
		{
			usbRegisters->INTCLRR1 = pContext->dwIntSourceL;
		}

		if(pContext->dwIntSourceH != FALSE)
		{
			usbRegisters->INTCLRR2 = pContext->dwIntSourceH;
		}

		/* Reset interrupt */
		if(pContext->dwIntSourceH & CSL_USB_GBL_INT_RESET)
		{
			usbRegisters->INDEX_TESTMODE = usbRegisters->INDEX_TESTMODE & 0x00ff;

			if(usbBulkOutEpObj.epNum == CSL_USB_IN_EP1)
			{
				CSL_FINS(usbRegisters->INDEX_TESTMODE,
						 USB_INDEX_TESTMODE_EPSEL, CSL_USB_EP1);
				CSL_FINS(usbRegisters->PERI_CSR0_INDX,
				         USB_PERI_CSR0_INDX_RXPKTRDY, TRUE);
			}
			else
			{
				CSL_FINS(usbRegisters->INDEX_TESTMODE,
						 USB_INDEX_TESTMODE_EPSEL, CSL_USB_EP2);
				CSL_FINS(usbRegisters->PERI_CSR0_INDX,
				         USB_PERI_CSR0_INDX_RXPKTRDY, TRUE);
			}
		}

		/* Resume interrupt */
		if(pContext->dwIntSourceH & CSL_USB_GBL_INT_RESUME)
		{
			USB_setRemoteWakeup(CSL_USB0, CSL_USB_TRUE);
			status = USB_issueRemoteWakeup(CSL_USB0, TRUE);
			/* Give 10 msecs delay before resetting resume bit */
			USB_delay(CSL_USB_WAKEUP_DELAY);
			status = USB_issueRemoteWakeup(CSL_USB0, FALSE);
			if(status != CSL_SOK)
			{
				printf("USB Resume failed\n");
   /////INSTRUMENTATION FOR BATCH TESTING -- Part 2 --   
   /////  Reseting PaSs_StAtE to 0 if error detected here.
        PaSs_StAtE = 0x0000; // Was intialized to 1 at declaration.
   /////
			}
		}

		/* Check End point0 interrupts */
		if(pContext->dwIntSourceL & CSL_USB_TX_RX_INT_EP0)
		{
			saveIndex = usbRegisters->INDEX_TESTMODE;
				CSL_FINS(usbRegisters->INDEX_TESTMODE,
						 USB_INDEX_TESTMODE_EPSEL, CSL_USB_EP0);

			USB_getSetupPacket(CSL_USB0, &usbSetup, TRUE);

			if((usbRegisters->PERI_CSR0_INDX & CSL_USB_PERI_CSR0_INDX_RXPKTRDY_MASK)
					== CSL_USB_PERI_CSR0_INDX_RXPKTRDY_MASK)
			{
				/* Service the RXPKTRDY after reading the FIFO */
				CSL_FINS(usbRegisters->PERI_CSR0_INDX,
				         USB_PERI_CSR0_INDX_SERV_RXPKTRDY, TRUE);

				/* GET DESCRIPTOR Req */
				switch(usbSetup.bRequest)
				{
					/* zero data */
					case CSL_USB_SET_FEATURE:
						switch(usbSetup.wValue)
						{
							case CSL_USB_FEATURE_ENDPOINT_STALL:
								/* updated set and clear endpoint stall
								 * to work with logical endpoint num
								 */
								endpt = (usbSetup.wIndex) & 0xFF;
								hEPx = USB_epNumToHandle(CSL_USB0, endpt);
								if(!(USB_getEndptStall(hEPx, &status)))
								{
									USB_stallEndpt(hEPx);
								}
								break;

							case CSL_USB_FEATURE_REMOTE_WAKEUP:
								if(!(USB_getRemoteWakeupStat(CSL_USB0)))
								{
									USB_setRemoteWakeup(CSL_USB0, CSL_USB_TRUE);
								}
								break;

							default:
								break;
						}

						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_SERV_RXPKTRDY, TRUE);
						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_DATAEND, TRUE);
						break;

					case CSL_USB_CLEAR_FEATURE:
						switch(usbSetup.wValue)
						{
							case CSL_USB_FEATURE_ENDPOINT_STALL:
								endpt = (usbSetup.wIndex) & 0xFF;
								hEPx = USB_epNumToHandle(CSL_USB0, endpt);
								if(USB_getEndptStall(hEPx, &status))
								{
									USB_clearEndptStall(hEPx);
								}
								break;

							case CSL_USB_FEATURE_REMOTE_WAKEUP:
								if(USB_getRemoteWakeupStat(CSL_USB0))
								{
									USB_setRemoteWakeup(CSL_USB0,
									                    CSL_USB_FALSE);
								}
								break;

							default:
								 break;
						}
						break;

					case CSL_USB_SET_CONFIGURATION :
					case CSL_USB_SET_INTERFACE:
						endpt = (usbSetup.wIndex) & 0xFF;
						hEPx = USB_epNumToHandle(CSL_USB0, endpt);
						USB_postTransaction(hEPx, 0, NULL,
						                    CSL_USB_IOFLAG_NONE);

						/* DataEnd + ServicedRxPktRdy */
						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_SERV_RXPKTRDY, TRUE);
						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_DATAEND, TRUE);

						break;

					case CSL_USB_GET_DESCRIPTOR :

						switch(usbSetup.wValue >> 8)
						{
							case CSL_USB_DEVICE_DESCRIPTOR_TYPE:
								deviceDescPtr = (Uint16 *)deviceDesc;
								status = USB_postTransaction(hEpObjArray[1],
								                 deviceDesc[0]&0xFF, deviceDescPtr,
								                 CSL_USB_IN_TRANSFER);
								break;

							case CSL_USB_CONFIGURATION_DESCRIPTOR_TYPE:
								if(usbSetup.wLength == 0x0009)
								{
									cfgDescPtr = cfgDesc;
									status = USB_postTransaction(hEpObjArray[1],
									                 9, cfgDescPtr,
									                 CSL_USB_IN_TRANSFER);
								}
								else
								{
									cfgDescPtr = cfgDesc;
									status = USB_postTransaction(hEpObjArray[1],
									                 cfgDesc[1], cfgDescPtr,
									                 CSL_USB_IN_TRANSFER);
								}

								break;

							case CSL_USB_STRING_DESCRIPTOR_TYPE:
								if((usbSetup.wValue & 0xFF) == 0x00)
								{
									strDescPtr = (Uint16 *)strDesc[0];
									status = USB_postTransaction(hEpObjArray[1],
									                 strDesc[0][0]&0xFF, strDescPtr,
									                 CSL_USB_IN_TRANSFER);
								}
								if((usbSetup.wValue & 0xFF) == 0x01)
								{
									strDescPtr = (Uint16 *)strDesc[1];
									status = USB_postTransaction(hEpObjArray[1],
									                 strDesc[1][0]&0xFF, strDescPtr,
									                 CSL_USB_IN_TRANSFER);
								}
								if((usbSetup.wValue & 0xFF) == 0x02)
								{
									strDescPtr = (Uint16 *)strDesc[2];
									status = USB_postTransaction(hEpObjArray[1],
									                 strDesc[2][0]&0xFF, strDescPtr,
									                 CSL_USB_IN_TRANSFER);
								}
								if((usbSetup.wValue & 0xFF) == 0x03)
								{
									strDescPtr = (Uint16 *)strDesc[3];
									status = USB_postTransaction(hEpObjArray[1],
									                 strDesc[3][0]&0xFF, strDescPtr,
									                 CSL_USB_IN_TRANSFER);
								}
								break;

							default:
								break;
						}

						deviceDescPtr = (Uint16 *)deviceDesc;
						cfgDescPtr    = (Uint16 *)cfgDesc;
						strDescPtr    = (Uint16 *)strDesc[0];

						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_TXPKTRDY, TRUE);
						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_DATAEND, TRUE);
						break;

					case CSL_USB_SET_ADDRESS :
						devAddr = usbSetup.wValue;
						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_SERV_RXPKTRDY, TRUE);
						CSL_FINS(usbRegisters->PERI_CSR0_INDX,
						         USB_PERI_CSR0_INDX_DATAEND, TRUE);
						break;

					default:
						break;
				}
			}
			else
			{
				if(usbSetup.bRequest == 0x05)
コード例 #22
0
ファイル: main.c プロジェクト: TECHNOTICSROBOTICS/mspdev
/*----------------------------------------------------------------------------+
| Main Routine                                                                |
+----------------------------------------------------------------------------*/
VOID main(VOID)
{
    WDTCTL = WDTPW + WDTHOLD;	    // Stop watchdog timer
    Init_StartUp();                 // Initialize clocks, power, I/Os
    __enable_interrupt(); 
    USB_init();                     // Initialize the USB module


    // Enable all USB events
    USB_setEnabledEvents(kUSB_allUsbEvents);

    
    // The data interchange buffer (used when handling SCSI READ/WRITE) is declared by the application, and 
    // registered with the API using this function.  This allows it to be assigned dynamically, giving 
    // the application more control over memory management.  
    USBMSC_registerBufInfo(&RW_dataBuf[0], NULL, sizeof(RW_dataBuf));
   
    
    // The API maintains an instance of the USBMSC_RWbuf_Info structure.  If double-buffering were used, it would
    // maintain one for both the X and Y side.  (This version of the API only supports single-buffering,
    // so only one structure is maintained.)  This is a shared resource between the API and application; the 
    // application must request the pointers.  This function returns the pointer for a given LUN and buffer side.  
    RWbuf = USBMSC_fetchInfoStruct();  // 0 for X-buffer
    
    
    // The application must tell the API about the media.  Since the media isn't removable, this is only called 
    // once, at the beginning of execution.  If the media were removeable, the application must call this any time
    // the status of the media changes.  
    struct USBMSC_mediaInfoStr mediainfo; // This struct type contains information about the state of the medium.   
                                          // Since it's only used locally, it's declared within main so that it's 
                                          // taken from the heap rather than as a static global.
    mediainfo.mediaPresent = 0x01;        // The medium is present, because internal flash is non-removable.  
    mediainfo.mediaChanged = 0x00;        // It can't change, because it's in internal memory, which is always present.  
    mediainfo.writeProtected = 0x00;      // It's not write-protected
    mediainfo.lastBlockLba = 774;         // 774 blocks in the volume. (This number is also found twice in the volume itself; see mscFseData.c. They should match.)
    mediainfo.bytesPerBlock = BYTES_PER_BLOCK; // 512 bytes per block. (This number is also found in the volume itself; see mscFseData.c. They should match.)
    USBMSC_updateMediaInfo(0, &mediainfo); 
    
    // If USB is already connected when the program starts up, then there won't be a USB_handleVbusOnEvent(). 
    // So we need to check for it, and manually connect if the host is already present.   
    if (USB_connectionInfo() & kUSB_vbusPresent)
    {
        if (USB_enable() == kUSB_succeed)
        {
            USB_reset();
            USB_connect();
        }
    }

    
    while(1)
    {
        switch(USB_connectionState())
        {
        case ST_USB_DISCONNECTED:
             __bis_SR_register(LPM3_bits + GIE); 	       // Enter LPM3 until VBUS-on event
            
             // Check if the reason we woke was a button press; and if so, log a new piece of data.  
             if(fS1ButtonEvent)
             {
               // Build string
               char str[14] = "Data entry #0\n";
               str[12] = logCnt++;                             // Number the entries 0 through....?
               
               memcpy(RW_dataBuf, Data559, BYTES_PER_BLOCK);  // Copy data block 559 from flash to RAM buffer
               memcpy(&RW_dataBuf[DataCnt], str, sizeof(str)); // Write the new entry to the RAM buffer
               flashWrite_LBA((PBYTE)Data559, RW_dataBuf);    // Copy it back to flash
               
               DataCnt += sizeof(str);                         // Increment the index past the new entry
               if((DataCnt + sizeof(str)>= BYTES_PER_BLOCK))   // Roll index back to 0, if no more room in the block
                 DataCnt = 0;

               fS1ButtonEvent = 0;
             }
             
             break;
            
        case ST_USB_CONNECTED_NO_ENUM:
             break;
            
        case ST_ENUM_ACTIVE:             

                // Call USBMSC_poll() to initiate handling of any received SCSI commands.  Disable interrupts 
                // during this function, to avoid conflicts arising from SCSI commands being received from the host
                // AFTER decision to enter LPM is made, but BEFORE it's actually entered (avoid sleeping accidentally).  
                __disable_interrupt();
                if(USBMSC_poll() == kUSBMSC_okToSleep)
                {
                    __bis_SR_register(LPM0_bits + GIE);  // Enable interrupts atomically with LPM0 entry
                }
                __enable_interrupt();
                        
                            
                // If the API needs the application to process a buffer, it will keep the CPU awake by returning kUSBMSC_processBuffer
                // from USBMSC_poll().  The application should respond by checking the 'operation' field of all defined USBMSC_RWbuf_Info
                // structure instances.  If any of them is non-null, then an operation needs to be processed.  A value of 
                // kUSBMSC_READ indicates the API is waiting for the application to fetch data from the storage volume, in response 
                // to a SCSI READ command from the USB host.  After doing so, we must indicate whether the operation succeeded, and 
                // close the buffer operation by calling USBMSC_bufferProcessed().  
                while(RWbuf->operation == kUSBMSC_READ)
                {
                  RWbuf->returnCode = Read_LBA(RWbuf->lba, RWbuf->bufferAddr, RWbuf->lbCount); // Fetch a block from the medium, using file system emulation
                  USBMSC_bufferProcessed();                           // Close the buffer operation
                }
                
                // Same as above, except for WRITE.  If operation == kUSBMSC_WRITE, then the API is waiting for us to 
                // process the buffer by writing the contents to the storage volume.  
                while(RWbuf->operation == kUSBMSC_WRITE)
                {
                  RWbuf->returnCode = Write_LBA(RWbuf->lba, RWbuf->bufferAddr, RWbuf->lbCount); // Write the block to the medium, using file system emulation
                  USBMSC_bufferProcessed();                            // Close the buffer operation
                }
                break;
                
            case ST_ENUM_SUSPENDED:
                 __bis_SR_register(LPM3_bits + GIE);            // Enter LPM3, until a resume or VBUS-off event
                 break;
                
            case ST_ENUM_IN_PROGRESS:
                 break;
                
            case ST_ERROR:
                 break;
                
            default:;
        }    
    }  // while(1)
} //main()