Exemple #1
0
/********************************************************************
 * Function:        void main(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Main program entry point.
 *
 * Note:            None
 *******************************************************************/
MAIN_RETURN main(void)
{
    SYSTEM_Initialize(SYSTEM_STATE_USB_START);

    USBDeviceInit();
    USBDeviceAttach();
    setup();

    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

        //Application specific tasks
        APP_DeviceCDCBasicDemoTasks();

    }//end while
}//end main
BOOL	InitApp( HWND hWnd )
{
	srand((unsigned int)time(NULL));

	//	IEXシステム初期化
	IEX_Initialize( hWnd, bFullScreen, ScreenMode );
	IEX_InitAudio();
	IEX_InitInput();

	// テキスト初期化
	Text::Init();

	//静的Debug関連
	Debug::Init();

	// キーボード入力初期化
	OKB_Init();


	// ナンバー初期化
	Number::Init();


	//	システムの初期化
	SYSTEM_Initialize();
	//	メインフレームワーク生成
	MainFrame = new Framework();
	//	初期シーン登録
	//MainFrame->ChangeScene( new TitleScene() );
	//MainFrame->ChangeScene( new sceneMain() );
	MainFrame->ChangeScene(new SceneMainServer());

	return TRUE;
}
Exemple #3
0
/*
                         Main application
 */
void main(void)
{
    // initialize the device
    SYSTEM_Initialize();

    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    //INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();

    while (1)
    {
        // Add your application code
        IO_RA1_SetHigh();
        __delay_ms(100);
        IO_RA1_SetLow();
        __delay_ms(100);
        
    }
}
Exemple #4
0
void main(void)
{
    int i;
    
    // initialize the device
    SYSTEM_Initialize();
    OLED_Initialize();

    while (1)
    {
        OLED_PutPicture( logo);
        __delay_ms( 2000);
        OLED_Command( SSD1306_INVERTDISPLAY);
        __delay_ms( 2000);
        OLED_Command( SSD1306_NORMALDISPLAY);
        __delay_ms( 2000);

       for( i=0xAF; i>0x00; i--){
            OLED_SetContrast( i);
            __delay_ms( 20);
       }
       for( i=0x00; i<0xAF; i++){
            OLED_SetContrast( i);
            __delay_ms( 20);
       }
    }
}
void main(void)
{
    /* Configure the oscillator for the device */
    //ConfigureOscillator();

    /* Initialize I/O and Peripherals for application */
   // InitApp();
    SYSTEM_Initialize();
    INTCONbits.GIE = 1;
    INTCONbits.PEIE = 1;
    LATA4 = 1;
    LATC0 = 0;
    LATC1 = 0;
    LATC2 = 0;
    
    
    
    while(1)
    {
        for(int x=1000;x>=100;x-=10){
            
           Beat((x/10),x);
        }
        for(int x=100;x<=1000;x+=10){
            
           Beat((x/10),x);
        }
    }

}
void main() {
    // Initialize the device
    SYSTEM_Initialize();
    
    ANSELAbits.ANSA0 = 0;
    TRISAbits.RA0 = 0;

    // If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts
    // If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global and Peripheral Interrupts
    // Use the following macros to:

    // Enable high priority global interrupts
    //INTERRUPT_GlobalInterruptHighEnable();

    // Enable low priority global interrupts.
    //INTERRUPT_GlobalInterruptLowEnable();

    // Disable high priority global interrupts
    //INTERRUPT_GlobalInterruptHighDisable();

    // Disable low priority global interrupts.
    //INTERRUPT_GlobalInterruptLowDisable();

    // Enable the Global Interrupts
//    INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
//    INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
//    INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
//    INTERRUPT_PeripheralInterruptDisable();
    
//    delay_25ms_n_times(20);
    
//    init_logic();
//    connect_to_peripherals();
//    audio_init();
    
    while (1) {
        
        LATAbits.LA0 = 1;
        delay_25ms_n_times(40);
        LATAbits.LA0 = 0;
        
        uint8_t i = 0;
        for (i; i < 8; i++) {
            LED_play_pattern(LED_ARMED + i);
        }
        __delay_ms (25);
        __delay_ms (25);
        __delay_ms (25);
        __delay_ms (25);
    }    
}
Exemple #7
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
Exemple #8
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
Exemple #9
0
void main(void)
{
    PIN_MANAGER_Initialize();
    SYSTEM_Initialize();
    OSCILLATOR_Initialize();
    SPI1_Initialize();
    
    while(1)
        listenForMaster();
}
Exemple #10
0
/*
                         Main application
 */
int main(void)
{
    // initialize the device
    SYSTEM_Initialize();

    while (1)
    {
        // Add your application code
    }

    return -1;
}
Exemple #11
0
/*
 * --------------------------------------------------
 *      Important Pins
 * --------------------------------------------------
 *  -- Debug LED    RA3
 *  -- JP10         RA7
 *  -- JP11         RE2
 *  -- JP12         RB5
 *  -- Rx1          RC7
 *  -- Tx1          RC6
 *  -- Rx2          RB7
 *  -- Tx2          RB6
 */
