Beispiel #1
0
Datei: main.c Projekt: 21rcc/ioio
int main() {
  log_init();

  // If bootloader mode not requested, go immediately to app.
  if (!ShouldEnterBootloader()) {
    OscCalibrateCached();
    log_printf("Running app...");
    __asm__("goto __APP_RESET");
  }

  // We need to enter bootloader mode, wait for the boot pin to be released.
  while (!led_read());

  // Now we can start!
  led_init();
#ifdef SIGNAL_AFTER_BAD_RESET
  if (RCON & 0b1100001001000000) {
    SignalRcon();
  }
#endif

  log_printf("Hello from Bootloader!!!");
  if (IsPin1Grounded()) {
    log_printf("Erasing config.");
    EraseConfig();
  }
  OscCalibrateCached();
  Blink(5);
  USBInitialize();

  while (1) {
    // Wait for connection
    while (!(USBGetDeviceState() == CONFIGURED_STATE
      && CDCIsDtePresent())) USBTasks();

    log_printf("Connected!");
    BootProtocolInit();

    while (USBGetDeviceState() == CONFIGURED_STATE && CDCIsDtePresent()) {
      static char in_buf[64];
      USBTasks();

      BYTE size = getsUSBUSART(in_buf, sizeof(in_buf));
      if (!BootProtocolProcess(in_buf, size)) {
        log_printf("Protocol error. Will detach / re-attach.");
        USBSoftDetach();
        __delay_ms(2000);
        USBDeviceAttach();
        break;
      }
      BootProtocolTasks();
    }
    log_printf("Disconnected!");
  }
  return 0;
}
Beispiel #2
0
void ProcessIO( void )
{
    if ( ( USBGetDeviceState() < CONFIGURED_STATE ) || USBIsDeviceSuspended() )
        return;

    ServiceRequests();
}
Beispiel #3
0
/*********************************************************************
* Function: void SYSTEM_Tasks(void)
*
* Overview: Runs system level tasks that keep the system running
*
* PreCondition: System has been initalized with SYSTEM_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void SYSTEM_Tasks(void)
{
    switch(softStartStatus)
    {
        case SOFT_START_POWER_OFF:
            break;

        case SOFT_START_POWER_START:
            if(USBGetDeviceState() != CONFIGURED_STATE)
            {
                break;
            }

            AppPowerEnable();
            softStartStatus = SOFT_START_POWER_ENABLED;
            break;

        case SOFT_START_POWER_ENABLED:
            if(AppPowerReady() == true)
            {
                softStartStatus = SOFT_START_POWER_READY;
                LED_Enable(LED_USB_DEVICE_STATE);
            }
            break;

        case SOFT_START_POWER_READY:
            break;
    }
}
Beispiel #4
0
void usb_tty_task(void *pvParameters){
    unsigned long tempo = 0;

    stack_uso_usb = uxTaskGetStackHighWaterMark( NULL );

    sinal_inicializado++;

    while(1){

        if ((TickGet() - tempo) >= (TICK_SECOND / 64)) {
            tempo = TickGet();
            usb_tty_status();

        }

        #if defined(USB_INTERRUPT)
            if (USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE)){
                USBDeviceAttach();
            }
        #endif

        usb_tty_loop();

        stack_uso_usb = uxTaskGetStackHighWaterMark( NULL );
    }
}
Beispiel #5
0
int main(void) {
    InitializeSystem();
    initADCDMA();

    
    #if defined(USB_INTERRUPT)
        if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE))
        {
            USBDeviceAttach();
        }
    #endif

    #if defined(USB_POLLING)
            // Check bus status and service USB interrupts.
            USBDeviceTasks();
    #endif
    while(1)
    {
        if (!ADC_DATA_READY)
            continue;
                
        ADC_DATA_READY = 0;
        
        RunFFT();

        putrsUSBUSART((char*)&fftOut[0].real);
        
        ProcessIO();
    }
    return (EXIT_SUCCESS);
}
Beispiel #6
0
// *--------------------------------------------------------------------------------*
int main(){
	
    mJTAGPortEnable(0);							// JTAG des-habilitado
	SYSTEMConfigPerformance(GetSystemClock()); 	// Activa pre-cache.-
	
	AD1PCFG = 0xFFFF;
	LED1_OUTPUT();
	LED2_OUTPUT();
	SW1_INPUT();
	SW2_INPUT();
	
	buttonCount = 0;
    buttonPressed = FALSE;
    stringPrinted = TRUE;
	
	USBDeviceInit();	
	while(1){
		#if defined(USB_INTERRUPT)
		if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE)){
			USBDeviceAttach();
		}
		#endif
		#if defined(USB_POLLING)
			// Check bus status and service USB interrupts.
			USBDeviceTasks();
		#endif
		ProcessIO();
	}
}
Beispiel #7
0
void main(void) {
    InitializeSystem();

    while (1) {
        // Comprueba el terminal que indica la conexión USB al inicio o al reset
        if (PORTBbits.RB4 == 1) {
            // Si no se ha activado el USB, lo activa
            if ((USBGetDeviceState() == DETACHED_STATE)) {
                USBDeviceAttach();
            } else {
                // Si ya se ha activado, realiza las tareas USB
                // USB Tasks
                blinkUSBStatus();
                processUSBData();
            }
        } else {
            // Si no está conectado el terminal USB, entra en modo de bajo consumo
            USBDeviceDetach();
            LATCbits.LATC0 = 0;
            OSCCONbits.IDLEN = 0;
            Sleep();
            Nop();
        }
    }//end while
}//end main
Beispiel #8
0
/*********************************************************************
* Function: void SYSTEM_Tasks(void)
*
* Overview: Runs system level tasks that keep the system running
*
* PreCondition: System has been initalized with SYSTEM_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void SYSTEM_Tasks(void)
{
    switch(softStartStatus)
    {
        case SOFT_START_POWER_OFF:
            break;

        case SOFT_START_POWER_START:
            if(USBGetDeviceState() != CONFIGURED_STATE)
            {
                break;
            }
            
            AppPowerEnable();
            softStartStatus = SOFT_START_POWER_ENABLED;
            break;

        case SOFT_START_POWER_ENABLED:
            if(AppPowerReady() == true)
            {
                softStartStatus = SOFT_START_POWER_READY;
                LED_Enable(LED_USB_DEVICE_STATE);
                LED_Enable(LED_USB_DEVICE_HID_CUSTOM);
				
                ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
                ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
            }
            break;
            
        case SOFT_START_POWER_READY:
            break;
    }
}
Beispiel #9
0
MAIN_RETURN main(void)
{
    SYSTEM_Initialize(SYSTEM_STATE_USB_START);

    USBDeviceInit();
    USBDeviceAttach();

    IPR1 = 0;   //All others interrupt sources will be Low priority
    IPR2 = 32; //USB interrupt is High priority
    RCONbits.IPEN = 1;  //Enabling interrupt priority
    ADCON1bits.PCFG = 0x0F; //By default all I/O digital
    CMCONbits.CM = 7; //Comparators off by default

    while(1)
    {
        SYSTEM_Tasks();

        #if defined(USB_POLLING)
            // Interrupt or polling method.  If using polling, must call
            // this function periodically.  This function will take care
            // of processing and responding to SETUP transactions
            // (such as during the enumeration process when you first
            // plug in).  USB hosts require that USB devices should accept
            // and process SETUP packets in a timely fashion.  Therefore,
            // when using polling, this function should be called
            // regularly (such as once every 1.8ms or faster** [see
            // inline code comments in usb_device.c for explanation when
            // "or faster" applies])  In most cases, the USBDeviceTasks()
            // function does not take very long to execute (ex: <100
            // instruction cycles) before it returns.
            USBDeviceTasks();
        #endif

        /* If the USB device isn't configured yet, we can't really do anything
         * else since we don't have a host to talk to.  So jump back to the
         * top of the while loop. */
        if( USBGetDeviceState() < CONFIGURED_STATE )
        {
            /* Jump back to the top of the while loop. */
            continue;
        }

        /* If we are currently suspended, then we need to see if we need to
         * issue a remote wakeup.  In either case, we shouldn't process any
         * keyboard commands since we aren't currently communicating to the host
         * thus just continue back to the start of the while loop. */
        if( USBIsDeviceSuspended() == true )
        {
            /* Jump back to the top of the while loop. */
            continue;
        }

        //Application specific tasks
        APP_DeviceCustomHIDTasks();

    }//end while
}//end main
Beispiel #10
0
/********************************************************************
 * Function:        void main(void)
 *******************************************************************/
