Exemplo n.º 1
0
BOOL InitializeSystem ( void )
{

    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
    }

    // Init UART
    UART2Init();
    // Set Default demo state
    DemoState = DEMO_INITIALIZE;
	if(USBHostIsochronousBuffersCreate(&isocData,2,1024)){
    	UART2PrintString( "CreateIsochronousBuffers\r\n" );
	}else{
        UART2PrintString( "Fail:CreateIsochronousBuffers\r\n" );
	}

    return TRUE;
} // InitializeSystem
Exemplo n.º 2
0
Arquivo: main.c Projeto: 21rcc/ioio
int main() {
  ADB_FILE_HANDLE f;
  iPPSInput(IN_FN_PPS_U2RX,IN_PIN_PPS_RP2);       //Assign U2RX to pin RP2 (42)
  iPPSOutput(OUT_PIN_PPS_RP4,OUT_FN_PPS_U2TX);    //Assign U2TX to pin RP4 (43)
  UART2Init();

  UART2PrintString("***** Hello from app! *******\r\n");

  f = ADBFileRead("/data/data/ioio.manager/files/image.ioio", &FileCallback);
  UART2PrintString("***** file handle: ");
  UART2PutHexWord(f);
  UART2PrintString("*****\r\n");

  state = STATE_READ_FILE;
  
  while (state == STATE_READ_FILE) {
    BootloaderTasks();
  }
  

  // blink LED
  TRISFbits.TRISF3 = 0;
  while (1) {
    long i = 1000L;
    LATFbits.LATF3 = 0;
    while (i--);
    i = 1000000L;
    LATFbits.LATF3 = 1;
    while (i--);
    BootloaderTasks();
  }
}
Exemplo n.º 3
0
/*********************************************************************************************************
** 函数名称:  InitAllSP
** 函数功能:  对所有串口进行初始化
** 入口参数:  p_u32U2,p_u32U3,p_u32U5	串口2、3、5波特率
** 出口参数:  无
** 函数说明:  初始化网口
*********************************************************************************************************/
void InitAllSP(uint32 p_u32U2, uint32 p_u32U3, uint32 p_u32U5)
{								 
	UART2Init(p_u32U2);	//串口2
	UART3Init(p_u32U3);	//串口3
	UART5Init(p_u32U5);	//串口5
	UART1_Init();	  	//串口1波特率为57600

	memcpy(&g_sniLocal, (uint8 *)&SETUPALIAS.u32LocalIPAddress, sizeof(NetInfo)-2);

	InitializeW5100(&g_sniLocal);//
}
Exemplo n.º 4
0
/******************************************************************************
 * Function:        void InitializeUSART(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This routine initializes the UART to 19200
 *
 * Note:            
 *
 *****************************************************************************/
void InitializeUSART(void)
{
    #if defined(__18CXX)
	    unsigned char c;
        #if defined(__18F14K50)
    	    ANSELHbits.ANS11 = 0;	// Make RB5 digital so USART can use pin for Rx

        #endif
        UART_TRISRx=1;				// RX
        UART_TRISTx=0;				// TX
        TXSTA = 0x24;       	// TX enable BRGH=1
        RCSTA = 0x90;       	// Single Character RX
        SPBRG = 0x71;
        SPBRGH = 0x02;      	// 0x0271 for 48MHz -> 19200 baud
        BAUDCON = 0x08;     	// BRG16 = 1
        c = RCREG;				// read 
    #endif

    #if defined(__C30__) || defined __XC16__
        #if defined( __PIC24FJ256GB110__ )
            // PPS - Configure U2RX - put on pin 49 (RP10)
            RPINR19bits.U2RXR = 10;

            // PPS - Configure U2TX - put on pin 50 (RP17)
            RPOR8bits.RP17R = 5;
        #else
            #error Verify that any required PPPS is done here.
        #endif

        UART2Init();
    #endif

    #if defined(__C32__)
        UART2Init();
    #endif

}//end InitializeUSART
Exemplo n.º 5
0
/**
 * roombaの通信の初期化
 */