int main(int argc, char** argv) {
    TRISAbits.TRISA3=0;
    SYSTEM_Initialize();
    while(1)
    {
        EUSART1_Write(0x99);
        delay(500);
        LATAbits.LATA3=!LATAbits.LATA3;
        delay(500);
    }


    return (EXIT_SUCCESS);
}
Exemple #12
0
MAIN_RETURN main(void) {
    gpio_init();
    timer_init();
    SYSTEM_Initialize(SYSTEM_STATE_USB_START);
    USBDeviceInit();
    USBDeviceAttach();
    while (1) {
        SYSTEM_Tasks();
#if defined(USB_POLLING)
        USBDeviceTasks();
#endif
        //APP_DeviceCDCBasicDemoTasks();
        serial_update();
    }
}
Exemple #13
0
void main(void)
{
    SYSTEM_Initialize();
    INTERRUPT_GlobalInterruptEnable();
    INTERRUPT_PeripheralInterruptEnable();

    TMR0_Initialize();
    TMR0_SetInterruptHandler(tmr0_handler);

    EPWM1_Initialize();
    
    EUSART_Initialize();
    
    PROTOCOL_Initialize(DEVICE_ID, start_handler, stop_handler, set_handler);
    PROTOCOL_Loop();
}
Exemple #14
0
void main(void)
{
    // initialize the device
    SYSTEM_Initialize();
    INTERRUPT_GlobalInterruptEnable();
    INTERRUPT_PeripheralInterruptEnable();
    EUSART_Initialize();
    EPWM1_Initialize();

    uint16_t dutyValue;
    uint16_t angle;
    uint8_t c;
    uint8_t buf[32] = {'\0'};
    uint8_t cnt = 0;
    
    // read angle from EEPROM
    angle = (uint16_t)DATAEE_ReadByte(0);
    // printf("read angle from EEPROM: %d\n", angle);
    dutyValue = calc_duty(angle);
    EPWM1_LoadDutyValue(dutyValue);
            
    while (1)
    {
        __delay_ms(500);
        LATCbits.LATC4 ^= 1;

        do {
            c = EUSART_Read();
            if (c == '\n') {
                buf[cnt] = '\0';
                cnt = 0;
                if (strcmp(buf, "w") == 0) {
                    DATAEE_WriteByte(0, (uint8_t)angle);
                    // printf("write the last angle onto EEPROM: %d\n", angle);
                } else {
                    angle = atoi(buf);
                    dutyValue = calc_duty(angle);
                    EPWM1_LoadDutyValue(dutyValue);
                }
            } else {
                buf[cnt++] = c;
            }
        } while (EUSART_DataReady);

        CLRWDT();
    } 
}
Exemple #15
0
/********************************************************************
 * Function:        void main(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Main program entry point.
 *
 * Note:            None
 *******************************************************************/
MAIN_RETURN main(void)
{   
    SYSTEM_Initialize(SYSTEM_STATE_USB_HOST);

    //Initialize the stack
    USBHostInit(0);

    APP_HostHIDMouseInitialize();

    while(1)
    {
        USBHostTasks();
        USBHostHIDTasks();

        //Application specific tasks
        APP_HostHIDMouseTasks();
    }//end while
}//end main
Exemple #16
0
void setup()
{
    // load last used offset from eeprom
    preloadOffsetH = DATAEE_ReadByte(0);
    preloadOffsetL = DATAEE_ReadByte(1);
    preloadOffset = (preloadOffsetH << 8) 
                                    + preloadOffsetL;
    
    // call system setup
    SYSTEM_Initialize();
    
    preloadOffset = 0;
            
    // Enable interrupts!!
    INTCONbits.PEIE = 1;
    INTCONbits.GIE  = 1;
    
    toggle = true;
}
/**
 * @brief Main application
 */
void main()
{
    // initialize the device
    SYSTEM_Initialize();

    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();

    // Initialize Remote's program to start state
    
    // Connect to all peripherals
    connect_to_peripherals();
    
    // Flash indicator LEDs
//    indicatorLEDsPassed = btn_test_LEDs();
    
//    if (! (spellButtonsPassed & indicatorLEDsPassed) ) {
//         We have failed so bad if we get here...
//         Show failure
//    }
    
    // Indicate success or failure
    
    while (1)
    {

    }
}
Exemple #18
0
/****************************************************************************
 *
 *                        Main application
 *
****************************************************************************/
void main(void)
{
    unsigned long lc;   // file length
    MFILE* fp;          // file pointer
    unsigned int entry; // current piece

    // initialize the device
    SYSTEM_Initialize();

    // init File System
    LED0_LAT = 0;
    LED1_LAT = 0;

    while  (1)  // main loop
    {
        if ( mount() != 0)
        {
            LED0_LAT = 1;       // turn on LED0 if mount successful

            entry = 0;

            // look for a  W22 file
            while ( (fp = ffindM( "W22", &entry)) != NULL)
            {
                LED0_LAT = 0;       // turn off lED0 to save power
                LED1_LAT = 1;       // turn on LED1 if mount successful
                // wait for button press
                while( SW1_GetValue());
                // wait for button release
                while( !SW1_GetValue());
                LED1_LAT = 0;       // turn off LED1 to save power

                lc = InitWAV( fp);
                Play( fp, lc);
            } // while 
        }
        else
            LED0_LAT = 0;       // mounting error
    }
} // main
Exemple #19
0
BOOL InitApp(HINSTANCE hInstance, int nCmdShow)									// ゲーム起動時の最初の初期化 必要な初期化を全てここに
{
	if (GetAsyncKeyState(VK_CONTROL) & 0x8000) bFullScreen = TRUE;// Ctrlでフルスクリーン

	if (!tdnSystem::InitWindow(hInstance, nCmdShow, AppTitle, ScreenMode, bFullScreen))
	{
		MessageBox(0, "ウィンドウ初期化失敗。", "System", MB_OK);
	}
	
	//tdnSystem::InitD3D();
	tdnRenderState::Initialize();
	tdnTexture::Initialize();
	tdnText::Init();
	tdnInput::Initialize();
	
	//IEXのシステム関数を一時的採用、話し合いでSystem.hを抹消するか決める
	SYSTEM_Initialize();

	MainFrame = new Framework();			 // メインフレームワーク生成
	MainFrame->ChangeScene(new sceneMain()); // 初期シーン

	return TRUE;
}
Exemple #20
0
/*********************************************************************
 * Function: void APP_HostHIDKeyboardTasks(void);
 *
 * Overview: Keeps the demo running.
 *
 * PreCondition: The demo should have been initialized via
 *   the APP_HostHIDKeyboardInitialize()
 *
 * Input: None
 *
 * Output: None
 *
 ********************************************************************/
