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; }
// *--------------------------------------------------------------------------------* int main(){ UINT16 Count=0; mJTAGPortEnable(0); // JTAG des-habilitado SYSTEMConfigPerformance(GetSystemClock()); // Activa pre-cache.- LED1_OUTPUT(); LED2_OUTPUT(); INTEnableSystemMultiVectoredInt(); deviceAttached = FALSE; //Initialize the stack USBInitialize(0); while(1){ //USB stack process function USBTasks(); if(++Count==0){ LED1_TOGGLE(); } //if thumbdrive is plugged in if(USBHostMSDSCSIMediaDetect()){ deviceAttached = TRUE; LED1_OFF(); //now a device is attached //See if the device is attached and in the right format if(FSInit()){ //Opening a file in mode "w" will create the file if it doesn't // exist. If the file does exist it will delete the old file // and create a new one that is blank. myFile = FSfopen("test.txt","w"); //Write some data to the new file. FSfwrite("This is a test.",1,15,myFile); //Always make sure to close the file so that the data gets // written to the drive. FSfclose(myFile); //Just sit here until the device is removed. while(deviceAttached == TRUE){ USBTasks(); if(++Count==0){ LED2_TOGGLE(); } } LED2_OFF(); } } } }
void ConnectionTasks() { int i; USBTasks(); for (i = 0; i < CHANNEL_TYPE_MAX; ++i) { factories[i]->tasks(); } }
BOOL BootloaderConnTasks() { int role = USBTasks(); ConnADBTasks(); return !role // device mode || USBHostAndroidIsInterfaceAttached(ANDROID_INTERFACE_ADB) || unknown_device_attached; }
/****************************************************************************** * Function: void main(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: Main program entry point. * * Note: None *****************************************************************************/ void main(void) { InitializeSystem(); while(1) { USBTasks(); // USB Tasks ProcessIO(); // See user\user.c & .h }//end while }//end main
void bootloader(void) { FSFILE* file; USBInitialize(0); if (!FSInit()) { // File system failed - pretty much DISKmount didn't work AT45D_FormatFS(); if (!FSInit()) { error(ERR_FS_INIT); } } while (1) { USBTasks(); BlinkBlueLED(); // User Application USB tasks if ((USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1)) { // do nothing } else { BlinkGreenLED(); MSDTasks(); } if (_T1IF) { _T1IF = 0; // check for MSD activity... if (MDD_AT45D_Write_Activity) { MDD_AT45D_Write_Activity = 0; } else { file = FSfopen("image.hex", "r"); if (file != NULL) { file_flash(file); FSfclose(file); FSremove("image.hex"); //AT45D_FormatFS(); return; } } } } }
/** * Main function * Main program entry point. * */ void main(void) { InitializeSystem(); tickInit(); while(1) { USBTasks(); BlinkUSBStatus(); if (!((usb_device_state < CONFIGURED_STATE)||(UCONbits.SUSPND==1))) ProcessIO(); // See user\user.c & .h } }
// 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); }
/****************************************************************************** * Function: void Main(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: Main program entry point. * * Note: None *****************************************************************************/ void Main(void) { //NOTE: The c018.o file is not included in the linker script for this project. //The C initialization code in the c018.c (comes with C18 compiler in the src directory) //file is instead modified and included here manually. This is done so as to provide //a more convenient entry method into the bootloader firmware. Ordinarily the _entry_scn //program code section starts at 0x00 and is created by the code of c018.o. However, //the linker will not work if there is more than one section of code trying to occupy 0x00. //Therefore, must not use the c018.o code, must instead manually include the useful code //here instead. // Initialize the C stack pointer, and other compiler managed items as normally done in the c018.c file. _asm lfsr 1, _stack lfsr 2, _stack clrf TBLPTRU, 0 _endasm // End of the important parts of the C initializer. This bootloader firmware does not use // any C initialized user variables (idata memory sections). Therefore, the above is all // the initialization that is required. InitializeSystem(); //Some USB, I/O pins, and other initialization while(1) { ClrWdt(); USBTasks(); // Need to call USBTasks() periodically // it handles SETUP packets needed for enumeration BlinkUSBStatus(); //Blink the LEDs based on current USB state if((usb_device_state == CONFIGURED_STATE) && (UCONbits.SUSPND != 1)) { ProcessIO(); // This is where all the actual bootloader related data transfer/self programming takes place } // see ProcessIO() function in the Boot87J50Family.c file. }//end while }//end main
int main (void) { #if defined (__C30__) || defined __XC16__ #if defined( __PIC24FJ256GB110__ ) || defined(__PIC24FJ256GB210__) // Configure U2RX - put on pin 49 (RP10) RPINR19bits.U2RXR = 10; // Configure U2TX - put on pin 50 (RP17) RPOR8bits.RP17R = 5; // Configure SPI2 Data In - put on pin 11 (RP26) RPINR22bits.SDI2R = 26; // Configure SPI2 Clock Out - put on pin 10 (RP21) RPOR10bits.RP21R = 11; // Configure SPI2 Data Out - put on pin 12 (RP19) RPOR9bits.RP19R = 10; OSCCON = 0x3302; // Enable secondary oscillator CLKDIV = 0x0000; // Set PLL prescaler (1:1) #elif defined(__PIC24FJ64GB004__) //On the PIC24FJ64GB004 Family of USB microcontrollers, the PLL will not power up and be enabled //by default, even if a PLL enabled oscillator configuration is selected (such as HS+PLL). //This allows the device to power up at a lower initial operating frequency, which can be //advantageous when powered from a source which is not gauranteed to be adequate for 32MHz //operation. On these devices, user firmware needs to manually set the CLKDIV<PLLEN> bit to //power up the PLL. { unsigned int pll_startup_counter = 600; CLKDIVbits.PLLEN = 1; while(pll_startup_counter--); } //Device switches over automatically to PLL output after PLL is locked and ready. #elif defined(__PIC24FJ256DA210__) //TX RF3 RP16 //RX RD0 RP11 // Configure U2RX - put on RP11 RPINR19bits.U2RXR = 11; // Configure U2TX - put on RP16 RPOR8bits.RP16R = 5; #endif #elif defined(__PIC32MX__) { int value; value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() ); // Enable the cache for the best performance CheKseg0CacheOn(); INTEnableSystemMultiVectoredInt(); value = OSCCON; while (!(value & 0x00000020)) { value = OSCCON; // Wait for PLL lock to stabilize } } AD1PCFG = 0xFFFF; // Set analog pins to digital. TRISF = 0x00; #else #error Cannot initialize. #endif UART2Init(); UART2PrintString( "\r\n\r\nUSB Embedded Host Simple Full Sheet Printer Demo\r\n" ); // Initialize USB Embedded Host USBInitialize(0); // Turn on the A/D converter to monitor Vbus. InitializeVbusMonitor(); while(1) { MonitorVBUS(); USBTasks(); if (status.printerAttached) { if(status.printerStatusDone == 0) { if(status.printerStatusSent == 0) { if(USBHostPrinterGetStatus( printerInfo.deviceAddress, &status.printer ) == USB_SUCCESS) { status.printerStatusSent = 1; } } } else { if(status.printer != 0x18) { //if there was an error in the printer status then setup to // check the status again status.printerStatusSent = 0; status.printerStatusDone = 0; } else { if (!status.pagePrinted) { status.pagePrinted = 1; UART2PrintString( "Printing to full sheet printer...\r\n" ); // Initialize USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_JOB_START, USB_NULL, 0, 0 ); if (!printerInfo.support.supportFlags.supportsVectorGraphics) { // In the demo's initial configuration, this section executes for the HP Deskjet 460. UART2PrintString( "Vector graphics are not supported.\r\n" ); imageInfo.resolution = 75; imageInfo.scale = 1.0; imageInfo.positionX = (PRINTER_PAGE_PORTRAIT_WIDTH - 0x120)/2; imageInfo.positionY = 100; #if defined( __C30__ ) || defined __XC16__ PrintImageFullSheet( (BYTE __prog__ *)(logoMCHP.address), &imageInfo ); #elif defined( __PIC32MX__ ) PrintImageFullSheet( (const BYTE *)(logoMCHP.address), &imageInfo ); #endif USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_NAME, USB_NULL, USB_PRINTER_FONT_COURIER, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)24, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_BOLD, USB_NULL, 0, 0 ); WriteLine( 200, 325, &(businessCard[0][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_MEDIUM, USB_NULL, 0, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)20, 0 ); WriteLine( 200, 350, &(businessCard[1][0]) ); WriteLine( 200, 375, &(businessCard[2][0]) ); WriteLine( 200, 400, &(businessCard[3][0]) ); WriteLine( 200, 425, &(businessCard[4][0]) ); WriteLine( 200, 450, &(businessCard[5][0]) ); WriteLine( 200, 475, &(businessCard[6][0]) ); WriteLine( 200, 500, &(businessCard[7][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_NAME, USB_NULL, USB_PRINTER_FONT_TIMES_NEW_ROMAN, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)18, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_BOLD, USB_NULL, 0, 0 ); WriteLine( 50, PRINTER_PAGE_PORTRAIT_HEIGHT - 145, &(adddressMicrochip[0][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_MEDIUM, USB_NULL, 0, 0 ); WriteLine( 50, PRINTER_PAGE_PORTRAIT_HEIGHT - 120, &(adddressMicrochip[1][0]) ); WriteLine( 50, PRINTER_PAGE_PORTRAIT_HEIGHT - 95, &(adddressMicrochip[2][0]) ); WriteLine( 50, PRINTER_PAGE_PORTRAIT_HEIGHT - 70, &(adddressMicrochip[3][0]) ); } else { // In the demo's initial configuration, this section executes for the Lexmark E250dn. USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_ORIENTATION_LANDSCAPE, USB_NULL, 0, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE_WIDTH, USB_NULL, PRINTER_LINE_WIDTH_THICK, 0 ); params.sBevel.xL = 50; // X-axis position of the left side of the bevel. params.sBevel.yT = 50; // Y-axis position of the top of the bevel. params.sBevel.xR = PRINTER_PAGE_LANDSCAPE_WIDTH - 50; // X-axis position of the right side of the bevel. params.sBevel.yB = PRINTER_PAGE_LANDSCAPE_HEIGHT - 50; // Y-axis position of the bottom of the bevel. params.sBevel.r = 20; // The radius of the cicle that defines the rounded corner USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_BEVEL, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sBevel), 0 ); imageInfo.resolution = 75; imageInfo.scale = 1.0; imageInfo.positionX = 100; imageInfo.positionY = 100; #if defined( __C30__ ) || defined __XC16__ PrintImageFullSheet( (BYTE __prog__ *)(logoMCHP.address), &imageInfo ); #elif defined( __PIC32MX__ ) PrintImageFullSheet( (const BYTE *)(logoMCHP.address), &imageInfo ); #endif USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_NAME, USB_NULL, USB_PRINTER_FONT_HELVETICA, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)18, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_BOLD, USB_NULL, 0, 0 ); WriteLine( 100, PRINTER_PAGE_LANDSCAPE_HEIGHT - 145, &(adddressMicrochip[0][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_MEDIUM, USB_NULL, 0, 0 ); WriteLine( 100, PRINTER_PAGE_LANDSCAPE_HEIGHT - 120, &(adddressMicrochip[1][0]) ); WriteLine( 100, PRINTER_PAGE_LANDSCAPE_HEIGHT - 95, &(adddressMicrochip[2][0]) ); WriteLine( 100, PRINTER_PAGE_LANDSCAPE_HEIGHT - 70, &(adddressMicrochip[3][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_NAME, USB_NULL, USB_PRINTER_FONT_AVANT_GARDE, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)24, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_BOLD, USB_NULL, 0, 0 ); WriteLine( 450, 125, &(businessCard[0][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_MEDIUM, USB_NULL, 0, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)20, 0 ); WriteLine( 450, 150, &(businessCard[1][0]) ); WriteLine( 450, 175, &(businessCard[2][0]) ); WriteLine( 450, 200, &(businessCard[3][0]) ); WriteLine( 450, 225, &(businessCard[4][0]) ); WriteLine( 450, 250, &(businessCard[5][0]) ); WriteLine( 450, 275, &(businessCard[6][0]) ); WriteLine( 450, 300, &(businessCard[7][0]) ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_NAME, USB_NULL, USB_PRINTER_FONT_PALATINO, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_SIZE, USB_NULL, (DWORD)16, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_FONT_ITALIC, USB_NULL, 0, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE_WIDTH, USB_NULL, PRINTER_LINE_WIDTH_NORMAL, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE_TYPE, USB_NULL, PRINTER_LINE_TYPE_DASHED, 0 ); WriteLine( 120, 310, &(notes[0][0]) ); params.sLine.x1 = 170; params.sLine.y1 = 290; params.sLine.x2 = 220; params.sLine.y2 = 260; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sLine), 0 ); WriteLine( 216, 396, &(notes[1][0]) ); params.sLine.x1 = 266; params.sLine.y1 = 400; params.sLine.x2 = 216; params.sLine.y2 = 445; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sLine), 0 ); WriteLine( 440, 330, &(notes[2][0]) ); params.sLine.x1 = 490; params.sLine.y1 = 310; params.sLine.x2 = 515; params.sLine.y2 = 280; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sLine), 0 ); WriteLine( 450, 410, &(notes[3][0]) ); params.sLine.x1 = 550; params.sLine.y1 = 415; params.sLine.x2 = 590; params.sLine.y2 = 430; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sLine), 0 ); params.sLine.x1 = 500; params.sLine.y1 = 415; params.sLine.x2 = 500; params.sLine.y2 = 540; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sLine), 0 ); #define TAO_UNIT 4 #define TAO_XL (PRINTER_PAGE_LANDSCAPE_WIDTH - 200) #define TAO_YT (PRINTER_PAGE_LANDSCAPE_HEIGHT - 200) #define TAO_XC (TAO_XL + TAU_UNIT * 12) #define TAO_YC (TAO_YL + TAU_UNIT * 12) USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE_WIDTH, USB_NULL, PRINTER_LINE_WIDTH_NORMAL, 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_LINE_TYPE, USB_NULL, PRINTER_LINE_TYPE_SOLID, 0 ); params.sArc.xL = TAO_XL; params.sArc.yT = TAO_YT; params.sArc.xR = TAO_XL + TAO_UNIT * 24; params.sArc.yB = TAO_YT + TAO_UNIT * 24; params.sArc.r1 = 0; params.sArc.r2 = TAO_UNIT * 12; params.sArc.octant = 0xF0; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_ARC, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sArc), 0 ); params.sCircle.x = TAO_XL + TAO_UNIT * 12; params.sCircle.y = TAO_YT + TAO_UNIT * 18; params.sCircle.r = TAO_UNIT * 6; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_CIRCLE_FILLED, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sCircle), 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_COLOR, USB_NULL, PRINTER_COLOR_WHITE, 0 ); params.sCircle.x = TAO_XL + TAO_UNIT * 12; params.sCircle.y = TAO_YT + TAO_UNIT * 6; params.sCircle.r = TAO_UNIT * 6; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_CIRCLE_FILLED, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sCircle), 0 ); params.sCircle.x = TAO_XL + TAO_UNIT * 12; params.sCircle.y = TAO_YT + TAO_UNIT * 18; params.sCircle.r = TAO_UNIT; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_CIRCLE_FILLED, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sCircle), 0 ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_COLOR, USB_NULL, PRINTER_COLOR_BLACK, 0 ); params.sCircle.x = TAO_XL + TAO_UNIT * 12; params.sCircle.y = TAO_YT + TAO_UNIT * 6; params.sCircle.r = TAO_UNIT; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_CIRCLE_FILLED, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sCircle), 0 ); params.sCircle.x = TAO_XL + TAO_UNIT * 12; params.sCircle.y = TAO_YT + TAO_UNIT * 12; params.sCircle.r = TAO_UNIT * 12; USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_GRAPHICS_CIRCLE, USB_DATA_POINTER_RAM(¶ms), sizeof(params.sCircle), 0 ); } // Terminate UART2PrintString( "Demo complete.\r\n" ); USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_JOB_STOP, USB_NULL, 0, 0 ); } } } } } }
static BOOL hid_device_read(BYTE deviceAddress, void *data) { // call usb host layer USBTasks(); // Was device detached? // Or, was report descriptor parsed with error.? if(!USBHostHIDDeviceDetect(deviceAddress)){ App_State[deviceAddress] = DEVICE_NOT_CONNECTED; } switch(App_State[deviceAddress]){ case DEVICE_NOT_CONNECTED: USBTasks(); /* True if report descriptor is parsed with no error */ if(USBHostHIDDeviceDetect(deviceAddress)){ App_State[deviceAddress] = DEVICE_CONNECTED; } break; case DEVICE_CONNECTED: App_State[deviceAddress] = READY_TO_TX_RX_REPORT; break; case READY_TO_TX_RX_REPORT: if(USBHostHIDDeviceDetect(deviceAddress)){ App_State[deviceAddress] = GET_INPUT_REPORT; }else{ App_State[deviceAddress] = DEVICE_NOT_CONNECTED; } break; case GET_INPUT_REPORT: if(!USBHostHIDRead(deviceAddress, Appl_raw_report_buffer[deviceAddress].Report_ID,0, Appl_raw_report_buffer[deviceAddress].ReportSize, Appl_raw_report_buffer[deviceAddress].ReportData)){ App_State[deviceAddress] = INPUT_REPORT_PENDING; } break; case INPUT_REPORT_PENDING: if(USBHostHIDTransferIsComplete(deviceAddress, &ErrorDriver[deviceAddress],&NumOfBytesRcvd[deviceAddress])){ if(ErrorDriver[deviceAddress] ||(NumOfBytesRcvd[deviceAddress] != Appl_raw_report_buffer[deviceAddress].ReportSize )){ ErrorCounter[deviceAddress]++ ; if(MAX_ERROR_COUNTER <= ErrorDriver[deviceAddress]){ App_State[deviceAddress] = ERROR_REPORTED; }else{ App_State[deviceAddress] = READY_TO_TX_RX_REPORT; } }else{ ErrorCounter[deviceAddress] = 0; ReportBufferUpdated[deviceAddress] = TRUE; App_State[deviceAddress] = READY_TO_TX_RX_REPORT; App_ProcessInputReport(deviceAddress, data); App_PrepareOutputReport(deviceAddress); return TRUE; } } break; case SEND_OUTPUT_REPORT: /* Will be done while implementing Keyboard */ if(!USBHostHIDWrite(deviceAddress, Appl_LED_Indicator[deviceAddress].reportID, Appl_LED_Indicator[deviceAddress].interfaceNum, Appl_LED_Indicator[deviceAddress].reportLength, (BYTE*)&Appl_led_report_buffer[deviceAddress])){ App_State[deviceAddress] = OUTPUT_REPORT_PENDING; } break; case OUTPUT_REPORT_PENDING: if(USBHostHIDTransferIsComplete(deviceAddress, &ErrorDriver[deviceAddress],&NumOfBytesRcvd[deviceAddress])){ if(ErrorDriver[deviceAddress]){ ErrorCounter[deviceAddress]++ ; if(MAX_ERROR_COUNTER <= ErrorDriver[deviceAddress]){ App_State[deviceAddress] = ERROR_REPORTED; } }else{ ErrorCounter[deviceAddress] = 0; App_State[deviceAddress] = READY_TO_TX_RX_REPORT; } } break; case ERROR_REPORTED: // forever error loop break; default: break; } // ReportData isn't ready! return FALSE; }
void hidTask (void) { BYTE i; int deviceValue = 0; USBTasks(); App_Detect_Device(); switch (App_State_Mouse_Keyboard) { case DEVICE_NOT_CONNECTED: connectedDevice = DEVICE_NOT_CONNECTED_OR_NOT_SUPPORTED; USBTasks(); if (DisplayDeatachOnce == FALSE) { DisplayDeatachOnce = TRUE; } if (USBHostHID_ApiDeviceDetect()) { DisplayConnectOnce = FALSE; deviceValue = USBHID_ReportDecriptor_Difference(); if (deviceValue == USB_HID_MOUSE) { App_State_Mouse_Keyboard = MOUSE_DEVICE_CONNECTED; } else if (deviceValue == USB_HID_KEYBOARD) { App_State_Mouse_Keyboard = KEYBOARD_DEVICE_CONNECTED; } } break; case MOUSE_DEVICE_CONNECTED: UART2PrintString("\r\n"); UART2PrintString(UHP_MOUSE_CONNECTED); UART2PrintString("\r\n"); connectedDevice = DEVICE_MOUSE; App_State_Mouse_Keyboard = MOUSE_READY_TO_TX_RX_REPORT; if (DisplayConnectOnce == FALSE) { DisplayConnectOnce = TRUE; DisplayDeatachOnce = FALSE; } break; case KEYBOARD_DEVICE_CONNECTED: UART2PrintString("\r\n"); UART2PrintString(UHP_KEYBOARD_CONNECTED); UART2PrintString("\r\n"); connectedDevice = DEVICE_KEYBOARD; App_State_Mouse_Keyboard = KEYBOARD_READY_TO_TX_RX_REPORT; if (DisplayConnectOnce == FALSE) { DisplayConnectOnce = TRUE; DisplayDeatachOnce = FALSE; } InitializeTimer(); break; case MOUSE_READY_TO_TX_RX_REPORT: if (!USBHostHID_ApiDeviceDetect()) { App_State_Mouse_Keyboard = DEVICE_NOT_CONNECTED; } else { App_State_Mouse_Keyboard = MOUSE_GET_INPUT_REPORT; } break; case KEYBOARD_READY_TO_TX_RX_REPORT: if (!USBHostHID_ApiDeviceDetect()) { App_State_Mouse_Keyboard = DEVICE_NOT_CONNECTED; } break; case MOUSE_GET_INPUT_REPORT: if (USBHostHID_ApiGetReport(Appl_raw_report_buffer.Report_ID, 0, Appl_raw_report_buffer.ReportSize, Appl_raw_report_buffer.ReportData)) { // Host may be busy/error -- keep trying } else { App_State_Mouse_Keyboard = MOUSE_INPUT_REPORT_PENDING; } USBTasks(); break; case KEYBOARD_GET_INPUT_REPORT: if (USBHostHID_ApiGetReport(Appl_raw_report_buffer.Report_ID, Appl_ModifierKeysDetails.interfaceNum, Appl_raw_report_buffer.ReportSize, Appl_raw_report_buffer.ReportData)) { /* Host may be busy/error -- keep trying */ } else { App_State_Mouse_Keyboard = KEYBOARD_INPUT_REPORT_PENDING; } USBTasks(); break; case MOUSE_INPUT_REPORT_PENDING: if (USBHostHID_ApiTransferIsComplete(&ErrorDriver, &NumOfBytesRcvd)) { if (ErrorDriver || (NumOfBytesRcvd != Appl_raw_report_buffer.ReportSize)) { ErrorCounter++; if (MAX_ERROR_COUNTER <= ErrorDriver) App_State_Mouse_Keyboard = ERROR_REPORTED; else App_State_Mouse_Keyboard = MOUSE_READY_TO_TX_RX_REPORT; } else { ErrorCounter = 0; ReportBufferUpdated = TRUE; App_State_Mouse_Keyboard = MOUSE_READY_TO_TX_RX_REPORT; if (DisplayConnectOnce == TRUE) { for (i = 0; i < Appl_raw_report_buffer.ReportSize; i++) { if (Appl_raw_report_buffer.ReportData[i] != 0) { DisplayConnectOnce = FALSE; } } } App_ProcessInputReport_Mouse(); } } break; case KEYBOARD_INPUT_REPORT_PENDING: if (USBHostHID_ApiTransferIsComplete(&ErrorDriver, &NumOfBytesRcvd)) { if (ErrorDriver || (NumOfBytesRcvd != Appl_raw_report_buffer.ReportSize)) { ErrorCounter++; if (MAX_ERROR_COUNTER <= ErrorDriver) { App_State_Mouse_Keyboard = ERROR_REPORTED; } else { App_State_Mouse_Keyboard = KEYBOARD_READY_TO_TX_RX_REPORT; } } else { ErrorCounter = 0; ReportBufferUpdated = TRUE; App_State_Mouse_Keyboard = KEYBOARD_READY_TO_TX_RX_REPORT; if (DisplayConnectOnce == TRUE) { for (i = 0; i < Appl_raw_report_buffer.ReportSize; i++) { if (Appl_raw_report_buffer.ReportData[i] != 0) { DisplayConnectOnce = FALSE; } } } App_ProcessInputReport_Keyboard(); App_PrepareOutputReport(); } } break; case SEND_OUTPUT_REPORT: /* Will be done while implementing Keyboard */ if (USBHostHID_ApiSendReport(Appl_LED_Indicator.reportID, Appl_LED_Indicator.interfaceNum, Appl_LED_Indicator.reportLength, (BYTE*) & Appl_led_report_buffer)) { /* Host may be busy/error -- keep trying */ } else { App_State_Mouse_Keyboard = OUTPUT_REPORT_PENDING; } USBTasks(); break; case OUTPUT_REPORT_PENDING: if (USBHostHID_ApiTransferIsComplete(&ErrorDriver, &NumOfBytesRcvd)) { if (ErrorDriver) { ErrorCounter++; if (MAX_ERROR_COUNTER <= ErrorDriver) App_State_Mouse_Keyboard = ERROR_REPORTED; } else { ErrorCounter = 0; App_State_Mouse_Keyboard = KEYBOARD_READY_TO_TX_RX_REPORT; } } break; case ERROR_REPORTED: break; default: break; } }
/****************************************************************************** * Function: void main(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: Main program entry point. * * Note: None *****************************************************************************/ void main(void) { //do some startup tasks... InitializeSystem(); //small delay for things to cook up for (b=0;b<1026;b++) { Delay1KTCYx(1); } //start I2C system at 100 Khz speed initi2c(); //board default configuration registers are changed here //make changed to loafconfigfriendly for a more friendly version loadconfig(); // //setup your IO configuration // // NOTE: you should change this 1st before anything else // this allows you to change ports to input, output, or analog // this function is in user.c // loadconfigfriendly(); for (c=0;c<10;c++) { //small delay for things to cook up for (b=0;b<1036;b++) { Delay1KTCYx(10); } } //start the USART module at 57600 buad rate startUsart(200000); //small delay for things to cook up for (b=0;b<1026;b++) { Delay1KTCYx(10); } //test xbee module at given baudrate of 57600 if (testxbee()) { //57600 baud failed so lets test to see if its a new module //start the USART module at 9600 buad rate startUsart(9600); //small delay for things to cook up for (b=0;b<1060;b++) { Delay1KTCYx(1); } //testing xbee at 9600 baudrate if (testxbee()) { //LOOP FOR NO XBEE MODULE FOUND (FAILED AT BOTH BAUDRATES) //xbee module failed at 9600 baud so no module present at either baudrate //new modules come with a 9600 baud rate by default. // //this is the no module operating code in here, put what you want when no module present //can use as a regular controller or PLC. // // NO XBEE MODULE FOUND MAIN LOOP STARTS HERE // mInitializeUSBDriver(); for(c=0;c<60;c++) { for (b=0;b<1060;b++) { Delay1KTCYx(1); USBTasks(); ProcessIO(); } } while(1) { //small delay so dont roast the USB system too much Delay1KTCYx(10); //USB polling tasks optional for (b=0;b<1060;b++) { Delay1KTCYx(1); USBTasks(); ProcessIO(); } // // NO XBEE MODULE FOUND MAIN LOOP ENDS HERE // } //end no xbee found main loop //END LOOP } //found module at 9600 baud rate // //now we will change the baud rate to 57600 in the module to speed things up else { //small delay for things to cook up for (b=0;b<1060;b++) { Delay1KTCYx(20); } //change xbee module to 57600 baud rate changebaudrate(); //start the USART module at 57600 buad rate startUsart(200000); for (c=0;c<30;c++) { //small delay for things to cook up for (b=0;b<3000;b++) { Delay1KTCYx(1); } } //initialize xbee module to the paramters specified in the following function // // NOTE: you need to edit this function to tailor this node's network parameters and such // this function is found in user.c // initxbee(); } } //found xbee module at 57600 baud rate else { //initialize xbee module to the paramters specified in the following function // // NOTE: you need to edit this function to tailor this node's network parameters and such // this function is found in user.c // //small delay for things to cook up for (b=0;b<1026;b++) { Delay1KTCYx(10); } initxbee(); } //configure xbee sleep mode here but it is not written to non volatile memory //since may have problems re-entering command mode later on!! //sleep_config_xbee(); //put xbee to not pin sleep xbee_sleep=0; //put module to not sleep!! (edge triggeered wakeup) //shutoff USB module to save 8 mA current //...uncomment to turn module off // UCONbits.USBEN=0; // UCONbits.SUSPND=1; //uncomment to turn USB on mInitializeUSBDriver(); //end usb turn on for(c=0;c<40;c++) { for (b=0;b<1060;b++) { Delay1KTCYx(1); USBTasks(); ProcessIO(); } } // set processor primary idle mode (not sleep!!) // OSCCONbits.IDLEN=1; //start timer 1 to time periodic functions starttimer(); //start USART receive interrupt PIE1bits.RCIE=1; //MAIN LOOP FOR XBEE MODULE NORMAL // // START MAIN LOOP FOR XBEE MODULE FOUND AT 200 K BAUD AND INTIALIZED TO YOUR PARAMETERS // while(1) { //loop to service USB requests (polling) for (b=0;b<1060;b++) { Delay1KTCYx(1); //service USB tasks USBTasks(); ProcessIO(); } }//end while // // END MAIN LOOP FOR XBEE MODULE FOUND AT 57600 BAUD AND INITIALIZED TO YOUR PARAMETERS // //END LOOP }//end main
static void file_flash(FSFILE* file) { UINT readBytes; UINT i; // Erase Flash (Block Erase the program Flash) if (NVMemBlockErase() != 0) { error(ERR_NV_ERASE); } record.status = REC_NOT_FOUND; // Initialize the state-machine to read the records. while (1) { USBTasks(); BlinkBlueLED(); BlinkOrangeLED(); // For a faster read, fetch 512 bytes at a time and buffer it. readBytes = FSfread((void*)&asciiBuffer[pointer], 1, 512, file); if (readBytes == 0) { // Nothing to read. Come out of this loop // break; // Jump to start of application // Disable all enabled interrupts (only USB) // before jumping to the application code. IEC5bits.USB1IE = 0; // JumpToApp(); return; } for (i = 0; i < (readBytes + pointer); i ++) { // This state machine seperates-out the valid hex records from the read 512 bytes. switch (record.status) { case REC_FLASHED: case REC_NOT_FOUND: if (asciiBuffer[i] == ':') { // We have a record found in the 512 bytes of data in the buffer. record.start = &asciiBuffer[i]; record.len = 0; record.status = REC_FOUND_BUT_NOT_FLASHED; } break; case REC_FOUND_BUT_NOT_FLASHED: if ((asciiBuffer[i] == 0x0A) || (asciiBuffer[i] == 0xFF)) { // We have got a complete record. (0x0A is new line feed and 0xFF is End of file) // Start the hex conversion from element // 1. This will discard the ':' which is // the start of the hex record. ConvertAsciiToHex(&record.start[1], hexRec); WriteHexRecord2Flash(hexRec); record.status = REC_FLASHED; } break; } record.len ++; // Move to next byte in the buffer. } if (record.status == REC_FOUND_BUT_NOT_FLASHED) { // We still have a half read record in the buffer. The next half part of the record is read // when we read 512 bytes of data from the next file read. memcpy(asciiBuffer, record.start, record.len); pointer = record.len; record.status = REC_NOT_FOUND; } else { pointer = 0; } } }
/**************************************************************************** Function: BOOT_LOADER_RETURN_CODES EnterBootLoaderMode(void* handle) Description: This routine is the main state machine for the bootloader. Precondition: The device is attached and has been detected. Parameters: void* handle - A generic pointer to the attached device Returns: BOOT_SUCCESS - Device has been successfully Booted (may still have a validation error, though) BOOT_DEVICE_DETACHED - Device has been detached before Bootloading finished BOOT_UNKNOWN_ERROR - An unknown error occurred with USB transfers ***************************************************************************/ BOOT_LOADER_RETURN_CODES EnterBootLoaderMode(void* handle) { BYTE errorCode; DWORD size; DWORD_VAL status; BOOT_LOADER_STATE state = BOOT_START; // Device was attached when this function was called device_attached = TRUE; // Run loop while(1) { //Keep the USB stack running USBTasks(); // Return, if the device has been detached if(device_attached == FALSE) { return BOOT_DEVICE_DETACHED; } // Bootloader state machine switch(state) { case BOOT_START: // Try to read from the attached Android device if(AndroidAppRead(handle, data, sizeof(data)) != USB_SUCCESS) { state = BOOT_ERROR; // update state to error, if unsuccessful } else { state = BOOT_ENTER_WAIT; // Otherwise, wait until read is complete } break; case BOOT_ENTER_WAIT: // If read from Android device is complete if(AndroidAppIsReadComplete(handle, &errorCode, &size) == TRUE) { // Then check to see if there was an error if(errorCode != USB_SUCCESS) { state = BOOT_ERROR; // Update state to error if there was an error } else { // Otherwise check the first byte in the packet to see if it was START_BOOT_REQ if(data[0] != START_BOOT_REQ) { state = BOOT_ERROR; // If not, then an error occurred } else { state = READ_FILE_REQ_SEND; // If so, then update state to send READ_FILE_REQ } } } break; case READ_FILE_REQ_SEND: // Set the first byte of the packet to READ_FILE_REQ data[0] = READ_FILE_REQ; // And send packet to the Android device if(AndroidAppWrite(handle, data, 1) != USB_SUCCESS) { state = BOOT_ERROR; // If unsuccessful, then update state to error } else { state = READ_FILE_REQ_WAIT; // Otherwise wait until write is complete } break; case READ_FILE_REQ_WAIT: // If the write is complete if(AndroidAppIsWriteComplete(handle, &errorCode, &size) == TRUE) { // Then check for errors if(errorCode != USB_SUCCESS) { state = BOOT_ERROR; // If there was an error, update state to error } else { state = READING_DATA; // Otherwise start reading data that contains flash update } } break; case READING_DATA: // Try to read enough to fill the buffer if(AndroidAppRead(handle, data, sizeof(data)) != USB_SUCCESS) { state = BOOT_ERROR; // Update state to error if unsuccessful } else { state = READING_DATA_WAIT; // Otherwise wait until the read is successful } break; case READING_DATA_WAIT: // If the read was successful if(AndroidAppIsReadComplete(handle, &errorCode, &size) == TRUE) { // Then check to see if there were any errors if(errorCode != USB_SUCCESS) { state = BOOT_ERROR; // If so, then update state to error } else { state = FLASHING_DATA; // Otherwise start re-flashing the new data into program memory } } break; case FLASHING_DATA: // Write the data from the buffer to program memory status.Val = CustomBinWrite(data,size); // If there is more to read from the Android device if(status.Val == DONE_WRITING_BUFFER) { state = READING_DATA; // Then update state to reading data } else { state = LOAD_COMPLETE_RSP_SEND; // Otherwise update state to send load complete response } break; case LOAD_COMPLETE_RSP_SEND: // Write LOAD_COMPLETE_RSP command to first byte, and status of the write to the rest of the packet data[0] = LOAD_COMPLETE_RSP; data[1] = status.byte.MB; data[2] = status.byte.UB; data[3] = status.byte.HB; data[4] = status.byte.LB; // Send to Android device if(AndroidAppWrite(handle, data, 5) != USB_SUCCESS) { state = BOOT_ERROR; // If there are any errors, update state to error } else { state = LOAD_COMPLETE_RSP_WAIT; // Otherwise, wait until write is complete } break; case LOAD_COMPLETE_RSP_WAIT: // If the write is finished if(AndroidAppIsWriteComplete(handle, &errorCode, &size) == TRUE) { // Then check for errors if(errorCode != USB_SUCCESS) { state = BOOT_ERROR; // If there was an error, update state to error } else { return BOOT_SUCCESS; // Otherwise return with BOOT_SUCCESS } } break; case BOOT_ERROR: // If there was an error, then return BOOT_UNKNOWN_ERROR return BOOT_UNKNOWN_ERROR; break; } //switch } //while(1) return BOOT_UNKNOWN_ERROR; }
/**************************************************************************** Function: int main(void) Summary: main function Description: main function Precondition: None Parameters: None Return Values: int - exit code for main function Remarks: None ***************************************************************************/ int main(void) { DWORD size = 0; BOOL responseNeeded; BYTE mode = 0; BYTE wasMode = 0; BYTE pushButtonValues = 0xFF; BYTE potPercentage = 0xFF; BOOL buttonsNeedUpdate = FALSE; BOOL potNeedsUpdate = FALSE; BOOL motorON = FALSE; BOOL readyToRead = TRUE; BOOL writeInProgress = FALSE; BYTE tempValue = 0xFF; BYTE errorCode; ACCESSORY_APP_PACKET* command_packet = NULL; CLKDIV = 0; /* set for default clock operations Fcyc = 4MHz */ AD1PCFGL = 0xffff; AD1PCFGH = 0x0003; BOOL connected_to_app = FALSE; BOOL need_to_disconnect_from_app = FALSE; #if defined(__PIC32MX__) InitPIC32(); #endif #if defined(__dsPIC33EP512MU810__) || defined (__PIC24EP512GU810__) // Configure the device PLL to obtain 60 MIPS operation. The crystal // frequency is 8MHz. Divide 8MHz by 2, multiply by 60 and divide by // 2. This results in Fosc of 120MHz. The CPU clock frequency is // Fcy = Fosc/2 = 60MHz. Wait for the Primary PLL to lock and then // configure the auxilliary PLL to provide 48MHz needed for USB // Operation. PLLFBD = 38; /* M = 60 */ CLKDIVbits.PLLPOST = 0; /* N1 = 2 */ CLKDIVbits.PLLPRE = 0; /* N2 = 2 */ OSCTUN = 0; /* Initiate Clock Switch to Primary * Oscillator with PLL (NOSC= 0x3)*/ __builtin_write_OSCCONH(0x03); __builtin_write_OSCCONL(0x01); while (OSCCONbits.COSC != 0x3); // Configuring the auxiliary PLL, since the primary // oscillator provides the source clock to the auxiliary // PLL, the auxiliary oscillator is disabled. Note that // the AUX PLL is enabled. The input 8MHz clock is divided // by 2, multiplied by 24 and then divided by 2. Wait till // the AUX PLL locks. ACLKCON3 = 0x24C1; ACLKDIV3 = 0x7; ACLKCON3bits.ENAPLL = 1; while(ACLKCON3bits.APLLCK != 1); TRISBbits.TRISB5 = 0; LATBbits.LATB5 = 1; #endif USBInitialize(0); AndroidAppStart(&myDeviceInfo); responseNeeded = FALSE; mInitPOT(); InitializeTimer2For_PWM(); PwmInit(); //InitMOTOR(); DEBUG_Init(0); InitAllLEDs(); while(1) { //Keep the USB stack running USBTasks(); //If the device isn't attached yet, if(device_attached == FALSE || mode == 1) { buttonsNeedUpdate = TRUE; potNeedsUpdate = TRUE; need_to_disconnect_from_app = FALSE; connected_to_app = FALSE; size = 0; /**/ BYTE curPush = GetPushbuttons(); if ((curPush == 0x8) || (mode == 1)) { LED0_On(); mode = 1; if (wasMode == 0) { pot2LEDs(); PwmInit(); } tempValue = ReadPOT(); wasMode = 1; //If it is different than the last time we read the pot, then we need // to send it to the Android device if(tempValue != potPercentage) { potNeedsUpdate = TRUE; //setRPM(tempValue); setPWM(); } } if ((curPush == 0x4) || (mode == 0)) { mode = 0; //LED0_Off(); if (wasMode == 1) { SetLEDs(0b00000000); wasMode = 0; setRPM(0); } //Reset the accessory state variables InitAllLEDs(); //Continue to the top of the while loop to start the check over again. continue; } /* //Reset the accessory state variables InitAllLEDs(); //Continue to the top of the while loop to start the check over again. continue; }*/ //} } //If the accessory is ready, then this is where we run all of the demo code if(readyToRead == TRUE && mode == 0) { errorCode = AndroidAppRead(device_handle, (BYTE*)&read_buffer, (DWORD)sizeof(read_buffer)); //If the device is attached, then lets wait for a command from the application if( errorCode != USB_SUCCESS) { //Error DEBUG_PrintString("Error trying to start read"); } else { readyToRead = FALSE; } } size = 0; if(AndroidAppIsReadComplete(device_handle, &errorCode, &size) == TRUE) { //We've received a command over the USB from the Android device. if(errorCode == USB_SUCCESS) { //Maybe process the data here. Maybe process it somewhere else. command_packet = (ACCESSORY_APP_PACKET*)&read_buffer[0]; } else { //Error DEBUG_PrintString("Error trying to complete read request"); } } while(size > 0) { if(connected_to_app == FALSE) { if(command_packet->command == COMMAND_APP_CONNECT) { connected_to_app = TRUE; need_to_disconnect_from_app = FALSE; } } else { switch(command_packet->command) { case COMMAND_SET_LEDS: SetLEDs(command_packet->data); break; case COMMAND_APP_DISCONNECT: need_to_disconnect_from_app = TRUE; break; case COMMAND_SET_PWM: setRPM(command_packet->data); break; default: //Error, unknown command DEBUG_PrintString("Error: unknown command received"); break; } } //All commands in this example are two bytes, so remove that from the queue size -= 2; //And move the pointer to the next packet (this works because // all command packets are 2 bytes. If variable packet size // then need to handle moving the pointer by the size of the // command type that arrived. command_packet++; if(need_to_disconnect_from_app == TRUE) { break; } } if(size == 0) { readyToRead = TRUE; } //Get the current pushbutton settings tempValue = GetPushbuttons(); //If the current button settings are different than the last time // we read the button values, then we need to send an update to the // attached Android device if(tempValue != pushButtonValues) { buttonsNeedUpdate = TRUE; pushButtonValues = tempValue; } //Get the current potentiometer setting tempValue = ReadPOT(); //If it is different than the last time we read the pot, then we need // to send it to the Android device if(tempValue != potPercentage) { potNeedsUpdate = TRUE; potPercentage = tempValue; } //If there is a write already in progress, we need to check its status if( writeInProgress == TRUE ) { if(AndroidAppIsWriteComplete(device_handle, &errorCode, &size) == TRUE) { writeInProgress = FALSE; if(need_to_disconnect_from_app == TRUE) { connected_to_app = FALSE; need_to_disconnect_from_app = FALSE; } if(errorCode != USB_SUCCESS) { //Error DEBUG_PrintString("Error trying to complete write"); } } } if((need_to_disconnect_from_app == TRUE) && (writeInProgress == FALSE)) { outgoing_packet.command = COMMAND_APP_DISCONNECT; outgoing_packet.data = 0; writeInProgress = TRUE; errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2); if( errorCode != USB_SUCCESS ) { DEBUG_PrintString("Error trying to send button update"); } } if(connected_to_app == FALSE) { //If the app hasn't told us to start sending data, let's not do anything else. continue; } //If we need up update the button status on the Android device and we aren't // already busy in a write, then we can send the new button data. if((buttonsNeedUpdate == TRUE) && (writeInProgress == FALSE)) { outgoing_packet.command = COMMAND_UPDATE_PUSHBUTTONS; outgoing_packet.data = pushButtonValues; errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2); if( errorCode != USB_SUCCESS ) { DEBUG_PrintString("Error trying to send button update"); } buttonsNeedUpdate = FALSE; writeInProgress = TRUE; } //If we need up update the pot status on the Android device and we aren't // already busy in a write, then we can send the new pot data. if((potNeedsUpdate == TRUE) && (writeInProgress == FALSE)) { outgoing_packet.command = COMMAND_UPDATE_POT; outgoing_packet.data = potPercentage; errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2); if( errorCode != USB_SUCCESS ) { DEBUG_PrintString("Error trying to send pot update"); } potNeedsUpdate = FALSE; writeInProgress = TRUE; } } //while(1) main loop }
/****************************************************************************** * Function: void UninitializedMain(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This is the main function for this bootloader mode firmware. * if execution gets to this function, it is assumed that we * want to stay in bootloader mode for now. * * Note: If adding code to this function, make sure to add it only * after the C initializer like code at the top of this function. *****************************************************************************/ void BootMain(void) { //NOTE: The c018.o file is not included in the linker script for this project. //The C initialization code in the c018.c (comes with C18 compiler in the src directory) //file is instead modified and included here manually. This is done so as to provide //a more convenient entry method into the bootloader firmware. Ordinarily the _entry_scn //program code section starts at 0x00 and is created by the code of c018.o. However, //the linker will not work if there is more than one section of code trying to occupy 0x00. //Therefore, must not use the c018.o code, must instead manually include the useful code //here instead. //Make sure interrupts are disabled for this code (could still be on, //if the application firmware jumped into the bootloader via software methods) INTCON = 0x00; // Initialize the C stack pointer, and other compiler managed items as normally done in the c018.c file. _asm lfsr 1, _stack lfsr 2, _stack clrf TBLPTRU, 0 _endasm //Clear the stack pointer, in case the user application jumped into //bootloader mode with excessive junk on the call stack STKPTR = 0x00; // End of the important parts of the C initializer. This bootloader firmware does not use // any C initialized user variables (idata memory sections). Therefore, the above is all // the initialization that is required. //Check if the USB module is already enabled. If so, disable it and wait //~100ms+ (>1 second recommended if CDC application firmware on XP), to //ensure that the host has a chance to see and process the USB device detach //event. if(UCONbits.USBEN == 1) { //USB module was already on. This is likely because the user applicaiton //firmware jumped into this bootloader firmware using the absolute //software entry method, without first turning off the USB module DisableUSBandExecuteLongDelay(); } //Call other initialization code and (re)enable the USB module InitializeSystem(); //Some USB, I/O pins, and other initialization //Execute main loop while(1) { ClrWdt(); //Need to call USBTasks() periodically. This function takes care of //processing non-USB application related USB packets (ex: "Chapter 9" //packets associated with USB enumeration) USBTasks(); BlinkUSBStatus(); //When enabled, blinks LEDs on the board, based on USB bus state LowVoltageCheck(); //Regularly monitor voltage to make sure it is sufficient //for safe operation at full frequency and for erase/write //operations. //Checks for and processes application related USB packets (assuming the //USB bus is in the CONFIGURED_STATE, which is the only state where //the host is allowed to send application related USB packets to the device. if((usb_device_state == CONFIGURED_STATE) && (UCONbits.SUSPND != 1)) { ProcessIO(); // This is where all the actual bootloader related data transfer/self programming takes place } // see ProcessIO() function in the BootPIC[xxxx].c file. }//end while }
int main(void) { int value; int junk; millisec = 0; value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() ); // Enable the cache for the best performance CheKseg0CacheOn(); //Setupt input for inteface button JF8 (RA01) (0x02) TRISASET = 0x02; //RED LED - JF9 (RA04) (0x10) TRISACLR = 0x10; ODCACLR = 0x10; LATASET = 0x10; //Green LED -JF7 (RE9) (0x200) TRISECLR = 0x200; ODCECLR = 0x200; LATESET = 0x200; //Setupt Input for DataFlag Button - JF10 - RA5 0x20 TRISASET = 0x20; //Setup Output for Clutch Hold (Launch) JE1 RD14 0x4000 //This function is active low, driving the FET on the PDU TRISDCLR = 0x4000; ODCDCLR = 0x4000; LATDSET = 0x4000; //Default state is high (off) CAN1Init();//CAN1 ACCL 500kbs CAN2Init();//Motec 1mbs DelayInit(); initUART2(); // GPS UART prevButton1 = 0; prevButton2 = 0; millisec = 0; // Configure Timer 2 to request a real-time interrupt once per millisecond. // The period of Timer 2 is (16 * 5000)/(80 MHz) = 1 ms. OpenTimer2(T2_ON | T2_IDLE_CON | T2_SOURCE_INT | T2_PS_1_16 | T2_GATE_OFF, 5000); // Configure the CPU to respond to Timer 2's interrupt requests. INTEnableSystemMultiVectoredInt(); INTSetVectorPriority(INT_TIMER_2_VECTOR, INT_PRIORITY_LEVEL_2); INTClearFlag(INT_T2); INTEnable(INT_T2, INT_ENABLED); //UART GPS Interrupts INTSetVectorPriority(INT_UART_2_VECTOR ,INT_PRIORITY_LEVEL_1); //Make sure UART interrupt is top priority INTClearFlag(INT_U2RX); INTEnable(INT_U2RX, INT_ENABLED); value = OSCCON; while (!(value & 0x00000020)) { value = OSCCON; // Wait for PLL lock to stabilize } deviceAttached = FALSE; //Initialize the stack USBInitialize(0); shouldLog = FALSE; shouldStop = FALSE; //count = 0; angularRateInfoRec = FALSE; accelerationSensorRec = FALSE; HRaccelerationSensorRec = FALSE; //init tim er 3 to convert adc at 100hz OpenTimer3(T3_ON|T3_PS_1_256|T3_SOURCE_INT, 1562); //initialize i2c for the psoc initI2CPSoC(); state = wait; logNum = 0; initI2CEEPROM(); short addy = 0x0000; BYTE num = 0x00; logNum = readEEPROM(addy); if(logNum >= 0xEF) //Address stored in EEPROM if greater than 0xEF reset to zero, limited to a single byte with current code configuration { writeEEPROM(addy, 0x00); } char GroupString[550];//Group Names (Line1) char UnitString[550];//Units (line2) char ParamString[650];//Paramater Names (line3) sprintf(GroupString,"Time,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Drivetrain,Drivetrain,Electrical,Drivetrain,Drivetrain,Drivetrain,Drivetrain,Engine,Engine,Engine,Engine,Electrical,Electrical,Electrical,Electrical,Electrical,Electrical,Suspension,Suspension,Suspension,Suspension,Suspension,Drivetrain,Driver\n"); sprintf(UnitString,"ms,deg/s,deg/s,deg/s,m/s^2,m/s^2,m/s^2,m/s^2,m/s^2,m/s^2,rpm,%,kpa,degF,degF,lambda,psi,degF,na,na,psi,psi,V,mph,mph,mph,mph,s,gal,degF,degBTDC,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,\n"); sprintf(ParamString, "Millisec,pitch(deg/sec),roll(deg/sec),yaw(deg/sec),lat(m/s^2),long(m/s^2),vert(m/s^2),latHR(m/s^2),longHR(m/s^2),vertHR(m/s^2),rpm,tps(percent),MAP(kpa),AT(degF),ect(degF),lambda,fuel pres,egt(degF),launch,neutral,brake pres,brake pres filtered,BattVolt(V),ld speed(mph), lg speed(mph),rd speed(mph),rg speed(mph),run time(s),fuel used,Oil Temp (deg F), Ignition Adv (degBTDC),Overall Consumption(mV),Overall Production(mV),Fuel Pump(mV),Fuel Injector(mV),Ignition(mV),Vref(mV),Back Left(mV),Back Right(mV),Front Left(mV),Front Right(mV),Steering Angle(mV),Brake Temp(mV),Data Flag,GPRMC,Time,Valid,Lat,N/S,Long,E/W,Speed,Course,Date,Variation,E/W\n"); LATACLR = 0x10; //Turn on Red LED // LATECLR = 0x200; UARTSendString(UART2,PMTK_HOT_RESTART); int i = 0; while(!UARTTransmissionHasCompleted(UART2)){ i++; } while(1) { GPSDataRead(); GPSSentenceParse(); ClutchHold(); //This function handles the venting direction of the clutch actuator DataFlagFunc(); //This function handles the updates of the data flag variable //USB stack process function USBTasks(); switch(state){ case wait: USBTasks(); millisec = 0; if(CheckLogStateChange() == 1){ //start the transition from wait to log state = startLog; } break; case startLog: //if thumbdrive is plugged in if(USBHostMSDSCSIMediaDetect()) { deviceAttached = TRUE; //now a device is attached //See if the device is attached and in the right format if(FSInit()) { //Opening a file in mode "w" will create the file if it doesn't // exist. If the file does exist it will delete the old file // and create a new one that is blank. logNum = readEEPROM(addy); sprintf(nameString, "test%d.csv", logNum); myFile = FSfopen(nameString,"w"); FSfwrite(GroupString,1,strlen(GroupString),myFile); FSfwrite(UnitString,1,strlen(UnitString),myFile); FSfwrite(ParamString,1, strlen(ParamString),myFile); millisec = 0; //LATDSET = 0x4000; //Send sync pulse (aeroprobe) // while(millisec < 1000){} //Wait 1s then move to log, the aeroprobe ADC waits 1s. state = log; LATECLR = 0x200; //Turn on Green LATASET = 0x10; //Turn off Red } } break; case log: //This uses MOTEC as the master timer. Data is only written to the USB after all the motec Data is received if(motec0Read && motec1Read && motec2Read && motec3Read && motec4Read && motec5Read){ WriteToUSB(); } else{}//Wait for motec data to write the next row if(CheckLogStateChange() == 2){ //Start the transition from log to wait state = stopLog; } if(millisec > 2000){ LATDCLR = 0x4000; //After 2 seconds pass no need to keep output high } //Add a function to check for a flag button and set a variable break; case stopLog: //Always make sure to close the file so that the data gets written to the drive. FSfwrite("endFile", 1, 7, myFile); FSfclose(myFile); state = wait; logNum++; writeEEPROM(addy, logNum); LATACLR = 0x10; //Turn on Red LATESET = 0x200; //Turn off Green break; default: state = wait; break; } //CAN Handlers CANRxMessageBuffer* CAN1RxMessage = CAN1RxMsgProcess(); if(CAN1RxMessage){ WriteAccelData(CAN1RxMessage); //Accel is on CAN 1 } CANRxMessageBuffer* CAN2RxMessage = CAN2RxMsgProcess(); if(CAN2RxMessage){ writeCan2Msg(CAN2RxMessage); //Motec is on CAN 2 } } return 0; }
//****************************************************************************** //****************************************************************************** // Main //****************************************************************************** //****************************************************************************** int main (void) { BYTE i; DWORD temp; int value; value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() ); mJTAGPortEnable(DEBUG_JTAGPORT_OFF); // Enable the cache for the best performance CheKseg0CacheOn(); value = OSCCON; while (!(value & 0x00000020)) { value = OSCCON; // Wait for PLL lock to stabilize } InitKeyboardDriver(); INTEnableSystemMultiVectoredInt(); // Init status LED mPORTCSetBits(BIT_0); mPORTCSetPinsDigitalOut(BIT_0); //DBINIT(); // Initialize USB layers USBInitialize(0); while (1) { USBTasks(); App_Detect_Device(); switch (App_State_Keyboard) { case DEVICE_NOT_CONNECTED: mPORTCSetBits(BIT_0); USBTasks(); if (DisplayDeatachOnce == FALSE) { DBPRINTF("Device Detached\n"); DisplayDeatachOnce = TRUE; } if (USBHostHID_ApiDeviceDetect()) /* True if report descriptor is parsed with no error */ { DBPRINTF("Device Attached\n"); App_State_Keyboard = DEVICE_CONNECTED; DisplayConnectOnce = FALSE; } break; case DEVICE_CONNECTED: mPORTCClearBits(BIT_0); App_State_Keyboard = READY_TO_TX_RX_REPORT; if (DisplayConnectOnce == FALSE) { DisplayConnectOnce = TRUE; DisplayDeatachOnce = FALSE; } InitializeTimer(); // start 10ms timer to schedule input reports break; case READY_TO_TX_RX_REPORT: if (!USBHostHID_ApiDeviceDetect()) { App_State_Keyboard = DEVICE_NOT_CONNECTED; // DisplayOnce = FALSE; } break; case GET_INPUT_REPORT: if (USBHostHID_ApiGetReport(Appl_raw_report_buffer.Report_ID, Appl_ModifierKeysDetails.interfaceNum, Appl_raw_report_buffer.ReportSize, Appl_raw_report_buffer.ReportData)) { /* Host may be busy/error -- keep trying */ } else { App_State_Keyboard = INPUT_REPORT_PENDING; } USBTasks(); break; case INPUT_REPORT_PENDING: if (USBHostHID_ApiTransferIsComplete(&ErrorDriver, &NumOfBytesRcvd)) { if (ErrorDriver || (NumOfBytesRcvd != Appl_raw_report_buffer.ReportSize )) { ErrorCounter++ ; if (MAX_ERROR_COUNTER <= ErrorDriver) App_State_Keyboard = ERROR_REPORTED; else App_State_Keyboard = READY_TO_TX_RX_REPORT; } else { ErrorCounter = 0; ReportBufferUpdated = TRUE; App_State_Keyboard = READY_TO_TX_RX_REPORT; if (DisplayConnectOnce == TRUE) { for (i = 0; i < Appl_raw_report_buffer.ReportSize; i++) { if (Appl_raw_report_buffer.ReportData[i] != 0) { //LCDClear(); //LCDL1Home(); DisplayConnectOnce = FALSE; } } } App_ProcessInputReport(); App_PrepareOutputReport(); } } break; case SEND_OUTPUT_REPORT: /* Will be done while implementing Keyboard */ if (USBHostHID_ApiSendReport(Appl_LED_Indicator.reportID, Appl_LED_Indicator.interfaceNum, Appl_LED_Indicator.reportLength, (BYTE*) & Appl_led_report_buffer)) { /* Host may be busy/error -- keep trying */ } else { App_State_Keyboard = OUTPUT_REPORT_PENDING; } USBTasks(); break; case OUTPUT_REPORT_PENDING: if (USBHostHID_ApiTransferIsComplete(&ErrorDriver, &NumOfBytesRcvd)) { if (ErrorDriver) { ErrorCounter++ ; if (MAX_ERROR_COUNTER <= ErrorDriver) App_State_Keyboard = ERROR_REPORTED; // App_State_Keyboard = READY_TO_TX_RX_REPORT; } else { ErrorCounter = 0; App_State_Keyboard = READY_TO_TX_RX_REPORT; } } break; case ERROR_REPORTED: break; default: break; } } }