MAIN_RETURN main(void)
{
    SYSTEM_Initialize();

    USBDeviceInit();
    USBDeviceAttach();

    while(1)
    {
        SYSTEM_Tasks();

        #if defined(USB_POLLING)
            USBDeviceTasks();
        #endif

        /* If the USB device isn't configured yet, we can't really do anything
         * else since we don't have a host to talk to.  So jump back to the
         * top of the while loop. */
        if( USBGetDeviceState() < CONFIGURED_STATE )
        {
            /* Jump back to the top of the while loop. */
            continue;
        }

        /* If we are currently suspended, then we need to see if we need to
         * issue a remote wakeup.  In either case, we shouldn't process any
         * keyboard commands since we aren't currently communicating to the host
         * thus just continue back to the start of the while loop. */
        if( USBIsDeviceSuspended() == true )
        {
            /* Jump back to the top of the while loop. */
            continue;
        }
        // implement nMCLR button
        if ( BUTTON_IsPressed(BUTTON_S1)) {
            LUNSoftDetach(0);       // mark the media as temporarily unavailable 
            ICSP_nMCLR = SLAVE_RESET;
            LED_Off(GREEN_LED);     // turn off RED LED to indicate ready for download
            LED_On (RED_LED);
            DIRECT_Initialize();    // reset the programming state machine
        }
        else { // simply act as a slave reset 
            LUNSoftAttach(0);                       // mark the media as available
            if ( !DIRECT_ProgrammingInProgress()) {  // do not release during prog.!
                ICSP_nMCLR = SLAVE_RUN;
                LED_On(GREEN_LED);   // turn off RED LED to indicate ready for download
                LED_Off(RED_LED);
            }
        }

        //Application specific tasks
        APP_DeviceMSDTasks();
        APP_DeviceCDCEmulatorTasks();

    }//end while
}//end main
Beispiel #11
0
/**
 * update LED status
 */