void roomba_init (void)
{
    // UARTのポートの割り付け
    InitUartPort ();
    // UARTモジュールの初期化
    UART2Init ();
    /* 受信割り込みの許可 */
    IEC1bits.U2RXIE=1;
    /* 送信割り込みの許可 */
    IEC1bits.U2TXIE=0;
    /* 受信割り込みレベルの設定 */
    IPC7bits.U2RXIP = 7;
    /* タイマの初期化 */
    timer1_init ();
}
Exemplo n.º 6
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
        case SYSTEM_STATE_USB_HOST:
            //PRINT_SetConfiguration(PRINT_CONFIGURATION_UART);
            //UART2Init();  //?timijk for DEBUGGING
            
            break;
            
        case SYSTEM_STATE_USB_HOST_HID_PICKIT:
            LED_Enable(LED_USB_HOST_HID_PICKIT_DEVICE_READY);

            //also setup UART here
            //PRINT_SetConfiguration(PRINT_CONFIGURATION_UART);
            //timijk 2015.04.11 LCD_CursorEnable(true);
            UART2Init();
            IEC1bits.U2RXIE= 1;  //enable RXIE
            
            TIMER_SetConfiguration(TIMER_CONFIGURATION_1MS);

            break;
    }
}
Exemplo n.º 7
0
int main (void)
{

   FSFILE * pointer=NULL;
   DWORD first_sector;
   BYTE test_array[512];
   SearchRec rec;
   pointer=NULL;
   unsigned char attributes;
   unsigned char size = 0, i;
   PLLFBD =38;
   CLKDIVbits.PLLPOST=0;
   CLKDIVbits.PLLPRE=0;
   __builtin_write_OSCCONH(0b011);
   __builtin_write_OSCCONL(0b01);
	while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur	
	while(OSCCONbits.LOCK != 1) {};
	UART2Init();
	printf("starting Integration test\r\n");
	//DataEEInit();
	int id=0;
	id=Get_ID_Code();
	printf("ID: %u\r\n",id);
	OFB_init(id);
	Increment_ID_Code();
	#ifdef __DEBUG
		printf("Clock Switch Complete, Waiting For Media\r\n");
	#endif
	//waits for a card to be inserted
   while (!MDD_MediaDetect());
	#ifdef __DEBUG
		printf("Media Found, Waiting for FSinit\r\n");
	#endif
   // Initialize the library
   while (!FSInit());
   char filename[9];
   sprintf(filename,"%05d.bin",id);
   // Create a file
   printf("filename will be: %s\r\n",filename);
   while(pointer==NULL)
   {
   		pointer = FSfopen (filename, "w");
   }
   #ifdef __DEBUG
   	printf("File Has been opened\r\n");
   #endif		
	
	while(1)
	{
		Service_Spi(pointer);
	}	
	//printf("stuipd thing");
	//TRISD=0x0FF;
	//setting up pins to show on usb debugger
	TRISDbits.TRISD6=1;
	TRISAbits.TRISA7=0;
	TRISAbits.TRISA6=0;
	TRISAbits.TRISA5=0;
	TRISAbits.TRISA4=0;
	TRISGbits.TRISG0=0;
	AD1PCFGLbits.PCFG0=1;	
	//LATA=1;
	//_LATA4=1;
	//_RA7=1;
	//_LATA6=1;
	
	//_LATA5=1;
	//_LATA7=1;
	
	//printf("they should be on now");
	//while(1);
	//LATAbits.LATA7=0;
	//TRISB=0xFFFF;
	//AD1PCFGLbits.PCFG1=1;	
	//Service_Spi();
	/*#ifdef __DEBUG
		printf("Clock Switch Complete, Waiting For Media\r\n");
	#endif
	//waits for a card to be inserted
   while (!MDD_MediaDetect());
   
   
	#ifdef __DEBUG
		printf("Media Found, Waiting for FSinit\r\n");
	#endif
   // Initialize the library
   while (!FSInit());
	char temp;
	int character_count,remove_success;
	character_count=0;
   // Create a file
   printf("starting up\r\n");
   remove_success=FSremove("WRITE.TXT");
   printf("Removal of prev: %d\r\n",remove_success);
   pointer = FSfopen ("WRITE.TXT", "w");

   if (pointer == NULL)
   {
	   #ifdef __DEBUG
	   	printf("File open failed\r\n");
	   #endif
      while(1);
   }   

   printf("waiting for operation\r\n");
   printf("in file resize_test\r\n");
   
   
   DWORD sizeinbytes;
   //need to convert from number of sectors to number of bytes and allocate that much space
   sizeinbytes=(DWORD)FILESIZE*(DWORD)512;
   printf("Chew Fat: %lu\r\nChew Fat Sectors: %d\r\n",CHEW_FAT_SIZE,CHEW_FAT_SIZE_IN_SECTORS);
   //sizeinbytes=3774873*(DWORD)512;
   //allocate_size(sizeinbytes,pointer,FALSE);
   //FSfclose(pointer);*/
   /*FILEallocate_multiple_clusters(pointer,24);
   FAT_print_cluster_chain(pointer->cluster, pointer->dsk);
   FILEallocate_multiple_clusters(pointer,24);
   FAT_print_cluster_chain(pointer->cluster, pointer->dsk);
   int numclus,numcount;
   //DWORD clusttemp;
   printf("First CLuster in main: %lu\r\n",get_First_Sector(pointer));
   for (numclus=0;numclus<48;numclus++)
   {
		for(numcount=0;numcount<512;numcount++)
		{
		   test_array[numcount]=numclus+48;
		}
		MDD_SDSPI_SectorWrite(get_First_Sector(pointer)+numclus,test_array,FALSE);
	}*/
   //FILEallocate_multiple_clusters(pointer,24);
   //FILEallocate_multiple_clusters(pointer,24);
   //FILEallocate_multiple_clusters(pointer,CHEW_FAT_SIZE_IN_SECTORS);
   //FSfclose(pointer);
   //FILEallocate_multiple_clusters(pointer,4096);
   //FSfclose(pointer);
   //FILEallocate_multiple_clusters(pointer,1024);
   //FILEallocate_multiple_clusters(pointer,1024);
   
   //FSfseek(pointer,0,SEEK_SET);
   first_sector=get_First_Sector(pointer);
   set_First_Sector(first_sector);
   DWORD erasure;
   OFB_init(0x1f1f);
   //FSfclose(pointer);
   //MDD_ShutdownMedia();
   printf("done with file allocation\r\n");
   #ifdef DMAON
   #else
   #endif
      
      //while(UART2IsEmpty());
      //temp=UART2GetChar();
      //write_array[character_count]=temp;
      //character_count++;
    while(1)
    {
	    Service_Spi(pointer);
	}
}
Exemplo n.º 8
0
void log_init() {
  iPPSOutput(OUT_PIN_PPS_RP28,OUT_FN_PPS_U2TX);  // U2TX to pin 32
  UART2Init();
}
Exemplo n.º 9
0
/******************************************************************************
 * Function:        void InitializeUSART(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This routine initializes the UART to 19200
 *
 * Note:            
 *
 *****************************************************************************/