void APP_HostHIDKeyboardTasks() {
    uint8_t error;
    uint8_t count;

    if (!USBHostHID_ApiDeviceDetect()) {
        if (pickit.state != WAITING_FOR_DEVICE) {
            pickit.state = DEVICE_NOT_CONNECTED;
            
#ifdef DEBUG_MODE
            UART2PrintString("APP: PICkit Disconnected!\n");
#endif
            pickit.inUse = false;

            if (pickit.buffer != NULL) {
                free(pickit.buffer);
                pickit.buffer = NULL;
            }
        }
    }

    switch (pickit.state) {
        case DEVICE_NOT_CONNECTED:
            //PRINT_ClearScreen();
#ifdef DEBUG_MODE
            UART2PrintString("APP: Attach PICkit\n");
#endif            
            pickit.state = WAITING_FOR_DEVICE;
            IEC0bits.U1RXIE=0;
            LED_Off(LED_USB_HOST_HID_KEYBOARD_DEVICE_READY);
            break;

        case WAITING_FOR_DEVICE:
            if (USBHostHID_ApiDeviceDetect()) /* True if report descriptor is parsed with no error */ {
                //PRINT_ClearScreen();
                SYSTEM_Initialize(SYSTEM_STATE_USB_HOST_HID_KEYBOARD);
                LED_On(LED_USB_HOST_HID_KEYBOARD_DEVICE_READY);

                pickit.state = DEVICE_CONNECTED;
                    
                //timwuu 2015.12.31 change control right from timer3 to uart
                TIMER_RequestTick(&APP_HostHIDTimerHandler, 2);  //2ms

            }
            break;

        case DEVICE_CONNECTED:
            break;

        case GET_INPUT_REPORT:
                       
            if (USBHostHID_ApiGetReport(pickit.details.reportID,
                    pickit.details.interfaceNum,
                    pickit.size,
                    pickit.buffer
                    )
                    ) {
                /* Host may be busy/error -- keep trying */
#ifdef DEBUG_MODE
                    UART2PrintString("GET_INPUT_REPORT:BUSY\n");
#endif
            } else {
#ifdef DEBUG_MODE
                    UART2PrintString("GET_INPUT_REPORT:OK\n");
#endif                
                pickit.state = INPUT_REPORT_PENDING;
            }
            break;

        case INPUT_REPORT_PENDING:
            if (USBHostHID_ApiTransferIsComplete(&error, &count)) {
                if (error || (count == 0)) {
#ifdef DEBUG_MODE
                    if(error) UART2PrintString("INPUT_REPORT_PENDING:ERROR\n");
                    if(count==0) UART2PrintString("INPUT_REPORT_PENDING:ZERO\n");
#endif                                 
                    pickit.state = DEVICE_CONNECTED;
                } else {
#ifdef DEBUG_MODE
                    UART2PrintString("INPUT_REPORT_PENDING:OK\n");
#endif
                  
                    UART2PutHex(pickit.buffer[61]);
                    UART2PutHex(pickit.buffer[60]);
                    UART2PutChar(':');
                    
                    pickit.state = DEVICE_CONNECTED;
                    App_ProcessInputReport();
                }
            }
            break;

        case SEND_OUTPUT_REPORT: 
            
            //App_PrepareOutputReport();

            if (USBHostHID_ApiSendReport(pickit.details.reportID,
                    pickit.details.interfaceNum,
                    pickit.size,
                    (uint8_t *)cmdBuffer)) {
                    //pickit.buffer)) {
                /* Host may be busy/error -- keep trying */
#ifdef DEBUG_MODE
                    UART2PrintString("SEND_OUTPUT_REPORT:BUSY\n");
#endif

            } else {
#ifdef DEBUG_MODE
                    UART2PrintString("SEND_OUTPUT_REPORT:OK\n");
#endif
                UB_SetCmdBufferStateEmpty();
                pickit.state = OUTPUT_REPORT_PENDING;
            }
            break;

        case OUTPUT_REPORT_PENDING:
            //timijk 2016.01.13 Issue
            if (USBHostHID_ApiTransferIsComplete(&error, &count)) {
#ifdef DEBUG_MODE
                    UART2PrintString("OUTPUT_REPORT_PENDING\n");
#endif
                //?timwuu 2016.01.02  signal the device is ready for the next command
//                if(error) {
//                    UART2PutChar('*');
//                    UART2PutHex(error);
//                    LATBbits.LATB15 =1;
//                    pickit.state = SEND_OUTPUT_REPORT;  //resent the data
//                }
//                else
//                {
                    U1TXREG = 0x00; //LENGTH ZERO DATA
                    pickit.state = DEVICE_CONNECTED;
//                }
            }
                
            break;

        case ERROR_REPORTED:
            break;

        default:
            break;

    }
}
Exemple #21
0
/*
                         Main application
 */
int main(void) {
    // initialize the device
    SYSTEM_Initialize();
    uint16_t portValue;
    char introduction[]="Here are some messages from PIC. \r\n";
    char append[4][3];
    uint8_t appendCount = 0;
    uint8_t uartBuffer[128];
    uint8_t i = 0;
    char currentCountAscii[16];
    uint8_t sLength = 0;
    uint8_t uartBytesWritten = 0;
    uint8_t* tempPtr;
    uint16_t tmrValue;
    //UART2_TRANSFER_STATUS status ;
    
    //intialize the Board Power VDD_Board
    IO_RB2_SetLow(); 
    
//    //Testing UART code
//    while(name[i] != '\0')
//    {
//        uartBuffer[i] = (uint8_t)name[i];
//        i++;
//    }
//    uartBuffer[i] = (uint8_t)name[i];
    /*
    IO_RB15_SetHigh();
    
    for(j = 0;j<10;j++)
    {
        while(!TMR2_GetElapsedThenClear())
        {
            //IO_RB8_SetHigh();
            IO_RB15_SetHigh();
        }
            
        while(!TMR2_GetElapsedThenClear())
        {
            //IO_RB8_SetLow();
            IO_RB15_SetLow();
        }
    TMR3_delay_ms(_XTAL_FREQ, 500);
       
    }
    IO_RB15_SetHigh();
     */

      
    memcpy((void*)append[0], (void*)"th",3);
    memcpy((void*)append[1], (void*)"st",3);
    memcpy((void*)append[2], (void*)"nd",3);
    memcpy((void*)append[3], (void*)"rd",3);
    
    
    while (1) {
        
        //IO_RB15_SetLow();
        
        // Add your application code
        // Read RB7
        //portValue = IO_RB7_GetValue();
        //if(portValue == 1)
        
        if(i == 0)
        {
            strcpy(uartBuffer, introduction);
            sLength = strlen(uartBuffer);
            i++;
            
        }else{      
         appendCount = i%10;
         if(appendCount > 3)
             appendCount = 0;
         sLength = sprintf(uartBuffer, "PIC %d%s Transmission\r\n", i,append[appendCount]);
         i++;
        }
        uartBytesWritten = 0;
        
        while(uartBytesWritten < sLength)
        {
            //status = UART2_TransferStatusGet ( ) ;
            if (!UART2_TransmitBufferIsFull())
            {
                tempPtr = uartBuffer + uartBytesWritten;
                uartBytesWritten += UART2_WriteBuffer(uartBuffer+uartBytesWritten, UART2_TransmitBufferSizeGet());
            }               
            UART2_TasksTransmit();
             
            
        }
        if(i==1)
            TMR3_delay_ms(_XTAL_FREQ, 3000); //delay just so I can see the first message
        //else
          //  TMR3_delay_ms(_XTAL_FREQ, 10);
        
    }

    return -1;
}
Exemple #22
0
/*******************************************************************
 * Function:        bool USER_USB_CALLBACK_EVENT_HANDLER(
 *                        USB_EVENT event, void *pdata, uint16_t size)
 *
 * PreCondition:    None
 *
 * Input:           USB_EVENT event - the type of event
 *                  void *pdata - pointer to the event data
 *                  uint16_t size - size of the event data
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is called from the USB stack to
 *                  notify a user application that a USB event
 *                  occured.  This callback is in interrupt context
 *                  when the USB_INTERRUPT option is selected.
 *
 * Note:            None
 *******************************************************************/