void BlinkUSBStatus(void) {

    #define BLINK_COUNT (0xffff/16)

    static UINT16 led_count = 0xffff;
    static USB_DEVICE_STATE lastState = DETACHED_STATE;
    static BOOL blinkConfiguredSequence = FALSE;

    led_count++;
    
    if (USBSuspendControl == 1) {
        LED_Off();
    } else {
        if (USBGetDeviceState() < CONFIGURED_STATE) {
            if (blinkConfiguredSequence) {
                blinkConfiguredSequence = FALSE;
            }

            if (lastState == CONFIGURED_STATE) {
                ReceiverOff();
            }

            if (led_count == 0) {
                LED_On();
            } else if (led_count == BLINK_COUNT) {
                LED_Off();
            }
        } else {
            if (lastState != CONFIGURED_STATE) {
                QueueInit();
                ReceiverOn();
                LED_On();
                blinkConfiguredSequence = TRUE;
                led_count = 0;
            } else if (blinkConfiguredSequence && led_count == 0) {
                blinkConfiguredSequence = FALSE;
                LED_Off();
            }
        }
    }

    lastState = USBGetDeviceState();
}
Beispiel #12
0
static void CDCTasks() {
  DWORD size;

  if (channel_state > CHANNEL_DETACHED
      && USBGetDeviceState() == DETACHED_STATE) {
    // handle detach
    if (channel_state >= CHANNEL_OPEN) {
      callback(NULL, 1, callback_arg);
    }
    channel_state = CHANNEL_DETACHED;
  } else if (channel_state > CHANNEL_WAIT_DTE
      && !CDCIsDtePresent()) {
    // handle close
    if (channel_state >= CHANNEL_OPEN) {
      callback(NULL, 0, callback_arg);
    }
    channel_state = CHANNEL_WAIT_DTE;
  }

  switch (channel_state) {
    case CHANNEL_DETACHED:
      if (USBGetDeviceState() == CONFIGURED_STATE) {
        channel_state = CHANNEL_WAIT_DTE;
      }
      break;

    case CHANNEL_WAIT_DTE:
      if (CDCIsDtePresent()) {
        channel_state = CHANNEL_WAIT_OPEN;
      }
      break;

    case CHANNEL_WAIT_OPEN:
      break;

    case CHANNEL_OPEN:
      size = getsUSBUSART(rx_buf, rx_buf_size);
      if (size) {
        callback(rx_buf, size, callback_arg);
      }
      break;
  }
}
Beispiel #13
0
void USB_CDC_task(void) {
#if defined(USB_POLLING)
    // Interrupt or polling method.  If using polling, must call
    // this function periodically.  This function will take care
    // of processing and responding to SETUP transactions
    // (such as during the enumeration process when you first
    // plug in).  USB hosts require that USB devices should accept
    // and process SETUP packets in a timely fashion.  Therefore,
    // when using polling, this function should be called
    // regularly (such as once every 1.8ms or faster** [see
    // inline code comments in usb_device.c for explanation when
    // "or faster" applies])  In most cases, the USBDeviceTasks()
    // function does not take very long to execute (ex: <100
    // instruction cycles) before it returns.
    USBDeviceTasks();
#endif


    /* If the USB device isn't configured yet, we can't really do anything
     * else since we don't have a host to talk to.  So jump back to the
     * top of the while loop. */
    if (USBGetDeviceState() < CONFIGURED_STATE) {
        /* Jump back to the top of the while loop. */
        return;
    }

    /* If we are currently suspended, then we need to see if we need to
     * issue a remote wakeup.  In either case, we shouldn't process any
     * keyboard commands since we aren't currently communicating to the host
     * thus just continue back to the start of the while loop. */
    if (USBIsDeviceSuspended() == true) {
        /* Jump back to the top of the while loop. */
        return;
    }

    // Tx task
    uint16_t length = 0;
    while (ringbuf_num(&usb_tx)) {
        writeBuffer[length++] = ringbuf_pop(&usb_tx);
        if (length >= CDC_DATA_IN_EP_SIZE) {
            break;
        }
    }
    if (length) {
        USB_CDC_send(length);
    }
    // Rx task
    length = USB_CDC_get();
    if (length) {
        for (uint16_t i = 0; i < length; i++) {
            ringbuf_put(&usb_rx, readBuffer[i]);
        }
    }
}
Beispiel #14
0
void APP_LEDUpdateUSBStatus(void)
{
    static uint16_t ledCount = 0;

    if(USBIsDeviceSuspended() == true)
    {
        LED_Off(LED_USB_DEVICE_STATE);
        return;
    }

    switch(USBGetDeviceState())
    {         
        case CONFIGURED_STATE:
            /* We are configured.  Blink fast.
             * On for 75ms, off for 75ms, then reset/repeat. */
            if(ledCount == 1)
            {
                LED_On(LED_USB_DEVICE_STATE);
            }
            else if(ledCount == 75)
            {
                LED_Off(LED_USB_DEVICE_STATE);
            }
            else if(ledCount > 150)
            {
                ledCount = 0;
            }
            break;

        default:
            /* We aren't configured yet, but we aren't suspended so let's blink with
             * a slow pulse. On for 50ms, then off for 950ms, then reset/repeat. */
            if(ledCount == 1)
            {
                LED_On(LED_USB_DEVICE_STATE);
            }
            else if(ledCount == 50)
            {
                LED_Off(LED_USB_DEVICE_STATE);
            }
            else if(ledCount > 950)
            {
                ledCount = 0;
            }
            break;
    }

    /* Increment the millisecond counter. */
    ledCount++;
}
Beispiel #15
0
Datei: main.c Projekt: 21rcc/ioio
// Calibrate the oscillar according to the SOF clock coming from a USB host.
// This function will first block until a USB connection has been established.
// Then it will wait for 32 SOF's for the tuning process (will hang if they do
// not arrive!). Then, if will disconnect from the USB bus and wait 2 seconds.
// Upon exit, the _TUN register will hold the correct value.
static void OscCalibrate() {
  int i;

  led_init();
  USBInitialize();

  // Start timer2/3 as 32-bit, system clock (16MHz).
  T2CON = 0x0008;
  PR2 = PR3 = 0xFFFF;
  T2CON = 0x8008;

  // Wait for a USB connection. Blink meanwhile.
  int led_counter = 0;
  while (USBGetDeviceState() != POWERED_STATE) {
    USBTasks();
    if ((led_counter++ & 0x3FFF) == 0) led_toggle();
  }
  led_off();

  log_printf("Connected to host. Starting calibration.");

  // Start from 0 (redundant, but better be explicit).
  _TUN = 0;

  for (i = 0; i < 32; ++i) {
    uint32_t duration;
    // Repeat for sanity: if for some reason the SOF is too long or too short,
    // ignore it.
    do {
      duration = MeasureSOF();
    } while (duration < 15000 || duration > 17000);

    if (duration < 16000 && _TUN != 31) {
      // We're running too slow.
      _TUN++;
    } else if (duration > 16000 && _TUN != 32) {
      // We're running too fast.
      _TUN--;
    }
  }
  log_printf("Duration: %lu, TUN=%d", MeasureSOF(), _TUN);

  // Undo side-effects.
  T2CON = 0x0000;

  // Detach, wait.
  USBShutdown();
  __delay_ms(2000);
}
Beispiel #16
0
int main(void)
#endif
{   
    InitializeSystem();

    while(1) {
        #if defined(USB_INTERRUPT)
            if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE)) {
                USBDeviceAttach();
            }
        #endif

        #if defined(USB_POLLING)
        USBDeviceTasks();
        #endif

        ProcessIO();
    }
}
Beispiel #17
0
/******************************************************************************
 * Function:        void BlinkUSBStatus(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        BlinkUSBStatus turns on and off LEDs corresponding to
 *                  the USB device state.
 *
 * Note:            mLED macros can be found in HardwareProfile.h
 *                  usb_device_state is declared in usbmmap.c and is modified
 *                  in usb_device.c, usbctrltrf.c, and usb9.c
 *****************************************************************************/