void InitializeUSART(void)
{
    UART2Init();
}//end InitializeUSART
Exemplo n.º 10
0
BOOL InitializeSystem ( void )
{
    #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); 

        ANSELA = 0x0000;
        ANSELB = 0x0000;
        ANSELC = 0x0000;
        ANSELD = 0x0000;
        ANSELE = 0x0000;
        ANSELG = 0x0000;

        // The dsPIC33EP512MU810 features Peripheral Pin
        // select. The following statements map UART2 to 
        // device pins which would connect to the the 
        // RX232 transciever on the Explorer 16 board.

        RPINR19 = 0;
        RPINR19 = 0x64;
        RPOR9bits.RP101R = 0x3;

#endif
    
    #if defined( __PIC24FJ256GB110__ )
        // Configure U2RX - put on pin 49 (RP10)
        RPINR19bits.U2RXR = 10;

        // Configure U2TX - put on pin 50 (RP17)
        RPOR8bits.RP17R = 5;

        OSCCON = 0x3302;    // Enable secondary oscillator
        CLKDIV = 0x0000;    // Set PLL prescaler (1:1)

        TRISA = 0x0000;
        TRISD = 0x00C0;

   #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--);
    }

    #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
            }
        }
    #endif

    // Init LCD
    LCDInit();

    // Init LEDs
    mInitAllLEDs();
    mLED_9_Off();
    mLED_10_Off();

    // Init Switches
    //mInitAllSwitches();
    SwitchState = IOPORT_BIT_6|IOPORT_BIT_7;

    // Init UART
    UART2Init();

    // Set Default demo state
    DemoState = DEMO_INITIALIZE;

    return TRUE;
} // InitializeSystem
Exemplo n.º 11
0
// main
int main ( void )
{
	// Initialize the processor and peripherals.

	// Init Clock
	// CPU 32MHz
	// Peripheral 8MHz
    CLKDIV = 0x0000;
	unsigned int pll_startup_counter = 600;
	CLKDIVbits.PLLEN = 1;
	while(pll_startup_counter--);

	// Configure U2RX - put on pin 17 (RP8)
	RPINR19bits.U2RXR = 8;
	// Configure U2TX - put on pin 16 (RP7)
	RPOR3bits.RP7R = 5;

	// Analog IN Disable
	AD1PCFG = 0xffff;

	EnablePullUpCN12;
	// Port output setup
	mPORTBOutputConfig(0x8000);

	// Init UART
	UART2Init();

	// Init USB
	if ( USBHostInit(0) != TRUE )
    {
        UART2PrintString( "ERR USBHostInit\r\n" );
        while (1);
    }

	/// GET STARTED with BTstack ///
	btstack_memory_init();
    run_loop_init(RUN_LOOP_EMBEDDED);
	
    // init HCI
	hci_transport_t    * transport = hci_transport_usb_instance();
	bt_control_t       * control   = NULL;
    hci_uart_config_t  * config    = NULL;
    remote_device_db_t * remote_db = NULL;//(remote_device_db_t *) &remote_device_db_memory;
	hci_init(transport, config, control, remote_db);
    
    // init L2CAP
    l2cap_init();
    l2cap_register_packet_handler(bt_packet_handler);
    
    // init RFCOMM
    rfcomm_init();
    rfcomm_register_packet_handler(bt_packet_handler);
    rfcomm_register_service_internal(NULL, rfcomm_channel_nr, 100);  // reserved channel, mtu=100

    // init SDP, create record for SPP and register with SDP
    sdp_init();
	memset(spp_service_buffer, 0, sizeof(spp_service_buffer));
    service_record_item_t * service_record_item = (service_record_item_t *) spp_service_buffer;
    sdp_create_spp_service( (uint8_t*) &service_record_item->service_record, 1, "SPP");
//    printf("SDP service buffer size: %u\n\r", (uint16_t) (sizeof(service_record_item_t) + de_get_len((uint8_t*) &service_record_item->service_record)));
    sdp_register_service_internal(NULL, service_record_item);

	// usbhost 
	data_source_t usbhost;
	usbhost.process = &usbhost_process;
	run_loop_add_data_source(&usbhost);

	data_source_t swtask;
	swtask.process = &sw_process;
	run_loop_add_data_source(&swtask);

    // go!
    run_loop_execute();	

    return 0;
} // main
Exemplo n.º 12
0
BOOL InitializeSystem ( void )
{
    #if defined( __PIC24FJ256GB110__ )
        // Configure U2RX - put on pin 49 (RP10)
        RPINR19bits.U2RXR = 10;

        // Configure U2TX - put on pin 50 (RP17)
        RPOR8bits.RP17R = 5;

        OSCCON = 0x3302;    // Enable secondary oscillator
        CLKDIV = 0x0000;    // Set PLL prescaler (1:1)

        TRISA = 0x0000;
        TRISD = 0x00C0;

   #elif defined( __PIC24FJ256GB106__ )
		// Configure U2RX - put on pin 17 (RP8)
		RPINR19bits.U2RXR = 8;
		// Configure U2TX - put on pin 16 (RP7)
		RPOR3bits.RP7R = 5;

//        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--);
    }
   #elif defined(__PIC24FJ64GB002__)
		//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--);
	    }

		AD1PCFG = 0xffff;
	    CLKDIV = 0x0000;    // Set PLL prescaler (1:1)

		// Configure U2RX - put on pin 17 (RP8)
		RPINR19bits.U2RXR = 8;
		// Configure U2TX - put on pin 16 (RP7)
		RPOR3bits.RP7R = 5;

    #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
            }
        }
    #endif

    // Init UART
    UART2Init();

    return TRUE;
} // InitializeSystem
Exemplo n.º 13
0
int main (void)
{

    FSFILE * pointer;
    char path[30];
    char count = 30;
    char * pointer2;
    int gh;
    BYTE write_array[512];
    for(gh=0; gh<512; gh++)
        if(gh%8)
            write_array[gh]='a';
        else
            write_array[gh]='b';
    DWORD first_sector;
    BYTE test_array[512];
    /* OFB_init();
     OFB_push(write_array);
     calc_checksum(write_array);
     while(1);*/
    SearchRec rec;
    pointer=NULL;
    unsigned char attributes;
    unsigned char size = 0, i;
    PLLFBD =38;
    CLKDIVbits.PLLPOST=0;
    CLKDIVbits.PLLPRE=0;
    __builtin_write_OSCCONH(0b011);
    __builtin_write_OSCCONL(0b01);
    while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur
    while(OSCCONbits.LOCK != 1) {};
    UART2Init();
    //printf("stuipd thing");
    //TRISD=0x0FF;
    //setting up pins to show on usb debugger
    TRISDbits.TRISD6=1;
    TRISAbits.TRISA7=0;
    TRISAbits.TRISA6=0;
    TRISAbits.TRISA5=0;
    TRISAbits.TRISA4=0;
    //LATA=1;
    //_LATA4=1;
    //_RA7=1;
    //_LATA6=1;

    //_LATA5=1;
    //_LATA7=1;

    //printf("they should be on now");
    //while(1);
    //LATAbits.LATA7=0;
    //TRISB=0xFFFF;
    //AD1PCFGLbits.PCFG1=1;

#ifdef TESTOVERFLOWBUFFER
#ifdef __DEBUG
    printf("Starting test of overflow buffer");

    unsigned char ofbtestin[SECTORSIZE];
    unsigned char ofbtestout[SECTORSIZE];
    OFB_init();
    int ofbi,ofbj,ofbk,result;
    char num=0;
    printf("Starting insertion test\r\n");
    for(ofbj=0; ofbj<=OVERFLOWBUFFERDEPTH; ofbj++)
    {
        for(ofbi=0; ofbi<SECTORSIZE; ofbi++)
            ofbtestin[ofbi]=num+48;
        printf("Size of Buffer: %d\r\n",OFB_getSize());
        printf("Result of Insertion: %d\r\n",OFB_push(ofbtestin));
        printf("New Size: %d\r\n",OFB_getSize());
        num++;
    }
    printf("Starting retrieval test\r\n");
    for(ofbj=0; ofbj<=OVERFLOWBUFFERDEPTH; ofbj++)
    {
        printf("Size of Buffer: %d\r\n",OFB_getSize());
        result=OFB_read_tail(ofbtestout);
        printf("result of read: %d\r\n",result);
        printf("343rd entry in array: %c\r\n",ofbtestout[342]);
        /*for(i=0;i<SECTORSIZE;i++)
        {
        	printf("%d",ofbtestout[i]);
        	while(UART2IsEmpty());
        }*/
        //printf("\r\n");
        result=OFB_pop();
        printf("Result of Pop: %d\r\n",result);
    }
    while(1);
#endif
#endif

    //Service_Spi();
#ifdef __DEBUG
    printf("Clock Switch Complete, Waiting For Media\r\n");
#endif
    //waits for a card to be inserted
    while (!MDD_MediaDetect());


#ifdef __DEBUG
    printf("Media Found, Waiting for FSinit\r\n");
#endif
    // Initialize the library
    while (!FSInit());
    char temp;
    int character_count,remove_success;
    character_count=0;
    // Create a file
    printf("starting up\r\n");
    remove_success=FSremove("WRITE.TXT");
    printf("Removal of prev: %d\r\n",remove_success);
    pointer = FSfopen ("WRITE.TXT", "w");

    if (pointer == NULL)
    {
#ifdef __DEBUG
        printf("File open failed\r\n");
#endif
        while(1);
    }
    //FSfseek(pointer,0,SEEK_SET);
    //set_First_Sector(first_sector);
    //FSfwrite("greetings",1,9,pointer);
    printf("waiting for operation\r\n");
    //FSfwrite("greetings",1,9,pointer);
    //allocate_size(38769,pointer);
    DWORD sizeinbytes;
    //need to convert from number of sectors to number of bytes and allocate that much space
    sizeinbytes=(DWORD)FILESIZE*(DWORD)512;
    //sizeinbytes=3774873*(DWORD)512;
    allocate_size(sizeinbytes,pointer,FALSE);
    FSfseek(pointer,0,SEEK_SET);
    first_sector=get_First_Sector(pointer);
    set_First_Sector(first_sector);
    DWORD erasure;
    OFB_init();
    for(erasure=0; erasure<FILESIZE; erasure++)
    {
        MDD_SDSPI_SectorWrite(first_sector, write_array,FALSE);
        first_sector++;
        if(erasure%100==0)
            printf("%lu\r",erasure);
    }
    int bleh;

    FSfclose(pointer);
    //MDD_ShutdownMedia();
    printf("done with file allocation\r\n");
#ifdef DMAON
#else
#endif

    //while(UART2IsEmpty());
    //temp=UART2GetChar();
    //write_array[character_count]=temp;
    //character_count++;
    while(1)
    {
        Service_Spi();
    }
    /*while(temp!='+')
    {
    	if(character_count<512)
    	{
    		if(!UART2IsEmpty())
    		{
    			temp=UART2GetChar();
    			write_array[character_count]=temp;
    			character_count++;
    			//printf("%08d\r",character_count);
    		}
    	}
    	else
    	{
    	FSfwrite(write_array,1,character_count, pointer);
    	character_count=0;
    	}
    }*/
    //FSfwrite(write_array,1,character_count, pointer);
    //FSfwrite(sendBuffer,1,21, pointer);
    unsigned int buffer[512];
    char buffersign;
    //bufferreturn(buffer);
    while(1)
    {
        /*buffersign=bufferreturn(buffer);
        if(buffersign==1)
        {
         //FSfwrite(buffer,1,512,pointer);
        }*/
        if(!PORTDbits.RD6)
        {
            DMA0CONbits.CHEN=0;
            //FSfclose(pointer);
            DMA0CONbits.CHEN=0;
            printf("done with operations\r\n");
            MDD_ShutdownMedia();
            while(1) {}
        }
    }
    while(1);
}
Exemplo n.º 14
0
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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), 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(&params), sizeof(params.sCircle), 0 );
                        }
        
                        // Terminate
                        UART2PrintString( "Demo complete.\r\n" );
                        USBHostPrinterCommandWithReadyWait( &returnCode, printerInfo.deviceAddress, USB_PRINTER_JOB_STOP, USB_NULL, 0, 0 );
                    }
                }
            }
        }

    }
}
Exemplo n.º 15
0
//------------------------------------------------------------------------------
int main(void)
{
  VICConfig();
  TimingInit();
  LEDInit();
  UART1Init();
  UART2Init();
  I2CInit();
  SPISlaveInit();

  Wait(100);
  UART1Printf("University of Tokyo NaviCtrl firmware V2");

  ReadEEPROM();
  UBloxInit();
  LSM303DLInit();
  FlightCtrlCommsInit();
  SDCardInit();
  NavigationInit();

  ExternalButtonInit();

  // Enable the "new data" interrupt.
  VIC_Config(EXTIT0_ITLine, VIC_IRQ, IRQ_PRIORITY_NEW_DATA);
  VIC_ITCmd(EXTIT0_ITLine, ENABLE);

  // Enable the 50Hz Interrupt.
  VIC_Config(EXTIT3_ITLine, VIC_IRQ, IRQ_PRIORITY_50HZ);
  VIC_ITCmd(EXTIT3_ITLine, ENABLE);

  // Main loop.
  uint32_t led_timer = GetTimestamp();
  for (;;)
  {
#ifndef VISION
    // Check for new data from the magnetometer.
    ProcessIncomingLSM303DL();

    // Skip the rest of the main loop if mag calibration is ongoing.
    if (MagCalibration(mag_calibration_)) continue;

    // Check for new data on the GPS UART port.
    ProcessIncomingUBlox();
#endif

    // Check for new data from the FlightCtrl.
    if (NewDataFromFlightCtrl())
    {
      ClearNewDataFromFlightCtrlFlag();

#ifdef VISION
      KalmanAccelerometerUpdate();
#endif

      UpdateNavigation();

      PrepareFlightCtrlDataExchange();

#ifndef VISION
      RequestLSM303DL();
#endif

      // Check if new data has come while processing the data. This indicates
      // that processing did not complete fast enough.
      if (NewDataFromFlightCtrl())
      {
        overrun_counter_++;
      }
    }

#ifndef VISION
    CheckUBXFreshness();
    CheckLSM303DLFreshness();

    // Normally the magnetometer is read every time new data comes from the
    // FlightCtrl. The following statement is a backup that ensures the
    // magnetometer is updated even if there is no connection to the FlightCtrl
    // and also deals with read errors.
    if (LSM303DLDataStale())
    {
      if (MillisSinceTimestamp(LSM303DLLastRequestTimestamp()) > 20)
        RequestLSM303DL();
      if (LSM303DLErrorBits() & LSM303DL_ERROR_BIT_I2C_BUSY)
        I2CReset();
    }
#else
    CheckVisionFreshness();
#endif

    // Check for incoming data on the "update & debug" UART port.
    ProcessIncomingUART1();

    // Check for incoming data on the "FligthCtrl" UART port.
    ProcessIncomingUART2();

    ProcessLogging();

    if (TimestampInPast(led_timer))
    {
      GreenLEDToggle();

      while (TimestampInPast(led_timer)) led_timer += 100;

      // Debug output for GPS and magnetomter. Remove after testing is completed

      // UART1Printf("%+5.2f,%+5.2f,%+5.2f",
      //   MagneticVector()[0],
      //   MagneticVector()[1],
      //   MagneticVector()[2]);

      // UART1Printf("%i,%i,%i",
      //   MagnetometerVector()[0],
      //   MagnetometerVector()[1],
      //   MagnetometerVector()[2]);

      // UART1Printf("%i,%i,%i",
      //   MagnetometerBiasVector()[0],
      //   MagnetometerBiasVector()[1],
      //   MagnetometerBiasVector()[2]);

      // UART1Printf("%f", CurrentHeading());

      // UART1Printf("%f,%f,%f",
      //   (float)(UBXPosLLH()->longitude * 1e-7),
      //   (float)(UBXPosLLH()->latitude * 1e-7),
      //   (float)(UBXPosLLH()->height_above_ellipsoid * 1e-3));

      UART1PrintfSafe("%+5.2f,%+5.2f,%+5.2f,%+5.2f",
        PositionVector()[0],
        PositionVector()[1],
        PositionVector()[2],
        CurrentHeading());
    }
  }
}
Exemplo n.º 16
0
int main(void)
{

    // Start from displaying of PIC24 banners
	_display_state = DISP_HELLO;

    // Setup PortA IOs as digital
    AD1PCFG = 0xffff;

	//IO Mapping for PIC24FJ64GA004 
	#ifdef __PIC24FJ64GA004__ //Defined by MPLAB when using 24FJ64GA004 device
		ioMap();
		lockIO();
	#endif

    // Setup SPI to communicate to EEPROM
    SPIMPolInit();

    // Setup EEPROM IOs
    EEPROMInit();

    // Setup the UART
    UART2Init();

	// Setup the timer
	TimerInit();
    
	// Setup the LCD
	mLCDInit();

	// Setup debounce processing
	BtnInit(); 

    // Setup the ADC
    ADCInit();

	// Setup the banner processing
	BannerStart();

	// Setup the RTCC
    RTCCInit();

	while (1) {
		LCDProcessEvents();
        ADCProcessEvents();

		if (TimerIsOverflowEvent()){

			// Button debounce processing
			BtnProcessEvents();
			// State dependent processing
			switch (_display_state) {
                // Show Microchip banners
				case DISP_HELLO: BannerProcessEvents(); break;
                // Show clock
				case DISP_CLOCK: TBannerProcessEvents(); break;
                // Show voltage and temperature
				case DISP_VOLTAGE: VBannerProcessEvents(); break;

                default: _display_state = DISP_HELLO;
			}// End of switch (_display_state)...

            // If S6 is pressed show the next example
			if (BtnIsPressed(4)) {

                // Change state and clear display 
                if(!TBannerIsSetup()){
       				_display_state++;
                    if(_display_state > DISP_MAX)
                         _display_state = 0;

                    // Initialize state
                    switch (_display_state) {
                        // Microchip banners
                 	    case DISP_HELLO: BannerInit(); break;
                        // Clock
    				    case DISP_CLOCK: TBannerInit(); break;
                        // Voltage and temperature
	        			case DISP_VOLTAGE: VBannerInit(); break;
                        default:
                             _display_state = 0;
        		    }// End of switch (_display_state)...
                    mLCDClear();
                }else
                    TBannerNext();

                // wait for button released
                while (BtnIsPressed(4)){
					BtnProcessEvents();
				}
			}// End of 	if (BtnIsPressed(4)){...

            if(_display_state == DISP_CLOCK){

        		if (BtnIsPressed(1)){
                        TBannerSetup();
                    // wait for button released
                    while (BtnIsPressed(1))	BtnProcessEvents();
                }// End of if (BtnIsPressed(1 ...

                if(TBannerIsSetup()){
	           		if (BtnIsPressed(2)) {
                        TBannerChangeField(1);
                        // wait for button released
                        while (BtnIsPressed(2))	BtnProcessEvents();
    		    	}// End of if (BtnIsPressed(2)){...
    
	    		    if (BtnIsPressed(3)) {
                        // wait for button released
                        TBannerChangeField(0);
                        while (BtnIsPressed(3))	BtnProcessEvents();
        			}// End of if (BtnIsPressed(3)){...
                }// End of if(TBannerIsSetup( ...

            }// End of if(_display_state == DISP_SET_CLOCK ...



            if(_display_state == DISP_VOLTAGE){

        		if (BtnIsPressed(2)){
                    ADCSetFromMemory();
                    // wait for button released
                    while (BtnIsPressed(2)){
						BtnProcessEvents();
					}
                }// End of if (BtnIsPressed(2 ...

           		if (BtnIsPressed(3)){
                    ADCStoreTemperature();
                    // wait for button released
                    while (BtnIsPressed(3)){
						BtnProcessEvents();
					}
  		    	}// End of if (BtnIsPressed(3)){...

            }// End of if(_display_state ...




    	}// End of if (TimerIsOverflowEvent()...
    }// End of while(1)...
}// End of main()...