bool USER_USB_CALLBACK_EVENT_HANDLER(USB_EVENT event, void *pdata, uint16_t size)
{
    switch((int)event)
    {
        case EVENT_TRANSFER:
            break;

        case EVENT_SOF:
            /* We are using the SOF as a timer to time the LED indicator.  Call
             * the LED update function here. */
            //APP_LEDUpdateUSBStatus();
            break;

        case EVENT_SUSPEND:
            /* Update the LED status for the suspend event. */
            //APP_LEDUpdateUSBStatus();

            //Call the hardware platform specific handler for suspend events for
            //possible further action (like optionally going reconfiguring the application
            //for lower power states and going to sleep during the suspend event).  This
            //would normally be done in USB compliant bus powered applications, although
            //no further processing is needed for purely self powered applications that
            //don't consume power from the host.
            SYSTEM_Initialize(SYSTEM_STATE_USB_SUSPEND);
            break;

        case EVENT_RESUME:
            /* Update the LED status for the resume event. */
            //APP_LEDUpdateUSBStatus();

            //Call the hardware platform specific resume from suspend handler (ex: to
            //restore I/O pins to higher power states if they were changed during the 
            //preceding SYSTEM_Initialize(SYSTEM_STATE_USB_SUSPEND) call at the start
            //of the suspend condition.
            SYSTEM_Initialize(SYSTEM_STATE_USB_RESUME);
            break;

        case EVENT_CONFIGURED:
            /* When the device is configured, we can (re)initialize the demo
             * code. */
            APP_DeviceCustomHIDInitialize();
            break;

        case EVENT_SET_DESCRIPTOR:
            break;

        case EVENT_EP0_REQUEST:
            /* We have received a non-standard USB request.  The HID driver
             * needs to check to see if the request was for it. */
            USBCheckHIDRequest();
            break;

        case EVENT_BUS_ERROR:
            break;

        case EVENT_TRANSFER_TERMINATED:
            break;

        default:
            break;
    }
    return true;
}
Exemple #23
0
void main (void)
{
    uint8_t    i;
    
    
    SYSTEM_Initialize();
    CONSOLE_Initialize();

    /*******************************************************************/

    // Initialize the system

    /*******************************************************************/

    /*******************************************************************/

    // Following block display demo information on LCD of Explore 16 or
    // PIC18 Explorer demo board.

    /*******************************************************************/
    LCDDisplay((char *)"Chat Demo", 0, true);

    // Clear the screen (VT100)
    Printf("\x1b[2J");
    // Send the cursor home (VT100)
    Printf("\x1b[H");
    Printf("\r\nChat Demo");
            #if defined(MRF24J40)
    Printf("\r\nRF Transceiver: MRF24J40");
            #elif defined(MRF49XA)
    Printf("\r\nRF Transceiver: MRF49XA");
            #elif defined(MRF89XA)
    Printf("\r\nRF Transceiver: MRF89XA");
            #endif
    Printf("\r\n\r\nDemo Instruction:");
    Printf("\r\nUse Console to Chat with the Peer Device");
    Printf("\r\n");
    LED_1 = 0;
    LED_2 = 0;

   /******************************************************************/

    // Read the MAC address from the MAC EEPROM on the PICTail Card

    ReadMacAddress();

    // ..and display on terminal

	Printf("\r\n\r\nMy MAC Address: 0x");
    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
    {
        CONSOLE_PrintHex(myLongAddress[MY_ADDRESS_LENGTH-1-i]);
    }
    /*******************************************************************/

    // Initialize Microchip proprietary protocol. Which protocol to use
    // depends on the configuration in ConfigApp.h

    /*******************************************************************/

    /*******************************************************************/

    // Function MiApp_ProtocolInit initialize the protocol stack. The
    // only input parameter indicates if previous network configuration
    // should be restored. In this simple example, we assume that the
    // network starts from scratch.

    /*******************************************************************/
    MiApp_ProtocolInit(false);

    // Set default channel
    if(MiApp_SetChannel(myChannel) == false)
    {
        Printf("\r\nERROR: Unable to program the channel\r\n");
        Printf("\r\nPress MCLR to start again\r\n");
        LCDDisplay((char *)"Error: Unable to Program Channel ", 0, TRUE);
        while(1);
        //Display error message on LCD and Console
    }

    /*******************************************************************/

    // Function MiApp_ConnectionMode defines the connection mode. The
    // possible connection modes are:
    //  ENABLE_ALL_CONN:    Enable all kinds of connection
    //  ENABLE_PREV_CONN:   Only allow connection already exists in
    //                      connection table
    //  ENABL_ACTIVE_SCAN_RSP:  Allow response to Active scan
    //  DISABLE_ALL_CONN:   Disable all connections.

    /*******************************************************************/
    MiApp_ConnectionMode(ENABLE_ALL_CONN);

    /*******************************************************************/

    // Display current opertion on LCD of demo board, if applicable

    /*******************************************************************/
    LCDDisplay((char *)"Connecting Peer  on Channel %d ", myChannel, true);
    Printf("\r\n\r\nConnecting to Peer...\r\n");

    /*******************************************************************/

    // Function MiApp_StartConnection will enable a node to start operating
    // in a variety of ways. Usually, this fucntion is called by the
    // PAN Coordinator who is the first in the PAN.
    //
    // The first parameter defines the mode to start the PAN in
    //
    // The second parameter defines the scan duration (if energy/carrier
    // sense scan is enabled). 0 if START_CONN_DIRECT used.
    //
    // The third parameter is a bit map of of the channels to perform the
    // noise scan on. 0 if START_CONN_DIRECT used.

    /*******************************************************************/

    MiApp_StartConnection(START_CONN_DIRECT, 0, 0) ;
    /*******************************************************************/

    // Function MiApp_EstablishConnection try to establish a new
    // connection with peer device.
    // The first parameter is the index to the active scan result,
    //      which is acquired by discovery process (active scan). If
    //      the value of the index is 0xFF, try to establish a
    //      connection with any peer.
    // The second parameter is the mode to establish connection,
    //      either direct or indirect. Direct mode means connection
    //      within the radio range; indirect mode means connection
    //      may or may not in the radio range.

    /*******************************************************************/
    #ifdef ENABLE_HAND_SHAKE
    i = 0xFF;
    while(i == 0xFF)
    {
        i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT);
    }
    #endif

    /*******************************************************************/

    // Display current opertion on LCD of demo board, if applicable

    /*******************************************************************/

    LCDDisplay((char *)"Joined  Network Successfully..", 0, true);

    /*******************************************************************/

    // Function DumpConnection is used to print out the content of the
    //  Connection Entry on the hyperterminal. It may be useful in
    //  the debugging phase.
    // The only parameter of this function is the index of the
    //  Connection Entry. The value of 0xFF means to print out all
    //  valid Connection Entry; otherwise, the Connection Entry
    //  of the input index will be printed out.

    /*******************************************************************/
    #ifdef ENABLE_DUMP
    DumpConnection(0xFF);
    #endif

    #ifndef ENABLE_POWERSAVE
    // Turn on LED 1 to indicate P2P connection established
    LED_1 = 1;
    #endif
    DELAY_ms(100);

    LCDBacklightON();
    LCD_Erase();
    sprintf((char *)LCDText, (char *)"MyAddr:   %02x%02x%02x", myLongAddress[2],
             myLongAddress[1], myLongAddress[0]);
    sprintf((char *) &(LCDText[16]), (char *)"PeerAddr: %02x%02x%02x", ConnectionTable[i].Address[2],
             ConnectionTable[i].Address[1], ConnectionTable[i].Address[0]);
    LCD_Update();

    /*******************************************************************/

    // Following block display demo instructions on LCD based on the
    // demo board used.

    /*******************************************************************/
    Printf("-------------------------------------------------------\r\n");
    Printf("Chat Window: \r\n");
    Printf("-------------------------------------------------------\r\n");
    Printf("$$");

    while(1)
    {
        if(MiApp_MessageAvailable())
        {  
            ProcessRxMessage();      
        }

        if(CONSOLE_IsGetReady())
        {
            FormatTxMessage();
            
        }

        if(messagePending)
        {
            tickCurrent = MiWi_TickGet();
            if
            (
                (MiWi_TickGetDiff(tickCurrent, tickPrevious) > (ONE_SECOND * 30)) ||
                (TxMessageSize >= MAX_MESSAGE_LEN) ||
                (transmitPending == true)
            )
            {
                
                TransmitMessage();


            }
        }

        // Display connection table if RB0 is pressed
        if(PUSH_BUTTON_1 == 0)
    	{
        	while(PUSH_BUTTON_1 == 0);
        	Printf("\r\n\r\nDumping Connection Table...\r\n");
        	DumpConnection(0xFF);
        	Printf("-------------------------------------------------------\r\n");
    		Printf("Chat Window: \r\n");
    		Printf("-------------------------------------------------------\r\n");
    		Printf("$$ ");
    	}


    }

    //Enable device to foward the received packet information to the console
}                           //end of main
Exemple #24
0
/*
                         Main application
 */