void BlinkUSBStatus(void)
{
    #ifdef ENABLE_USB_LED_BLINK_STATUS
        static unsigned int led_count = 0;

        led_count--;
        if(led_count == 0)
        {
            led_count = 0x4E00;     //Value determines blink interval
            if(USBGetDeviceState() < CONFIGURED_STATE)
            {
                mLED1 = 1;          //Turn on the LED continuously
            }
            else
            {
                mLED1 = !mLED1;     //Toggle the LED state
            }
        }
    #endif //#ifdef ENABLE_USB_LED_BLINK_STATUS
}//end BlinkUSBStatus
Beispiel #18
0
void usb_send(const char *format, ...)
{
    //char *usb_msg;
    static unsigned char usb_msg[CDC_DATA_OUT_EP_SIZE];

    va_list args;
    va_start(args,__format);
    sprintf(usb_msg,format,args);
    if (( USBGetDeviceState() < CONFIGURED_STATE ) || ( USBIsDeviceSuspended() == true ))
    {
        return;
    }
    else
    {
        if (mUSBUSARTIsTxTrfReady())
        {
            putUSBUSART(usb_msg,strlen(usb_msg));
        }
        CDCTxService();
    }

}
Beispiel #19
0
int main(void)
#endif
{   
    unsigned int i=0;
    InitializeSystem();
    for(i=0;i<SAMPLE_SIZE;i++)ADC_sample[i]=0;
    while(1)
    {
        #if defined(USB_INTERRUPT)
            if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE))
            {
                USBDeviceAttach();
            }
        #endif

   				  

		// Application-specific tasks.
		// Application related code may be added here, or in the ProcessIO() function.
    //ReadADC();
    ProcessIO();
    }//end while
}//end main
/*********************************************************************
* Function: void SYSTEM_Tasks(void)
*
* Overview: Runs system level tasks that keep the system running
*
* PreCondition: System has been initalized with SYSTEM_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void SYSTEM_Tasks(void)
{
    switch(softStartStatus)
    {
        case SOFT_START_POWER_OFF:
            break;

        case SOFT_START_POWER_START:
            if(USBGetDeviceState() != CONFIGURED_STATE)
            {
                break;
            }

            softStartStatus = SOFT_START_POWER_ENABLED;
            break;

        case SOFT_START_POWER_ENABLED:
            break;

        case SOFT_START_POWER_READY:
            break;
    }
}
Beispiel #21
0
int main(void)
#endif
{   
    InitializeSystem();

    while(1)
    {
        #if defined(USB_INTERRUPT)
            if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE))
            {
                USBDeviceAttach();
            }
        #endif

        #if defined(USB_POLLING)
		// Check bus status and service USB interrupts.
        USBDeviceTasks(); // Interrupt or polling method.  If using polling, must call
        				  // this function periodically.  This function will take care
        				  // of processing and responding to SETUP transactions 
        				  // (such as during the enumeration process when you first
        				  // plug in).  USB hosts require that USB devices should accept
        				  // and process SETUP packets in a timely fashion.  Therefore,
        				  // when using polling, this function should be called 
        				  // frequently (such as once about every 100 microseconds) at any
        				  // time that a SETUP packet might reasonably be expected to
        				  // be sent by the host to your device.  In most cases, the
        				  // USBDeviceTasks() function does not take very long to
        				  // execute (~50 instruction cycles) before it returns.
        #endif
    				  

		// Application-specific tasks.
		// Application related code may be added here, or in the ProcessIO() function.
        ProcessIO();        
    }//end while
}//end main
Beispiel #22
0
int CDCIsAvailable() {
  return USBGetDeviceState() != DETACHED_STATE;
}
Beispiel #23
0
int main(void)
{
    SYSTEM_Initialize(SYSTEM_STATE_USB_START);
    LED_Initialize();
    APP_KeyboardConfigure();

#ifdef WITH_HOS
    HosCheckDFU(BOOT_FLAGS_VALUE & BOOT_WITH_APP);
    if (!isUSBMode() || !isBusPowered()) {
        HosMainLoop();
    }
    for (uint16_t i = 0; i < HOS_STARTUP_DELAY; ++i) {
        if (HosSleep(HOS_TYPE_DEFAULT)) {
            break;
        }
        __delay_ms(4);
    }
#endif

    USBDeviceInit();
    USBDeviceAttach();

    for (;;)
    {
#ifdef WITH_HOS
        if (!isBusPowered() || !isUSBMode()) {
            Reset();
            Nop();
            Nop();
            // NOT REACHED HERE
        }
#endif

        SYSTEM_Tasks();

#if defined(USB_POLLING)
        /* Check bus status and service USB interrupts.  Interrupt or polling
         * method.  If using polling, must call this function periodically.
         * This function will take care of processing and responding to SETUP
         * transactions (such as during the enumeration process when you first
         * plug in).  USB hosts require that USB devices should accept and
         * process SETUP packets in a timely fashion.  Therefore, when using
         * polling, this function should be called regularly (such as once every
         * 1.8ms or faster** [see inline code comments in usb_device.c for
         * explanation when "or faster" applies])  In most cases, the
         * USBDeviceTasks() function does not take very long to execute
         * (ex: <100 instruction cycles) before it returns. */
        USBDeviceTasks();
#endif

        APP_LEDUpdateUSBStatus();

        /* If the USB device isn't configured yet, we can't really do anything
         * else since we don't have a host to talk to.  So jump back to the
         * top of the while loop. */
        if (USBGetDeviceState() < CONFIGURED_STATE)
        {
            /* Jump back to the top of the while loop. */
            continue;
        }

        /* If we are currently suspended, then we need to see if we need to
         * issue a remote wakeup.  In either case, we shouldn't process any
         * keyboard commands since we aren't currently communicating to the host
         * thus just continue back to the start of the while loop. */
        if (USBIsDeviceSuspended())
        {
            //Check if we should assert a remote wakeup request to the USB host,
            //when the user presses the pushbutton.
            if (BUTTON_IsPressed())
            {
                USBCBSendResume();  //Does nothing unless we are in USB suspend with remote wakeup armed.
            }

            /* Jump back to the top of the while loop. */
            continue;
        }

        if (USBIsBusSuspended())
        {
            /* Jump back to the top of the while loop. */
            continue;
        }

        /* Run the keyboard tasks. */
        APP_KeyboardTasks();
    }//end while
}//end main
/*********************************************************************
* Function: void APP_DeviceAudioMIDITasks(void);
*
* Overview: Keeps the Custom HID demo running.
*
* PreCondition: The demo should have been initialized and started via
*   the APP_DeviceAudioMIDIInitialize() and APP_DeviceAudioMIDIStart() demos
*   respectively.
*
* Input: None
*
* Output: None
*
********************************************************************/
void APP_DeviceAudioMIDITasks()
{
    /* If the device is not configured yet, or the device is suspended, then
     * we don't need to run the demo since we can't send any data.
     */
    if( (USBGetDeviceState() < CONFIGURED_STATE) ||
        (USBIsDeviceSuspended() == true))
    {
        return;
    }

    if(!USBHandleBusy(USBRxHandle))
    {
        //We have received a MIDI packet from the host, process it and then
        //  prepare to receive the next packet

        //INSERT MIDI PROCESSING CODE HERE

        //Get ready for next packet (this will overwrite the old data)
        USBRxHandle = USBRxOnePacket(USB_DEVICE_AUDIO_MIDI_ENDPOINT,(uint8_t*)&ReceivedDataBuffer,64);
    }

    /* If the user button is pressed... */
    if(BUTTON_IsPressed(BUTTON_DEVICE_AUDIO_MIDI) == true)
    {
        /* and we haven't sent a transmission in the past 100ms... */
        if(msCounter == 0)
        {
            /* and we have sent the NOTE_OFF for the last note... */
            if(sentNoteOff == true)
            {
                /* and we aren't currently trying to transmit data... */
                if(!USBHandleBusy(USBTxHandle))
                {
                    //Then reset the 100ms counter
                    msCounter = 100;

                    midiData.Val = 0;   //must set all unused values to 0 so go ahead
                                        //  and set them all to 0

                    midiData.CableNumber = 0;
                    midiData.CodeIndexNumber = MIDI_CIN_NOTE_ON;
                    midiData.DATA_0 = 0x90;         //Note on
                    midiData.DATA_1 = pitch;         //pitch
                    midiData.DATA_2 = 0x7F;  //velocity

                    USBTxHandle = USBTxOnePacket(USB_DEVICE_AUDIO_MIDI_ENDPOINT,(uint8_t*)&midiData,4);

                    /* we now need to send the NOTE_OFF for this note. */
                    sentNoteOff = false;
                }
            }
        }
    }
    else
    {
        if(msCounter == 0)
        {
            if(sentNoteOff == false)
            {
                if(!USBHandleBusy(USBTxHandle))
                {
                    //Debounce counter for 100ms
                    msCounter = 100;

                    midiData.Val = 0;   //must set all unused values to 0 so go ahead
                                        //  and set them all to 0

                    midiData.CableNumber = 0;
                    midiData.CodeIndexNumber = MIDI_CIN_NOTE_ON;
                    midiData.DATA_0 = 0x90;     //Note off
                    midiData.DATA_1 = pitch++;     //pitch
                    midiData.DATA_2 = 0x00;        //velocity

                    if(pitch == 0x49)
                    {
                        pitch = 0x3C;
                    }

                    USBTxHandle = USBTxOnePacket(USB_DEVICE_AUDIO_MIDI_ENDPOINT,(uint8_t*)&midiData,4);
                    sentNoteOff = true;
                }
            }
        }
    }
}
Beispiel #25
0
void main() {
    InitializeSystem();


    red = FALSE;
    green = FALSE;

    #if defined(USB_INTERRUPT)
        USBDeviceAttach();
    #endif

    while (1){
         #if defined(USB_POLLING)
		// Check bus status and service USB interrupts.
        USBDeviceTasks(); // Interrupt or polling method.  If using polling, must call
        				  // this function periodically.  This function will take care
        				  // of processing and responding to SETUP transactions
        				  // (such as during the enumeration process when you first
        				  // plug in).  USB hosts require that USB devices should accept
        				  // and process SETUP packets in a timely fashion.  Therefore,
        				  // when using polling, this function should be called
        				  // regularly (such as once every 1.8ms or faster** [see
        				  // inline code comments in usb_device.c for explanation when
        				  // "or faster" applies])  In most cases, the USBDeviceTasks()
        				  // function does not take very long to execute (ex: <100
        				  // instruction cycles) before it returns.
        #endif
        Tran_String_UART(init);
        lcd_gotoxy(1,2);
        lcd_putstr(init);
        if((USBGetDeviceState() \< CONFIGURED_STATE) ||(USBIsDeviceSuspended() == TRUE))
            {
            #if defined USE_UART
               Tran_String_UART(error);

            #endif
            #if defined USE_LCD
               lcd_clear();
               lcd_gotoxy(3,1);
               lcd_putstr(error);
            #endif
                //Either the device is not configured or we are suspended
                //  so we don't want to do execute any application code
                continue;   //go back to the top of the while loop
            }
            else

            #if defined USE_UART
                Tran_String_UART(success);

            #endif
            #if defined USE_LCD
                lcd_clear();
                lcd_gotoxy(3,1);
                lcd_putstr(success);
            #endif
//            if(!HIDRxHandleBusy(USBOutHandle))
//            {
//                if (outbuffer[0] == 0) {
//                    if(!HIDTxHandleBusy(USBInHandle))
//                    {
//                        inbuffer[0] = green;
//                        inbuffer[1] = red;
//                        USBInHandle = HIDTxPacket(HID_EP,(BYTE*)&inbuffer[0], HID_IN_SIZE);
//                    }
//                }
//                if (outbuffer[0] == 1) {
//                    if (outbuffer[1] == 1) green = TRUE; else green = FALSE;
//                    if (outbuffer[2] == 1) red = TRUE; else red = FALSE;
//                    if (green) LATCbits.LATC6 = 1; else LATCbits.LATC6 = 0;
//                    if (red) LATCbits.LATC7 = 1; else LATCbits.LATC7 = 0;
//                }
//                if(outbuffer[0]==2){
//                    LATCbits.LATC6=0;
//                    LATCbits.L4ATC7=0;
//                }
//                USBOutHandle = HIDRxPacket(HID_EP, (BYTE*)&outbuffer, HID_OUT_SIZE);
//            } 
    }
}
Beispiel #26
0
bool is_usb_available(void) {
    return !(USBGetDeviceState() < CONFIGURED_STATE || USBIsDeviceSuspended() == true);
}
/********************************************************************
* Function: 	UsbTasks()
*
* Precondition: 
*
* Input: 		None.
*
* Output:		None.
*
* Side Effects:	None.
*
* Overview: 	This function transmits frames and received frames to and from USB.
*
*			
* Note:		 	None.
********************************************************************/	
void UsbTasks(void)
{
	UINT TxLen;
	UINT8 *TxPtr;
	volatile test;
	
	
	 #if defined(USB_POLLING)		
	//This function must be called everytime. This is a stack function.
	USBDeviceTasks();
	 #endif

    if(USBGetDeviceState() == CONFIGURED_STATE)
	{
    	// Check if bootloader has something to send out to PC. 
    	TxLen = FRAMEWORK_GetTransmitFrame(UsbTxData);
    
    	// Initialize the transmit pointer.
    	TxPtr = &UsbTxData[0];
    	
    	while(TxLen)	
    	{
    	
    		while(UsbTxBusy()); // Wait for USB transmit completion.	
    		
    		// Send the packet (USB endpoint size is always 64 bytes)
    		USBTxOnePacket(HID_EP, TxPtr, MaxUsbPacketSize);	
    		
    		if(TxLen > MaxUsbPacketSize)
    		{
    			// Send pending bytes in next loop.
    			TxLen -= MaxUsbPacketSize;
    			// Point to next 64bytes.
    			TxPtr += MaxUsbPacketSize;
    			// Probably a wait is needed here, otherwise PC app may miss frames.
    			//Wait();			
    		}	
    		else
    		{
    			// No more bytes.
    			TxLen = 0;
    		}			
    	}
    	
    	// Following part of the code checks if there is any data from USB.
    	// If there are any data available, it just pushes the data to the frame work. 
    	// Framework decodes the packet and takes necessary action like erasing/ programming etc.	
    		
    	if(UsbRxDataAvlbl())// Check if we have got any data from USB.	 		
        {
    	    // Yes, we got a packet from HID End point.	    
    	    // Pass the buffer to frame work. Framework decodes the packet and executes the Bootloder specific commands (Erasing/Programming etc).
    		FRAMEWORK_BuildRxFrame(UsbRxData, MaxUsbPacketSize);
    	    	    
    	    // Re-arm the HID endpoint to receive next packet.(Remember! We have armed the HID endpoint for the first time in function USBCBInitEP())
    	    USBOutHandle = HIDRxPacket(HID_EP,(BYTE*)UsbRxData,MaxUsbPacketSize);	    	    		
    	}
    
    }// if device configured.   
       	
	
}	
USB_DEVICE_STATE ChipKITUSBGetDeviceState(void)
{
	return(USBGetDeviceState());
}
Beispiel #29
0
// Attached to USB
void RunAttached(void)
{
	// Do this first to give the card time to start up
	SD_ENABLE(); 		// Turn on SD card

    // Enable peripherals
	RtcInterruptOn(0);  // Keeps time upto date

	LED_SET(LED_WHITE);
    CLOCK_PLL();		// PLL clock

    // Initialize sensors
    // Check if we have an accelerometer
    AccelVerifyDeviceId();
    // Check if we have a gyro
	#ifdef USE_GYRO 
    GyroVerifyDeviceId();
	#endif
	#ifdef HAS_PROX
	// Check for prox
	ProxVerifyDeviceId();
	ProxStartup();
	#endif

    // Initialize sensors
    AccelStartup(ACCEL_RANGE_4G|ACCEL_RATE_100);
	#ifdef USE_GYRO 
	GyroStartup();
	#endif
	AdcInit();

	#ifndef NO_DISPLAY
	DisplayClear();
	Display_print_xy(" <= USB =>",0,2,2);
	#endif
	
	status.diskMounted = (status.lockCode == 0x0000) ? 1 : 0;
	status.stream = 0;

//   MDD_MediaInitialize();  // KL FIX: The SD card is re-inited in the usb framework which causes a lockup in some cases

	// Power up module if off
	PMD4bits.USB1MD = 0;

    USBInitializeSystem(); 	// Initializes buffer, USB module SFRs and firmware
    #ifdef USB_INTERRUPT
    USBDeviceAttach();
    #endif

    while(USB_BUS_SENSE && restart != 1)
    {
        // Check bus status and service USB interrupts.
        #ifndef USB_INTERRUPT
        USBDeviceTasks(); 	// Interrupt or polling method.  If using polling, must call
        #endif
        USBProcessIO();

        if ((USBGetDeviceState() >= CONFIGURED_STATE) && (USBIsDeviceSuspended() == FALSE))
        {
            const char *line = _user_gets();
            status.attached = 1;
            if (line != NULL)
            {
                status.stream = 0;  // Disable streaming
                SettingsCommand(line, SETTINGS_USB);
            }
        }
        else
        {
            status.attached = -1;
        }
	
        TimedTasks();	


        // Stream accelerometer data
        if (status.stream)
		{
			#define STREAM_RATE 10
			#define STREAM_INTERVAL (0x10000UL / STREAM_RATE)
			static unsigned long lastSampleTicks = 0;
            unsigned long now = RtcTicks();
            if (lastSampleTicks == 0) { lastSampleTicks = now; }
            if (now - lastSampleTicks > STREAM_INTERVAL)
            {
                accel_t accelSample;
				#ifdef USE_GYRO 
				gyro_t gyroSample;
				#endif

				extern unsigned char scratchBuffer[];
				char * ptr = (char *)scratchBuffer;
				unsigned short len;

                lastSampleTicks += STREAM_INTERVAL;
                if (now - lastSampleTicks > 2 * STREAM_INTERVAL) { lastSampleTicks = now; } // not keeping up with sample rate
                
#ifdef HAS_PROX
				// Sample sensors
				if(ProxSampleReady())
				{
					ProxReadSample();
					ProxStartSample();
				}
#endif
                AccelSingleSample(&accelSample);
				#ifdef USE_GYRO
				GyroSingleSample(&gyroSample);
				#endif
			
				// Write ascii to scratch buffer
				ptr = (char *)scratchBuffer;
				ptr += sprintf(ptr, "\f$ACCEL=%d,%d,%d\r\n", accelSample.x, accelSample.y, accelSample.z);
				#ifdef USE_GYRO 
				ptr += sprintf(ptr, "$GYRO=%d,%d,%d\r\n", gyroSample.x, gyroSample.y, gyroSample.z);
				#endif
				#ifdef HAS_PROX
				ptr += sprintf(ptr, "$PROX=%d\r\n", prox.proximity);
				ptr += sprintf(ptr, "$LIGHT=%d\r\n", prox.light);
				#endif
				len = (unsigned short)((void*)ptr - (void*)scratchBuffer);

				// Stream over USB
				if ((status.stream) && status.attached == 1) { usb_write(scratchBuffer, len); }
            }
        }
    }
	#if defined(USB_INTERRUPT)
    USBDeviceDetach();
	#endif
    status.attached = -1;

    return;
}