void main(void)
{
    uint16_t u16VoltVar;
    uint8_t u8CtrlHighCnt;
    uint8_t u8CtrlLowCnt;
    uint8_t u8SignalCnt;
    uint8_t u8VoltCnt;
    bool    bPowerIssue;
    bool    bCheckPower;
    
    // initialize the device
    SYSTEM_Initialize();
    InitVariable();
    
    u16VoltVar = 0;
    u8CtrlHighCnt = 0;
    u8CtrlLowCnt = 0;
    u8SignalCnt = 0;
    u8VoltCnt = 0;
    bPowerIssue = false;
    bCheckPower = false;

    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();
    
    __delay_ms(100);
    
    while (1)
    {
        if( gu8Mode != MODE_CHECK_VOLT && bPowerIssue == false )
        {
            if( bCheckPower == false )
            {
                if( gu8TMR0State & TMR0_FLAG_1S )
                {
                    gu8TMR0State &= ~TMR0_FLAG_1S;

                    u16VoltVar = 0;
                    u16VoltVar = ADC_GetVolt();
                    // 8.5V = 2250, 12V = 2850, 14V = 3200 1V ~= 170
                    if( u16VoltVar > DEF_OVP || u16VoltVar < DEF_UVP )
                    {
                        // Issue
                        u8VoltCnt = 0;
                        bCheckPower = true;
                    }
                    else
                    {
                        bPowerIssue = false;
                    }
                }
            }
            else
            {
                if( gu8TMR0State & TMR0_FLAG_10MS )
                {
                    gu8TMR0State &= ~TMR0_FLAG_10MS;
                    
                    u16VoltVar = 0;
                    u16VoltVar = ADC_GetVolt();
                    // To-Do:
                    // 8.5V = 2250, 12V = 2850, 16V = 3530 1V ~= 170
                    if( u16VoltVar > DEF_OVP || u16VoltVar < DEF_UVP )
                    {
                        u8VoltCnt++;
                        if( u8VoltCnt > 5 )
                        {
                            bPowerIssue = true;
                            bCheckPower = false;
                        }
                    }
                    else
                    {
                        u8VoltCnt = 0;
                        bCheckPower = false;
                    }
                }
            }
        }
        
        // Add your application code
        switch( gu8Mode )
        {
            case MODE_CHECK_VOLT:
                if( gu8TMR0State & TMR0_FLAG_10MS )
                {
                    gu8TMR0State &= ~TMR0_FLAG_10MS;
                    
                    u16VoltVar = 0;
                    u16VoltVar = ADC_GetVolt();
                    // To-Do:
                    // 8.5V = 2250, 12V = 2850, 16V = 3530 1V ~= 170
                    if( u16VoltVar > DEF_OVP || u16VoltVar < DEF_UVP )
                    {
                        u8VoltCnt++;
                        if( u8VoltCnt > 5 )
                        {
                            bPowerIssue = true;
                        }
                    }
                    else
                    {
                        u8VoltCnt = 0;
                        InitMotorPosition();
                    }
                }
                break;
                
            case MODE_IN_VOLT:
                break;
                
            case MODE_CHECK_CONTROL:
                if( gu8TMR0State & TMR0_FLAG_10MS )
                {
                    gu8TMR0State &= ~TMR0_FLAG_10MS;
                    u16VoltVar = 0;
                    u16VoltVar = ADC_GetVolt();
                    // To-Do:
                    // 8.5V = 2250, 12V = 2850, 16V = 3530 1V ~= 170
                    if( u16VoltVar > DEF_OVP || u16VoltVar < DEF_UVP )
                    {
                        u8VoltCnt++;
                        if( u8VoltCnt > 5 )
                        {
                            gu8Mode = MODE_CHECK_VOLT;
                        }
                    }
                    else
                    {
                        if( IO_CONTROL_GetValue() == HIGH )
                        {
                            u8CtrlHighCnt++;
                            u8CtrlLowCnt = 0;
                            if( u8CtrlHighCnt > 5 )
                            {
                                u8CtrlHighCnt = 0;
                                u8CtrlLowCnt = 0;
                                u8SignalCnt = 0;
                                gu8Mode = MODE_CONTROL_HIGH;
                            }
                        }
                        else
                        {
                            u8CtrlHighCnt = 0;
                            u8CtrlLowCnt++;
                            if( u8CtrlLowCnt > 5 )
                            {
                                u8CtrlHighCnt = 0;
                                u8CtrlLowCnt = 0;
                                u8SignalCnt = 0;
                                gu8Mode = MODE_CONTROL_LOW;
                            }
                        }
                    }
                }
                break;
                
            case MODE_CONTROL_HIGH:
                if( gu8TMR0State & TMR0_FLAG_10MS )
                {
                    gu8TMR0State &= ~TMR0_FLAG_10MS;
                    
                    IO_FEEDBACK_SetDigitalOutput();
                    if( IO_FEEDBACK_GetValue() == HIGH )
                    {
                        // C1F1
                        if( u8SignalCnt < 5 )
                        {
                            u8SignalCnt++;
                        }
                        else
                        {
                            gu8Mode = MODE_FORWARD;    // CW
                            TMR2_StartTimer();
                            TMR2_WriteTimer(0);
                            IO_CW_GREEN_SetHigh();
                        }
                    }
                    else
                    {
                        // C1F0
                        u8SignalCnt = 0;
                        u8CtrlHighCnt = 0;
                        u8CtrlLowCnt = 0;
                        gu8Mode = MODE_CHECK_CONTROL;
                    }
                }
                break;
                
            case MODE_CONTROL_LOW:
                if( gu8TMR0State & TMR0_FLAG_10MS )
                {
                    gu8TMR0State &= ~TMR0_FLAG_10MS;
                    
                    IO_FEEDBACK_SetDigitalOutput();
                    if( IO_FEEDBACK_GetValue() == LOW )
                    {
                        // C0F0
                        if( u8SignalCnt < 5 )
                        {
                            u8SignalCnt++;
                        }
                        else
                        {
                            gu8Mode = MODE_BACKWARD;    // CCW
                            TMR2_StartTimer();
                            TMR2_WriteTimer(0);
                            IO_CCW_RED_SetHigh();
                        }
                    }
                    else
                    {
                        // C0F1
                        u8CtrlHighCnt = 0;
                        u8CtrlLowCnt = 0;
                        u8SignalCnt = 0;
                        gu8Mode = MODE_CHECK_CONTROL;
                    }
                }
                break;
                
            case MODE_FORWARD:
                if( LOW == IO_CW_GREEN_GetValue() ||
                    true == bCheckInTheMiddle() )
                {
                    TMR2_StopTimer();
                    IO_CW_GREEN_SetLow();
                    IO_B_CTRL_SetHigh();        // Set B signal to low
                    IO_Y_CTRL_SetLow();        // Set Y signal to high
                    IO_W_CTRL_SetHigh();        // Set W signal to low
                    
                    IO_FEEDBACK_SetDigitalOutput();
                    IO_FEEDBACK_SetLow();
                    u8CtrlHighCnt = 0;
                    u8CtrlLowCnt = 0;
                    if( bPowerIssue == true )
                    {
                        bPowerIssue = false;
                        gu8Mode = MODE_CHECK_VOLT;
                    }
                    else
                    {
                        gu8Mode = MODE_CHECK_CONTROL;
                    }
                }
                break;
                
            case MODE_BACKWARD:
                if( LOW == IO_CCW_RED_GetValue() ||
                    true == bCheckBConnectW() )
                {
                    TMR2_StopTimer();
                    IO_CCW_RED_SetLow();
                    IO_B_CTRL_SetHigh();        // Set B signal to low
                    IO_Y_CTRL_SetLow();        // Set Y signal to high
                    IO_W_CTRL_SetHigh();        // Set W signal to low
                    
                    IO_FEEDBACK_SetDigitalOutput();
                    IO_FEEDBACK_SetHigh();
                    u8CtrlHighCnt = 0;
                    u8CtrlLowCnt = 0;
                    if( bPowerIssue == true )
                    {
                        bPowerIssue = false;
                        gu8Mode = MODE_CHECK_VOLT;
                    }
                    else
                    {
                        gu8Mode = MODE_CHECK_CONTROL;
                    }
                }
                break;
                
            case MODE_FINISH:
                IO_CW_GREEN_SetLow();
                IO_CCW_RED_SetLow();
                IO_B_CTRL_SetHigh();        // Set B signal to low
                IO_Y_CTRL_SetLow();        // Set Y signal to high
                IO_W_CTRL_SetHigh();        // Set W signal to low
                TMR2_StopTimer();
                
                IO_FEEDBACK_SetDigitalOutput();
                if( IO_CONTROL_GetValue() == LOW )
                {
                    IO_FEEDBACK_SetHigh();
                }
                else
                {
                    IO_FEEDBACK_SetLow();
                }
                u8CtrlHighCnt = 0;
                u8CtrlLowCnt = 0;
                if( bPowerIssue == true )
                {
                    bPowerIssue = false;
                    gu8Mode = MODE_CHECK_VOLT;
                }
                else
                {
                    gu8Mode = MODE_CHECK_CONTROL;
                }
                break;
                
            default:
                break;
        }
        
        CLRWDT();
    }
    
}
Exemple #25
0
int main(void) {
    // initialize the device
    SYSTEM_Initialize();
    
    //Light show 
    debounce(2);
    PORTAbits.RA3 = 0;    //Led 4 
    debounce(5);
    PORTBbits.RB5 = 0;    //Led 3
    debounce(2);
    PORTBbits.RB7 = 0;    //Led 2
    debounce(1);
    PORTBbits.RB6 = 0;    //Led 1
    debounce(1);
    
    ResetMemory();
    
    while (1) {
        //All mighty while loop
        
        if(TransmitComplete){
            TransmitComplete = 0; 
            SetTo90();
            if(LocalMemory[0]== 0x01){
            MoveServo1_Degrees(LocalMemory[1]); 
            debounce(1);
            MoveServo4_Degrees(LocalMemory[4]);
            debounce(1);
            MoveServo3_Degrees(LocalMemory[3]);
            debounce(1);
            MoveServo2_Degrees(LocalMemory[2]);
            debounce(1);
            MoveServo5_Degrees(LocalMemory[5]);
            ResetMemory();  
            }
            else if(LocalMemory[0]== 0x02){
                
                switch(LocalMemory[1]){
                    case 1: GrabBlock();
                        break;
                    case 2: break;
                    case 3: break;
                    case 4: break;
                    case 5: break;
                            
                    
                }
            }
            
        }
        
        if(PORTAbits.RA0 == 1){        //S1 pressed
            S1++; 
            if(S1==10)
                                     //Overflow Condition~No State 9
                S1 = 1; 
            
            debounce(10);
            StateMaker(S1);         //Set the LEDs 
        }
        
        if(PORTAbits.RA2 == 1){          //S2 pressed 
            
            PORTBbits.RB6 = 1;        //Signifies selection with blinking of light
            debounce(5);
            PORTBbits.RB6 = 0;
            debounce(3); 
            PORTBbits.RB6 = 1;
            debounce(2);
            PORTBbits.RB6 = 0;
            debounce(1); 
            PORTBbits.RB6 = 1;
            
            MakeSelection(S1); 
            
            PORTBbits.RB6 = 1;        //Signifies end of selection with blinking of light
            debounce(5);
            PORTBbits.RB6 = 0;
            debounce(3); 
            PORTBbits.RB6 = 1;
            debounce(2);
            PORTBbits.RB6 = 0;
            debounce(1); 
            PORTBbits.RB6 = 1;
            debounce(1);
            PORTBbits.RB6 = 0; 
          
        }
    }
    return -1;
}
Exemple #26
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_HostHIDMouseTasks(void);
*
* Overview: Keeps the demo running.
*
* PreCondition: The demo should have been initialized via
*   the APP_HostHIDMouseInitialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void APP_HostHIDMouseTasks()
{
    uint8_t error;
    uint8_t count;
    
    if(!USBHostHID_ApiDeviceDetect())
    {
        if(mouse.state != WAITING_FOR_DEVICE)
        {
            mouse.state = DEVICE_NOT_CONNECTED;

            mouse.inUse = false;

            if(mouse.buffer != NULL)
            {
                free(mouse.buffer);
                mouse.buffer = NULL;
            }
        }
    }

    switch(mouse.state)
    {
        case DEVICE_NOT_CONNECTED:
            PRINT_ClearScreen();
            PRINT_String("Attach mouse\r\n", 17);
            mouse.state = WAITING_FOR_DEVICE;
            break;
            
        case WAITING_FOR_DEVICE:
            if(USBHostHID_ApiDeviceDetect()) /* True if report descriptor is parsed with no error */
            {
                SYSTEM_Initialize(SYSTEM_STATE_USB_HOST_HID_MOUSE);
                PRINT_ClearScreen();
                PRINT_String("L:0 R:0\r\nX:0x00 Y:0x00\r\n", 24);
                
                mouse.state = DEVICE_CONNECTED;
                TIMER_RequestTick(&APP_HostHIDTimerHandler, 10);
            }
            break;
            
        case DEVICE_CONNECTED:
            break;

        case GET_INPUT_REPORT:
            if(USBHostHID_ApiGetReport( mouse.deflection.parsed.details.reportID,
                                        mouse.deflection.parsed.details.interfaceNum,
                                        mouse.deflection.parsed.details.reportLength,
                                        mouse.buffer
                                      )
              )
            {
                /* Host may be busy/error -- keep trying */
            }
            else
            {
                mouse.state = INPUT_REPORT_PENDING;
            }
            break;

        case INPUT_REPORT_PENDING:
            if(USBHostHID_ApiTransferIsComplete(&error, &count))
            {
                if(error || (count != mouse.deflection.parsed.details.reportLength))
                {
                    mouse.state = DEVICE_CONNECTED;
                }
                else
                {
                    mouse.state = DEVICE_CONNECTED;

                    App_ProcessInputReport();
                }
            }
            break;

        case ERROR_REPORTED:
            break;

        default:
            break;

    }
}
/*********************************************************************
* Function: void APP_HostHIDKeyboardTasks(void);
*
* Overview: Keeps the demo running.
*
* PreCondition: The demo should have been initialized via
*   the APP_HostHIDKeyboardInitialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void APP_HostHIDKeyboardTasks()
{
    uint8_t error;
    uint8_t count;
    
    if(!USBHostHID_ApiDeviceDetect())
    {
        if(keyboard.state != WAITING_FOR_DEVICE)
        {
            keyboard.state = DEVICE_NOT_CONNECTED;

            keyboard.inUse = false;

            if(keyboard.keys.buffer != NULL)
            {
                free(keyboard.keys.buffer);
                keyboard.keys.buffer = NULL;
            }
        }
    }

    switch(keyboard.state)
    {
        case DEVICE_NOT_CONNECTED:
            PRINT_ClearScreen();
            PRINT_String("Attach keyboard\r\n", 17);
            keyboard.state = WAITING_FOR_DEVICE;
            LED_Off(LED_USB_HOST_HID_KEYBOARD_DEVICE_READY);
            break;
            
        case WAITING_FOR_DEVICE:
            if(USBHostHID_ApiDeviceDetect()) /* True if report descriptor is parsed with no error */
            {
                PRINT_ClearScreen();
                SYSTEM_Initialize(SYSTEM_STATE_USB_HOST_HID_KEYBOARD);
                LED_On(LED_USB_HOST_HID_KEYBOARD_DEVICE_READY);
                
                keyboard.state = DEVICE_CONNECTED;
                TIMER_RequestTick(&APP_HostHIDTimerHandler, 10);
            }
            break;
            
        case DEVICE_CONNECTED:
            break;

        case GET_INPUT_REPORT:
            if(USBHostHID_ApiGetReport( keyboard.keys.id,
                                        keyboard.keys.normal.parsed.details.interfaceNum,
                                        keyboard.keys.size,
                                        keyboard.keys.buffer
                                      )
              )
            {
                /* Host may be busy/error -- keep trying */
            }
            else
            {
                keyboard.state = INPUT_REPORT_PENDING;
            }
            break;

        case INPUT_REPORT_PENDING:
            if(USBHostHID_ApiTransferIsComplete(&error, &count))
            {
                if(error || (count == 0))
                {
                    keyboard.state = DEVICE_CONNECTED;
                }
                else
                {
                    keyboard.state = DEVICE_CONNECTED;

                    App_ProcessInputReport();
                    if(keyboard.leds.updated == true)
                    {
                        keyboard.state = SEND_OUTPUT_REPORT;
                    }
                }
            }
            break;

        case SEND_OUTPUT_REPORT: /* Will be done while implementing Keyboard */
            if(USBHostHID_ApiSendReport(    keyboard.leds.parsed.details.reportID,
                                            keyboard.leds.parsed.details.interfaceNum,
                                            keyboard.leds.parsed.details.reportLength,
                                            (uint8_t*)&keyboard.leds.report
                                       )
              )
            {
                /* Host may be busy/error -- keep trying */
            }
            else
            {
                keyboard.state = OUTPUT_REPORT_PENDING;
            }
            break;

        case OUTPUT_REPORT_PENDING:
            if(USBHostHID_ApiTransferIsComplete(&error, &count))
            {
                keyboard.leds.updated = false;
                keyboard.state = DEVICE_CONNECTED;
            }
            break;

        case ERROR_REPORTED:
            break;

        default:
            break;

    }
}
Exemple #29
0
/********************************************************************
 * Function:        void main(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Main program entry point.
 *
 * Note:            None
 *******************************************************************/
void main(void) {
    
    // test command buffer
//    if(0)
//    {
//    UB_Init();
//    
//    UB_ProcessCommand( STX);
//    UB_ProcessCommand( STX);
//    UB_ProcessCommand( 0x76);
//    UB_ProcessCommand( 0x8A);
//    UB_ProcessCommand( ETX);
//    
//    UB_ProcessCommand( STX);
//    UB_ProcessCommand( STX);
//    UB_ProcessCommand( 0);
//    UB_ProcessCommand( ETX);
//    
//    APP_HostHIDPICkitTasks();
//    
//    UB_ProcessCommand( STX);
//    UB_ProcessCommand( STX);
//    UB_ProcessCommand( 0);
//    UB_ProcessCommand( ETX);
//    }
    
    //------------- test UART ----------------
    setup();
   
//    if(0)
//    {
//       //test Timer_1ms
//       TIMER_SetConfiguration ( TIMER_CONFIGURATION_1MS );
//       TIMER_RequestTick( blinkLED, 500); //500ms
//       
//       //test UART2
//       IEC1bits.U2RXIE= 1;  //enable RXIE
//
//    }
    
    //--------------------------------
    SYSTEM_Initialize(SYSTEM_STATE_USB_HOST);

    //Initialize the stack
    USBHostInit(0);

    APP_HostHIDPICkitInitialize();

    UB_Init(); // UART_Buffer

    while (1) {
        USBHostTasks();
        USBHostHIDTasks();

        //Application specific tasks
        APP_HostHIDPICkitTasks();

        UB_TxTasks();

        LATBbits.LATB3 ^= 1;
    }//end while
}//end main
Exemple #30
0
// Application Start
void main(void)
{
    // Prepare Application; MCC generated code
    SYSTEM_Initialize();
    // Custom Initializations
    
    
    
    /*   
     *   watchdog timer 
     *   configured for 131s timeout
     * 
     */
    //WDTCONbits.SWDTEN = 1; // enable watchdog
    //ClrWdt();
    
    
    
    oled_init();         // Dispaly
    USBDeviceInit();	// usb_device.c.  Initializes USB module SFRs and firmware
                        // variables to known states.
    
    
    
    
    USBDeviceAttach();
    // Interrupts Enabled
    PEIE = 1;
    GIE = 1;
    
    // Test Hardware
    moteApp_delayms(300);    
    modemResync();
    moteApp_delayms(300);
//    moteApp_clearCommand();
//    moteApp_delayms(100);   
    
    powerOnStatus = DATAEE_ReadByte(0x00);
#if 0
    if ( powerOnStatus != 0x55)
    {
        test_powerup();
        DATAEE_WriteByte(0x00, 0x55);
    }
#endif

    // Default to USB
    operationType = USB;   // Mode State
    USBapp_handlerState(USB_STARTUP);
    
    
    
    // Initial Display Print
    oled_clear();
    oled_putString("Scriptr IoT-X",0,0);
    oled_putString(" Dev: S1 ",0,1);
    oled_putString("   build 006   ",0,3);
    moteApp_delayms(700);
   
    // Application Loop
    while(1)
    {
        // Handle USB or Solo Mode
        switch (operationType)
        {
            default:        // Invalid
                while(1);   // Hold For Error;
            break;
            case USB:
                USBapp_Handler();   // It is held in here.
                // USB escaped; Cable is unplugged; Change OPERATION mode.
                operationType = MOTE;
                MOTEapp_handlerState(MOTE_STARTUP);   // Initial state for startup
            break;
            case MOTE:
                if (moteHandler() == MOTE_SWAP)
                {
                    // Return to USB Operation
                    operationType = USB;   // Mode State
                    USBapp_handlerState(USB_STARTUP);
                }
            break;
        }
    }
}