Ejemplo n.º 1
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
 
    char message[100];
    SYS_Initialize ( NULL );
    //set up accelerometer
    acc_setup();
   //set up display
    display_init();
    display_clear();
    sprintf(message,"System Initialised!");
    write_string(message,0,0);
    display_draw();    
    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );
        

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 2
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );
    // set B5 as OC1
    RPB5Rbits.RPB5R = 0b0101;       // set B5 to OC2
    OC2CONbits.OCTSEL = 1;          // Select Timer3 for comparison
    T3CONbits.TCKPS = 0;            // Timer3 prescaler 1:1
    PR3 = 3999;                     // period = (PR2+1) * N * 12.5 ns = 20 kHz
    TMR3 = 0;                       // initial TMR3 count is 0

    OC2CONbits.OCM = 0b110;         // PWM mode with no fault pin; other OC2CON bits are defaults

    OC2RS = 2500;                   // duty cycle = OC2RS/(PR3+1) = 50%
    OC2R = 2500;

    T3CONbits.ON = 1;               // turn on Timer3
    OC2CONbits.ON = 1;              // turn on OC2


    // set B15 as OC1
    RPB15Rbits.RPB15R = 0b0101;     // set B15 to OC1

    OC1CONbits.OCTSEL = 0;          // Select Timer2 for comparison
    T2CONbits.TCKPS = 0;            // Timer2 prescaler 1:1
    PR2 = 3999;                     // period = (PR2+1) * N * 12.5 ns = 20 kHz
    TMR2 = 0;                       // initial TMR2 count is 0

    OC1CONbits.OCM = 0b110;         // PWM mode with no fault pin; other OC1CON bits are defaults

    OC1RS = 2500;                   // duty cycle = OC1RS/(PR2+1) = 50%
    OC1R = 25000;

    T2CONbits.ON = 1;               // turn on Timer2
    OC1CONbits.ON = 1;              // turn on OC1

    //A Phase: B7 - Digital Output
    TRISBbits.TRISB7 = 0;      // 0 is output, 1 is input

    //B Phase: B14 - Digital Output
    ANSELBbits.ANSB14 = 0;      // 0 for digital, 1 for analog
    TRISBbits.TRISB14 = 0;      // 0 is output, 1 is input

    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 3
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );
    _CP0_SET_COUNT(0);
           // set up USER pin as input
        ANSELBbits.ANSB13=0;
	TRISBbits.TRISB13=1;
    // set up LED1 pin as a digital output
    //    TRISBbits.TRISB7=0;
    //   	LATBbits.LATB7=1;

    // set up LED2 as OC1 using Timer2 at 1kHz   PWM: B15   DIO: B9   left
        TRISBbits.TRISB9=0;
        LATBbits.LATB9=1;
        ANSELBbits.ANSB15=0;
	RPB15Rbits.RPB15R=0b0101;
	T2CONbits.TCKPS = 0;
	PR2=1999;
	TMR2=0;
	T2CONbits.ON=1;
        T2CONbits.TCS=0;
	OC1CONbits.OCTSEL=0;
	OC1CONbits.OCM = 0b110;  // PWM mode without fault pin; other OC1CON bits are defaults
	OC1CONbits.ON = 1;
	OC1RS=0;
	OC1R=0;
    //  OC2  PWM: B5    DIO: B3    right
        ANSELBbits.ANSB3=0;
        TRISBbits.TRISB3=0;
        LATBbits.LATB3=0;

        RPB5Rbits.RPB5R=0b0101;
        T3CONbits.TCKPS = 0;
	PR3=1999;
	TMR3=0;
	T3CONbits.ON=1;
        T3CONbits.TCS=0;
	OC2CONbits.OCTSEL=1;
	OC2CONbits.OCM = 0b110;  // PWM mode without fault pin; other OC1CON bits are defaults
	OC2CONbits.ON = 1;
	OC2RS=0;
	OC2R=0;
    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 4
0
int main(void) {
  /* Initialize all MPLAB Harmony modules, including application(s). */
  SYS_Initialize(NULL);

  while (true) {
    /* Maintain state machines of all polled MPLAB Harmony modules. */
    SYS_Tasks();
  }

  /* Execution should not come here during normal operation */
  return (EXIT_FAILURE);
}
Ejemplo n.º 5
0
/*
*********************************************************************************************************
*                                            MAIN - ENTRY POINT OF APPLICATION
*********************************************************************************************************
*/
void main ( void )
{
   
    
   /*Call the SYS Init routine. App init routine gets called from this*/
   SYS_Initialize(NULL);
   while(1)
   {
      SYS_Tasks();
   }
    
}
Ejemplo n.º 6
0
int main ( void )
{
    /* Initialize the application. */
    SYS_Initialize();

    while (true)
    {
        /* Maintain the application's state machine. */
        SYS_Tasks();
    }

    /* Should not come here during normal operation */
    PLIB_ASSERT(false, "leaving main");
    
    return (EXIT_FAILURE);
}
Ejemplo n.º 7
0
MAIN_RETURN main ( void )
{
    /*Call the SYS Init routine. App init routine gets called from this*/
    SYS_Initialize(NULL);

    while(true)
    {
        /*Invoke SYS tasks. APP tasks gets called from this*/
        SYS_Tasks();

    }

    // Should not come here during normal operation
    SYS_ASSERT(false, "about to exit main");

    return MAIN_RETURN_CODE(MAIN_RETURN_SUCCESS);
}
Ejemplo n.º 8
0
// *****************************************************************************
// *****************************************************************************
// Section: Main Entry Point
// *****************************************************************************
// *****************************************************************************
int main ( void )
{
    /* Call the System Intialize routine*/
    SYS_Initialize ( ) ;

    /*Initialize Timer*/
    TIMER_SetConfiguration ( TIMER_CONFIGURATION_RTCC ) ;

    TRISGbits.TRISG7 = 1; //in breakout pin RF2 (row 1)
    TRISGbits.TRISG2  = 1; //in breakout pin RA2 (row 2)
    TRISCbits.TRISC0 = 1; //in breakout pin RB8 (row 3)
    TRISCbits.TRISC1 = 1;//in breakout pin RB9 (row 4)                 
    TRISEbits.TRISE12 = 0; //in breakout pin RB12 (col 1)
    TRISCbits.TRISC2 = 0; //in breakout pin RB10 (col 2)
    TRISEbits.TRISE14 = 0; //in breakout pin RB14 (col 3)
    
    
    ANSELGbits.ANSG7 = 0; //Row 1-4        //configuring all pins as digital
    ANSELGbits.ANSG2 = 0;
    ANSELCbits.ANSC0 = 0;
    ANSELCbits.ANSC1 = 0;
    ANSELEbits.ANSE12 = 0; //Col 1-3
    ANSELCbits.ANSC2 = 0;
    ANSELEbits.ANSE14 = 0;
    
    char return_key;
    
    /* Infinite Loop */
    while ( 1 )
    {  
        return_key = 'X'; //initialize return key to default return variable from readKeyboard()
        
        while(return_key == 'X'){ //while nothing is pressed, keep on making calls
            return_key = readKeyboard();
        }
        
        if(return_key != 'X'){ //if return_key is not default key, print to LCD 
            //should transmit to UART at this point  
            LCD_PutChar(return_key);
        }
        
        while(readKeyboard() != 'X'){
            //no operation till next key is pressed.
        }
    }    
}
Ejemplo n.º 9
0
// *****************************************************************************
// *****************************************************************************
// Section: Main Entry Point
// *****************************************************************************
// *****************************************************************************
int main( void )
{
    /* Prepare the hardware to run this demo. */
    SYS_Initialize();

    while(true)
    {
        /*Invoke SYS tasks. APP tasks gets called from this*/
        SYS_Tasks();

    }

    // Should not come here during normal operation
    SYS_ASSERT(false, "about to exit main");

    return MAIN_RETURN_CODE(MAIN_RETURN_SUCCESS);

}
Ejemplo n.º 10
0
Archivo: main.c Proyecto: caygen/ME433
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );
    
    //Timer Setup
    T2CONbits.TCKPS 	= 4;			// timer2 pre-scaler N=16 (1:16)
	PR2 				= 2999;			// period2 = (4999+1) * 16 * 12.5ns = 0.001s, 1 kHz
	TMR2 				= 0;			// set timer to 0;
    T2CONbits.ON		= 1;			// turn on Timer2
    //OC1 Setup
    RPB15Rbits.RPB15R = 0b0101;         // OC1 = B15
    OC1CONbits.OCM		= 0x06;         // PWM mode without fault pin; other OC1CON bits are defaults
	OC1CONbits.OCTSEL	= 0;			// use Timer 2
	OC1RS				= 1500;         // duty cycle = OC1RS/(PR2+1) = 50%
	OC1R				= 1500;         // initialize before turning OC1 on
	OC1CONbits.ON		= 1;			// turn on OC1
    //OC2 Setup
    RPA1Rbits.RPA1R = 0b0101;           //OC2 = A0
    OC2CONbits.OCM		= 0x06;         // PWM mode without fault pin; other OC2CON bits are defaults
	OC2CONbits.OCTSEL	= 0;			// use Timer 2
	OC2RS				= 1500;         // duty cycle = OC2RS/(PR2+1) = 50%
	OC2R				= 1500;         // initialize before turning OC2 on
	OC2CONbits.ON		= 1;			// turn on OC2
    
    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        
        SYS_Tasks ( );
        //OC2RS = rightPWM;
        

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 11
0
/********************************************************************
 * Function:        void main(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        Main program entry point.
 *
 * Note:            None
 *******************************************************************/
int main(void)
{
    SYS_Initialize();

    FILEIO_Initialize();

    FILEIO_RegisterTimestampGet(GetTimestamp);

    //Initialize the stack
    USBHostInit(0);

    APP_HostMSDSimpleInitialize();

    while(1)
    {
        USBHostTasks();
        USBHostMSDTasks();

        //Application specific tasks
        APP_HostMSDSimpleTasks();
    }//end while
}//end main
Ejemplo n.º 12
0
int main ( void )
{

    //TRISA = 0b0010000000000000;
    TRISA = 0b00001111;
    TRISAbits.TRISA12 = 0;
    
    TRISCbits.TRISC1 = 0;
    TRISCbits.TRISC2 = 0;
    TRISCbits.TRISC3 = 0;
    TRISCbits.TRISC4 = 0;
    
    //TRISD = 0;
    TRISD = 0b0000000000010000; // RD11: DIR2; RD8: PWM2
    
    //TRISE = 0b00001000;
    TRISE = 0b00001000; // RE6: DIR1; RE0: PWM1
    TRISEbits.TRISE7 = 0; 
   
    //LCD an
    _PCFG16 = 1; // AN16 is digital
    _PCFG17 = 1; // AN17 is digital
    _PCFG18 = 1; // AN18 is digital
    _PCFG19 = 1; // AN19 is digital
    _PCFG20 =1;
    _PCFG31=1;
    
    //pwm analog select
    _PCFG24=1;
    _PCFG30=1;
    
    //RE4 for lcd r/s
     _PCFG28=1;
     TRISEbits.TRISE4 = 0;
    
    AD1PCFGHbits.PCFG28 = 1;
    AD1PCFGHbits.PCFG27 = 1;
    AD1PCFGHbits.PCFG30 = 1;
    AD1PCFGHbits.PCFG24 = 1;
    AD1PCFGH = 0x0020;
    TRISAbits.TRISA13 = 1;
    //set pwm low
    PWM1=0;
    PWM2=0;
    
    SYS_Initialize ( ) ;
    
    CLKDIVbits.FRCDIV = 0;
    CLKDIVbits.PLLPOST = 0;  // N2 = 2
    CLKDIVbits.PLLPRE = 0;  // N1 = 2
    PLLFBD = (Fosc*N1_default*N2_default/Ffrc) - M_default; // M = 8 -> Fosc = 7.3728 MHz * 8 / 2 / 2 = 16 MHz
    while(!OSCCONbits.LOCK);	// Wait for PLL to lock
	RCONbits.SWDTEN = 0;      // Disable Watch Dog Timer
    
    //TRISF = 0;
    gpsLock = 0;
   
    lcd_init();
    print_lcd("Initializing");
    //delay_ms(500);
    //lcd_clear();
    
    /*lcd test
    char line1[] = " On Route ";
    char line2[] = " Arrived ";
    //send_command_byte(0xFF);
    //while(1){send_command_byte(0xFF);send_data_byte(0);}
   // delay_ms(2);
    //send_command_byte(0x02); // Go to start of line 1
    //send_command_byte(0b00001111); // Display: display on, cursor on, blink on
    //send_command_byte(0b00000110); // Set entry mode: ID=1, S=0
    //send_command_byte(0b00000001); // Clear display
    
    print_lcd(line1);
    delay_ms(5000);
    lcd_clear();
    print_lcd(line2);
    //send_command_byte(0xC0); // Go to start of line 1
    //while(1){send_command_byte(0b00000001);}
    while(1);*/
    
    /*int a;
    long long int ct;
    int i;
    int j=0;*/
    //i2c init

    
    //uart init
    UART_Initialize();
    delayMs(100);
    
    
    /* while(1){//test for delay ms configuration
        //PORTDbits.RD1 = 1;
        //delayUs(10);
        //for(i = 0;i <7;i++);
        delayMs(10);
        PORTDbits.RD12 = 1;
        //for (i = 0; i < 1000; i++);
        //PORTDbits.RD1 = 0;
        //for(i = 0;i <7;i++);
        delayMs(10);
        
        PORTDbits.RD12 = 0;
        //for (i  = 0; i < 1000; i++);
    }*/
    
    //ultrasonic test
    
   /* while(1){
        long double x;
        delayMs(500);
        PORTEbits.RE4 = 1;                  //TRIGGER HIGH
        PORTDbits.RD5 = 1; 
        delay_us(10);                     //10uS Delay 
        lcd_clear();
        ultraSonicEn = 1;
        ultraSonicCount = 0;

        PORTEbits.RE4 = 0;                  //TRIGGER LOW
        PORTDbits.RD5 = 0; 
        
        
        while (!PORTDbits.RD4);              //Waiting for Echo
       IEC0bits.T2IE = 1; //enable timer
        while(PORTDbits.RD4);// 
        IEC0bits.T2IE = 0; //disable timer
        x = ultraSonicCount/TICKS_PER_METER;
        sprintf(outputBuf,"%lf",x); 
        print_lcd(outputBuf);
    }*/

    //TX_str(endGPS);
    //delayMs(3000);
    //TX_str(startGPS);
    /*TX_str(startGPShot);
    delayMs(2000);
    while ( !gpsLock ) {
        TX_str(getGPS);
        delayMs(500);
    }*/
    
   //TCP code
    
    TX_str(openNet);
    delayMs(5000);
    TX_str(openConnection);
    delayMs(5000);
 
    // while(!BUTTON_IsPressed ( BUTTON_S3 ));
    //TX_str(sprintf("%s%d\r",sendTCP, strlen("10")));
    sprintf(outputBuf2,"2\n%lf,%lf\n\r",roverLog,roverLat );
    sprintf(cmdBuf,"%s%d\r", sendTCP,strlen(outputBuf2));
         
    TX_str(cmdBuf);
    delayMs(3000);
    TX_str(outputBuf2);
    while(!waypointsReady || !gpsLock);
    
    
    //while(1);
    delayMs(7000);
    lcd_clear();
    print_lcd("waypoints locked");
    
    i2c_init();
    //i2c_write3(0x3c, 0x00, 0x70);
    i2c_write3(0x3c, 0x00, 0b00011000);
    //i2c_write3(0x3c, 0x01, 0b11000000);
    i2c_write3(0x3c, 0x01, 0xA0);
    i2c_write3(0x3c, 0x02, 0x00);
    
    //timer init, do this after other initializations
    motorDuty=0;
    tim1_init();
    tim2_init();
   
    /*
    double angleTolerance = 8.0;
     motorDuty=2;
 
    while (1){ //adjust


        double angleDiff = headingDiff(0,roverHeading );


        if (angleDiff > 0 ||abs(angleDiff) > 175 ){ //turn left

            PWM1_DIR = 0; //left            NOTE: 0 is forward, 1 is reverse
            PWM2_DIR = 1; //right
        } else{ // turn right

            PWM1_DIR = 1;
            PWM2_DIR = 0;
        }
        if (abs(angleDiff) < angleTolerance){
            motorDuty = 0;
            //break;
        }else{
            //motorDuty =4;
            motorDuty =2;
        }   
        delayMs(13);
        updateHeading();
    }*/
    
    //hardcoded gps for tcpip test
    
    
     /*while(1){
//        PORTDbits.RD5 = 1;
//        for (a = 0; a < (100/33); a++) {}
//        PORTDbits.RD5 = 0;
//        for (a = 0; a < (100/33); a++) {}
        ct = 0;
        //TMR2 = 0;//Timer Starts
        delayMs(60);
        PORTEbits.RE4 = 1;                  //TRIGGER HIGH
        PORTDbits.RD5 = 1; 
        delay_us(15);
                           //10uS Delay 
        PORTEbits.RE4 = 0;                  //TRIGGER LOW
        PORTDbits.RD5 = 0; 
        while (!PORTDbits.RD4){              //Waiting for Echo
            ct++;
        }
            //T2CONbits.TON = 1;
        while(PORTDbits.RD4) {
            ct++;
        }// {
        //T2CONbits.TON = 0;
        sprintf(outputBuf,"%lld", ct); 
        //a = TMR2;
        //a = a / 58.82;
        
        //long int p;
        //for(p = 0; p <100000; p++);
        
    }*/
    //tim1_init();
    //while ( 1 );
    //UART_Initialize();
    
    /* Infinite Loop */
    /*
     long int i;
    while ( 1 )
    {//test for delay ms configuration
        //PORTDbits.RD1 = 1;
        delayMs(10);
        PORTDbits.RD12 = 1;
        //for (i = 0; i < 1000; i++);
        //PORTDbits.RD1 = 0;
        delayMs(10);
        PORTDbits.RD12 = 0;
        //for (i = 0; i < 1000; i++);
    }*/
    //IEC0bits.T1IE = 0;
    
    //IEC0bits.T1IE = 1;
    //motorDuty =2;
    motorStopFlag = 0; //ready to go
    char tempBuf1[50];
    int wapointsVisited;
    double desiredHeading = 0;
    double dToWaypoint = 99999.9;
    double angleTolerance = 6.0;
    for (wapointsVisited =0; wapointsVisited<numGPSpoints;wapointsVisited++ )
    {
        dToWaypoint = 99999.9;
        while (1)
        {

            int f;
            roverLog = 0;
            roverLat = 0;
            for(f = 0; f < ROVER_LEN; f++){
                roverLog+=roverlog[f]/ROVER_LEN_D;
                roverLat+=roverlat[f]/ROVER_LEN_D;
            }
            
            
            dToWaypoint = dist(convertGPSToDeg(roverLat),convertGPSToDeg(roverLog),convertGPSToDeg(gpsLat[wapointsVisited]),convertGPSToDeg(gpsLonge[wapointsVisited]));
            if(dToWaypoint <= 3.0){break;} //go to next waypoint

            desiredHeading = 330.0;
            desiredHeading = bearing(convertGPSToDeg(roverLat),convertGPSToDeg(roverLog),convertGPSToDeg(gpsLat[wapointsVisited]),convertGPSToDeg(gpsLonge[wapointsVisited]));
            
            updateHeading();
            
                
            if (!(abs(headingDiff(desiredHeading,roverHeading )) < angleTolerance))
            {
                motorDuty = 0;  //stop
                delayMs(300);
                while (1) //ADJUSTMENT LOOP
                {
                   
                    double angleDiff = headingDiff(desiredHeading,roverHeading );

                    //double dist = ultraSonicPing();
                    /*sprintf(tempBuf1,"%f",dist);
                    lcd_clear();
                    print_lcd(tempBuf1);*/
                     if (abs(angleDiff) < angleTolerance){
                        motorDuty = 0;
                        /*sprintf(tempBuf1,"%f",roverHeading);
                        IEC0bits.T1IE = 0;
                        print_lcd(tempBuf1);
                        IEC0bits.T1IE = 1;*/
                        break;
                    }
                    if (angleDiff > 0 || abs(angleDiff) > 175 ){ //turn right
                        /*PORTDbits.RD4 = 1; //right 0 is forwards, 1 i backwards
                        PORTDbits.RD2 = 1;
                        PORTDbits.RD8 = 0; //left*/
                        PWM1_DIR = 0; //left            NOTE: 0 is forward, 1 is reverse
                        PWM2_DIR = 1; //right
                    } else{ // turn left
                        /*PORTDbits.RD4 = 0; //right 0 is forwards, 1 i backwards
                        PORTDbits.RD2 = 0;
                        PORTDbits.RD8 = 1; //left*/
                        PWM1_DIR = 1;
                        PWM2_DIR = 0;
                    }
                   
                       
                    motorDuty =3;
                     
                    delayMs(15);
                    updateHeading();
        //        sprintf(tempBuf1,"%f",roverHeading);
        //        IEC0bits.T1IE = 0;
        //        lcd_clear();
        //        print_lcd(tempBuf1);
        //        IEC0bits.T1IE = 1;
                //delayMs(1000);
                //for(p = 0; p <100000; p++);
                }
            }
            PWM1_DIR = 0; //left            NOTE: 0 is forward, 1 is reverse
            PWM2_DIR = 0;

            motorDuty = 5;
            ultraSonicDelayEnable = 1;
            //frequency is around 20kHz
            while (ultraSonicDelayCount < 60000){ //for 4 seconds poll ultrasonic and check for obsticles
                long double x;
                //PORTEbits.RE4 = 1;                  //TRIGGER HIGH
                PORTDbits.RD5 = 1; 
                delay_us(10);                     //10uS Delay 
                lcd_clear();
                ultraSonicEn = 1;
                ultraSonicCount = 0;

                //PORTEbits.RE4 = 0;                  //TRIGGER LOW
                PORTDbits.RD5 = 0; 


                while (!PORTDbits.RD4);              //Waiting for Echo
               IEC0bits.T2IE = 1; //enable timer
                while(PORTDbits.RD4);// 
                IEC0bits.T2IE = 0; //disable timer
                ultraSonicEn = 0;
                x = ultraSonicCount/TICKS_PER_METER;
                if (x <= 1.4){
                    motorDuty = 0;
                }else{
                    motorDuty = 5;
                }
                delayMs(200);
            }
            ultraSonicDelayEnable = 0;
            ultraSonicDelayCount = 0;
        }
        
        motorDuty = 0;
        delayMs(1000);
        //IEC0bits.T1IE = 0;
        lcd_clear();
        char buf3[40];
        sprintf(buf3, "reached %d", wapointsVisited);
        print_lcd(buf3);
        delayMs(3000);
        //IEC0bits.T1IE = 1;
        
    }
    //IEC0bits.T1IE = 0;
    lcd_clear();
    print_lcd("ARRIVED!!!");
    //IEC0bits.T1IE = 1;
    while (1);
}
Ejemplo n.º 13
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    ANSELBbits.ANSB15 = 0; //Make it digital
    TRISBbits.TRISB15 = 0;
    TRISBbits.TRISB7 = 0;

	__builtin_enable_interrupts();
    
    // set up USER pin as input
	ANSELBbits.ANSB13 = 0;
	TRISBbits.TRISB13 = 1;

    //Set phase pins
    //   PH1--> B7
//    RPB7Rbits.RPB7R = 0b001; //Peripheral requires output pin
    TRISBbits.TRISB7 = 0; //Make it an output
    LATBbits.LATB7 = 1; //Set it high- this initializes as the forward direction

    //   PH2-->B14
    ANSELBbits.ANSB14 = 0; //Make it digital
    RPB14Rbits.RPB14R = 0b001;
    TRISBbits.TRISB14 = 0; //Make it an output
    LATBbits.LATB14 = 0; //Set it high- this initializes as the forward direction    

    //Set enable pins
    //   EN1--> B5 
    //ANSELBbits.ANSB5 = 0; //Make it digital
    RPB5Rbits.RPB5R = 0b0101; //Set to OC2
    TRISBbits.TRISB5 = 0; //Make it an output

    //   EN2-->B15    
    ANSELBbits.ANSB15 = 0; //Make it digital
    RPB15Rbits.RPB15R = 0b0101; //Set to OC1
//    TRISBbits.TRISB15 = 0; //Make it an output

    //Set timers:
    //This is to set up PWM frequency for OC pin- this will be altered using potentiometer
	T2CONbits.TCKPS = 0;     // Timer2 prescaler N=1 (1:4)
	PR2 = 1999;                 // period = (PR2+1) * N * 12.5 ns = 1 ms, 1 kHz 
    TMR2 = 0;
    
 	OC1CONbits.OCM = 0b110;  // PWM mode without fault pin; other OC1CON bits are defaults
    OC1CONbits.OCTSEL = 0; //Using Timer 2 for OC1
    OC1RS = 0;               //duty cycle = OC1RS/(PR2+1) 25% duty cycle to begin with
    OC1R = 0;                //initialize before turning OC1 on;        
	T2CONbits.ON = 1;        // turn on Timer2
	OC1CONbits.ON = 1;       // turn on OC1

    //This is to set up PWM frequency for OC pin- this will be altered using potentiometer

 	OC2CONbits.OCM = 0b110;  // PWM mode without fault pin; other OC1CON bits are defaults
    OC2CONbits.OCTSEL = 0;     //Using Timer2 for OC2
    OC2RS = 0;               //duty cycle = OC1RS/(PR2+1)
    OC2R = 0;                //initialize before turning OC1 on;        
	OC2CONbits.ON = 1;       // turn on OC2
    
    __builtin_enable_interrupts();
    
    SYS_Initialize ( NULL );
    
    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        
        SYS_Tasks ( );

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 14
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );
    // PWM digital pin, set to OC1 / B15
    ANSELBbits.ANSB15 = 0; // 0 = digital, set this since default for this pin is analog
    RPB15Rbits.RPB15R = 0b0101; //Set B15 as OC1

    // PWM for servo motor
    OC1CONbits.OCTSEL = 0; 	// 0=Timer 2 is used for output compare
    OC1CONbits.OCM = 0b110;     // PWM mode without fault pin; other OC1CON bits are defaults
    OC1R = 1250; 		// duty cycle = OC1RS/(PR2+1) = 0.075, 1.5ms/20ms for neutral servo position
				// initialize before turning OC1 on; afterward it is read-only
    T2CONbits.TCKPS = 0b100; 	// set prescaler to 1:16 (N=16)
    PR2 = 49999;                // period = (PR2+1)*N=16*25ns = 20 ms, or 50 Hz
    TMR2 = 0;			// initalize counter to 0

    T2CONbits.ON = 1; 		// turn on Timer2
    OC1CONbits.ON = 1;          // turn on OC1

    /*Motors - both use Timer 3*/
    T3CONbits.TCKPS = 0; 	// set prescaler to 1:1 (N=1)
    TMR3 = 0;			// initalize counter to 0
    PR3 = 799;                  // period = (PR3+1)*N=1*25ns = 20 us, or 20 kHz

    /*Motor B: LEFT WHEEL (top down view)*/
    //PHA1 pin
    TRISBbits.TRISB4 = 0; //digital output
    LATBbits.LATB4 = 0; //output on=0 initially

    // PWM digital pin, set to OC2 (ENA1)
    RPB5Rbits.RPB5R = 0b0101;   // Set B5 as OC2
    OC2CONbits.OCTSEL = 1; 	// 1=Timer 3 is used for output compare
    OC2CONbits.OCM = 0b110;     // PWM mode without fault pin; other OC2CON bits are defaults
    OC2R = 0;                   // duty cycle = OC2RS/(PR3+1) = 0.075, 1.5ms/20ms for neutral servo position
    OC2RS = 0;			// initialize before turning OC2 on; afterward it is read-only

    /*Motor A: RIGHT WHEEL*/
    //PHA2 pin
    TRISBbits.TRISB8 = 0; //digital output
    LATBbits.LATB8 = 0; //output on=0 initially

    // PWM digital pin, set to OC3 (ENA2)
    RPB9Rbits.RPB9R = 0b0101;   // Set B9 as OC3
    OC3CONbits.OCTSEL = 1; 	// 1=Timer 3 is used for output compare
    OC3CONbits.OCM = 0b110;     // PWM mode without fault pin; other OC2CON bits are defaults
    OC3R = 0;                   // duty cycle = OC3RS/(PR3+1) = 0.075, 1.5ms/20ms for neutral servo position
    OC3RS = 0;          	// initialize before turning OC1 on; afterward it is read-only

    T3CONbits.ON = 1; 		// turn on Timer4
    OC3CONbits.ON = 1;          // turn on OC3
    OC2CONbits.ON = 1;          // turn on OC2

    // set up LED1 pin as a digital output - light checker
    TRISBbits.TRISB7 = 0; //digital output
    LATBbits.LATB7 = 0; //output on=0 initially
    
    while ( true )
    {
        //LATBbits.LATB7 = 1;
        //LATBINV = 0b10000000;
        //OC3RS=400;
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );
        
    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 15
0
//
// Main application entry point.
//
int main(void)
{

#if defined(APP_USE_IPERF)
    static uint8_t iperfOk = 0;
#endif
    static SYS_TICK startTick = 0;
    static IP_ADDR dwLastIP[sizeof (TCPIP_HOSTS_CONFIGURATION) / sizeof (*TCPIP_HOSTS_CONFIGURATION)];
    uint8_t i;


    // perform system initialization
    if(!SYS_Initialize())
    {
        return 0;
    }

    SYS_CONSOLE_MESSAGE("\r\n\n\n --- Unified TCPIP Demo Starts! --- \r\n");

    SYS_OUT_MESSAGE("TCPStack " TCPIP_STACK_VERSION "  ""                ");

    #if defined(TCPIP_STACK_USE_MPFS) || defined(TCPIP_STACK_USE_MPFS2)
	MPFSInit();
	#endif

    // Initiates board setup process if button is depressed 
	// on startup
    if(BUTTON0_IO == 0u)
    {
        #if defined(TCPIP_STACK_USE_STORAGE)  && (defined(SPIFLASH_CS_TRIS) || defined(EEPROM_CS_TRIS))
		// Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds
		SYS_TICK StartTime = SYS_TICK_Get();
		LED_PUT(0x00);
				
		while(BUTTON0_IO == 0u)
		{
			if(SYS_TICK_Get() - StartTime > 4*SYS_TICK_TicksPerSecondGet())
			{
                TCPIP_STORAGE_HANDLE hStorage;
                
                // just in case we execute this before the stack is initialized
                TCPIP_STORAGE_Init(0);
                hStorage = TCPIP_STORAGE_Open(0, false);   // no refresh actually needed
                if(hStorage)
                {
                    TCPIP_STORAGE_Erase(hStorage);
                    SYS_CONSOLE_MESSAGE("\r\n\r\nBUTTON0 held for more than 4 seconds.  Default settings restored.\r\n\r\n");
                    TCPIP_STORAGE_Close(hStorage);
                }
                else
                {
                    SYS_ERROR(SYS_ERROR_WARN, "\r\n\r\nCould not restore the default settings!!!.\r\n\r\n");
                }
                TCPIP_STORAGE_DeInit(0);
                
				LED_PUT(0x0F);
                // wait 4.5 seconds here then reset
				while((SYS_TICK_Get() - StartTime) <= (9*SYS_TICK_TicksPerSecondGet()/2));
				LED_PUT(0x00);
				while(BUTTON0_IO == 0u);
				SYS_Reboot();
				break;
			}
		}
        #endif  // defined(TCPIP_STACK_USE_STORAGE)  && (defined(SPIFLASH_CS_TRIS) || defined(EEPROM_CS_TRIS))
    }

    // Initialize the TCPIP stack
    if(!TCPIP_STACK_Init(TCPIP_HOSTS_CONFIGURATION, sizeof(TCPIP_HOSTS_CONFIGURATION)/sizeof(*TCPIP_HOSTS_CONFIGURATION),
                       TCPIP_STACK_MODULE_CONFIG_TBL, sizeof(TCPIP_STACK_MODULE_CONFIG_TBL)/sizeof(*TCPIP_STACK_MODULE_CONFIG_TBL) ))
    {
        return 0;
    }
#if defined(TCPIP_STACK_USE_TELNET_SERVER)
    TelnetRegisterCallback(ProcessIO);
#endif  // defined(TCPIP_STACK_USE_TELNET_SERVER)

#if defined (TCPIP_STACK_USE_IPV6)
    TCPIP_ICMPV6_RegisterCallback (ICMPv6Callback);
#endif

#if defined(TCPIP_STACK_USE_ICMP_CLIENT) || defined(TCPIP_STACK_USE_ICMP_SERVER)
    ICMPRegisterCallback (PingProcessIPv4);
#endif


#if defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)
    TCPIP_NET_HANDLE hWiFi = TCPIP_STACK_NetHandle("MRF24W");
    if(hWiFi)
    {
        TCPIP_STACK_SetNotifyEvents(hWiFi, TCPIP_EV_RX_ALL|TCPIP_EV_TX_ALL|TCPIP_EV_RXTX_ERRORS);
        TCPIP_STACK_SetNotifyHandler(hWiFi, StackNotification, 0);
    }
#endif  // defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)


#if defined(APP_USE_IPERF)
    IperfConsoleInit();
    iperfOk = IperfAppInit(TCPIP_HOSTS_CONFIGURATION[0].interface);
#endif

	// Now that all items are initialized, begin the co-operative
	// multitasking loop.  This infinite loop will continuously 
	// execute all stack-related tasks, as well as your own
	// application's functions.  Custom functions should be added
	// at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while(1)
    {
        // Blink LED0 (right most one) every second.
        if(SYS_TICK_Get() - startTick >= SYS_TICK_TicksPerSecondGet()/2ul)
        {
            startTick = SYS_TICK_Get();
            LED0_IO ^= 1;
        }

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        TCPIP_STACK_Task();


		// Process application specific tasks here.
		// For this demo app, this will include the Generic TCP 
		// client and servers, and the SNMP, Ping, and SNMP Trap
		// demos.  Following that, we will process any IO from
		// the inputs on the board itself.
		// Any custom modules or processing you need to do should
		// go here.
		#if defined(TCPIP_STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE)
		GenericTCPClient();
		#endif
		
		#if defined(TCPIP_STACK_USE_GENERIC_TCP_SERVER_EXAMPLE)
		GenericTCPServer();
		#endif
		
		#if defined(TCPIP_STACK_USE_SMTP_CLIENT)
		SMTPDemo();
		#endif
		
		#if defined(TCPIP_STACK_USE_ICMP_CLIENT) || defined (TCPIP_STACK_USE_ICMP_SERVER) || defined (TCPIP_STACK_USE_IPV6)
        // use ping on the default interface
		PingDemoTask();
		#endif
		
		#if defined(TCPIP_STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
		//User should use one of the following SNMP demo
		// This routine demonstrates V1 or V2 trap formats with one variable binding.
		SNMPTrapDemo();
		
		#if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3)
		//This routine provides V2 format notifications with multiple (3) variable bindings
		//User should modify this routine to send v2 trap format notifications with the required varbinds.
		//SNMPV2TrapDemo();
		#endif 
		if(gSendTrapFlag)
			SNMPSendTrap();
		#endif
		
		#if defined(TCPIP_STACK_USE_BERKELEY_API)
		BerkeleyTCPClientDemo();
		BerkeleyTCPServerDemo();
		BerkeleyUDPClientDemo(0);
		#endif


#if defined(APP_USE_IPERF)
        IperfConsoleProcess();
        if (iperfOk) IperfAppCall();    // Only running in case of init succeed
        IperfConsoleProcessEpilogue();
#endif

        // If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the console display, UART, and Announce
        // service
        // We use the default interface
        for (i = 0; i < sizeof(TCPIP_HOSTS_CONFIGURATION)/sizeof(*TCPIP_HOSTS_CONFIGURATION); i++)
        {	
            TCPIP_NET_HANDLE netH = TCPIP_STACK_NetHandle(TCPIP_HOSTS_CONFIGURATION[i].interface);
			if((uint32_t)dwLastIP[i].Val != TCPIP_STACK_NetAddress(netH))
			{
				dwLastIP[i].Val = TCPIP_STACK_NetAddress(netH);
				
				SYS_CONSOLE_MESSAGE(TCPIP_HOSTS_CONFIGURATION[i].interface);
				SYS_CONSOLE_MESSAGE(" new IP Address: ");
			
				DisplayIPValue(dwLastIP[i]);
			
				SYS_CONSOLE_MESSAGE("\r\n");
			
            }
        }

#if defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)
        if(stackNotifyCnt)
        {
            stackNotifyCnt = 0;
            ProcessNotification(stackNotifyHandle);
        }
#endif  // defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)
	}
}
Ejemplo n.º 16
0
//
// Main application entry point.
//
int main(void)
{

#if defined(HOST_CM_TEST)
    DWORD t1 = 0;
    char st[80];
    BOOL host_scan = FALSE;
    UINT16 scan_count = 0;
#endif

    static IPV4_ADDR dwLastIP[sizeof (TCPIP_HOSTS_CONFIGURATION) / sizeof (*TCPIP_HOSTS_CONFIGURATION)];
    int i, nNets;

#if defined(SYS_USERIO_ENABLE)    
    static SYS_TICK startTick = 0;
    int32_t LEDstate=SYS_USERIO_LED_DEASSERTED;
#endif  // defined(SYS_USERIO_ENABLE)

    TCPIP_NET_HANDLE netH;
    const char  *netName=0;
    const char  *netBiosName;

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
    char mDNSServiceName[] = "MyWebServiceNameX ";     // base name of the service Must not exceed 16 bytes long
                                                       // the last digit will be incremented by interface
#endif  // defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)

    // perform system initialization
    if(!SYS_Initialize())
    {
        return 0;
    }


    SYS_CONSOLE_MESSAGE("\r\n\n\n ---  TCPIP Demo Starts!  --- \r\n");
    SYS_OUT_MESSAGE("TCPIPStack " TCPIP_STACK_VERSION "  ""                ");

    // Initialize the TCPIP stack
    if (!TCPIP_STACK_Init(TCPIP_HOSTS_CONFIGURATION, sizeof (TCPIP_HOSTS_CONFIGURATION) / sizeof (*TCPIP_HOSTS_CONFIGURATION),
            TCPIP_STACK_MODULE_CONFIG_TBL, sizeof (TCPIP_STACK_MODULE_CONFIG_TBL) / sizeof (*TCPIP_STACK_MODULE_CONFIG_TBL)))
    {
        return 0;
    }

    // Display the names associated with each interface
    // Perform mDNS registration if mDNS is enabled
    nNets = TCPIP_STACK_NetworksNo();
    for(i = 0; i < nNets; i++)
    {
        netH = TCPIP_STACK_IxToNet(i);
        netName = TCPIP_STACK_NetName(netH);
        netBiosName = TCPIP_STACK_NetBIOSName(netH);

#if defined(TCPIP_STACK_USE_NBNS)
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS enabled\r\n", netName, netBiosName);
#else
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS disabled\r\n", netName, netBiosName);
#endif  // defined(TCPIP_STACK_USE_NBNS)

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
        mDNSServiceName[sizeof(mDNSServiceName) - 2] = '1' + i;
        mDNSServiceRegister( netH
            , mDNSServiceName                   // name of the service
            ,"_http._tcp.local"                 // type of the service
            ,80                                 // TCP or UDP port, at which this service is available
            ,((const BYTE *)"path=/index.htm")  // TXT info
            ,1                                  // auto rename the service when if needed
            ,NULL                               // no callback function
            ,NULL);                             // no application context
#endif //TCPIP_STACK_USE_ZEROCONF_MDNS_SD
    }

#if defined (TCPIP_STACK_USE_IPV6)
    TCPIP_ICMPV6_RegisterCallback(ICMPv6Callback);
#endif

#if defined(TCPIP_STACK_USE_ICMP_CLIENT)
    ICMPRegisterCallback(PingProcessIPv4);
#endif


#if defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)
    TCPIP_NET_HANDLE hWiFi = TCPIP_STACK_NetHandle("MRF24W");
    if (hWiFi)
    {
       TCPIP_STACK_RegisterHandler(hWiFi, TCPIP_EV_RX_ALL | TCPIP_EV_TX_ALL | TCPIP_EV_RXTX_ERRORS, StackNotification, 0);
    }
#endif  // defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)

#if defined(WF_UPDATE_FIRMWARE_UART_24G)
    extern bool    WF_FirmwareUpdate_Uart_24G(void);
    WF_FirmwareUpdate_Uart_24G();
#endif

  

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while (1)
    {
        SYS_Tasks();

       
#if defined(SYS_USERIO_ENABLE)    
        // Blink LED0 (right most one) every second.
        if (SYS_TICK_Get() - startTick >= SYS_TICK_TicksPerSecondGet() / 2ul)
        {
            startTick = SYS_TICK_Get();
            LEDstate ^= SYS_USERIO_LED_ASSERTED;
            SYS_USERIO_SetLED(SYS_USERIO_LED_0, LEDstate);
        }
#endif  // defined(SYS_USERIO_ENABLE)   

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        TCPIP_STACK_Task();

        // Process application specific tasks here.
        // For this demo app, this will include the Generic TCP
        // client and servers, and the SNMP, Ping, and SNMP Trap
        // demos.  Following that, we will process any IO from
        // the inputs on the board itself.
        // Any custom modules or processing you need to do should
        // go here.
#if defined(TCPIP_STACK_USE_TCP) && defined(APP_USE_FTP_CLIENT_DEMO)
        FTPClient();
#endif        
#if defined(TCPIP_STACK_USE_TCP) && defined(APP_USE_GENERIC_TCP_CLIENT_DEMO)
        GenericTCPClient();
#endif

#if defined(TCPIP_STACK_USE_TCP) && defined(APP_USE_GENERIC_TCP_SERVER_DEMO)
        GenericTCPServer();
#endif

#if defined(TCPIP_STACK_USE_SMTP_CLIENT) && defined(APP_USE_SMTP_CLIENT_DEMO)
        SMTPDemo();
#endif

#if (defined(TCPIP_STACK_USE_ICMP_CLIENT) || defined (TCPIP_STACK_USE_IPV6)) && defined(APP_USE_PING_DEMO)
        // use ping on the default interface
        PingDemoTask();
#endif

#if defined(TCPIP_STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)

        // User should use one of the following SNMP demo
        // This routine demonstrates V1 or V2 trap formats with one variable binding.

        //SNMPTrapDemo(); //This function sends the both SNMP trap version1 and 2 type of notifications

        #if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3)
        //This routine provides V2 format notifications with multiple (3) variable bindings
        //User should modify this routine to send v2 trap format notifications with the required varbinds.
            SNMPV2TrapDemo(); //This function sends the SNMP trap version 2 type of notifications
        #endif

         /*
         SNMPSendTrap() is used to send trap notification to previously configured ip address if trap notification is enabled.
         There are different trap notification code. The current implementation sends trap for authentication failure (4).
           PreCondition: If application defined event occurs to send the trap. Declare a notification flag and update as the event occurs.
           Uncomment the below function if the application requires.

         if(notification flag is updated by the application as a predefined event occured)
        {
            SNMPSendTrap();
        }

        */

#endif 


#if defined(TCPIP_STACK_USE_BERKELEY_API) && defined(APP_USE_BERKELEY_API_DEMO)
        BerkeleyTCPClientDemo();
        BerkeleyTCPServerDemo();
        BerkeleyUDPClientDemo(0);
#endif

        // If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the console display, UART, and Announce
        // service
        // We use the default interface
        for (i = 0; i < sizeof (TCPIP_HOSTS_CONFIGURATION) / sizeof (*TCPIP_HOSTS_CONFIGURATION); i++)
        {
            netH = TCPIP_STACK_NetHandle(TCPIP_HOSTS_CONFIGURATION[i].interface);
            if ((uint32_t) dwLastIP[i].Val != TCPIP_STACK_NetAddress(netH))
            {
                dwLastIP[i].Val = TCPIP_STACK_NetAddress(netH);

                SYS_CONSOLE_PRINT("Interface Name is: %s\r\n", TCPIP_HOSTS_CONFIGURATION[i].interface);
                SYS_CONSOLE_MESSAGE("New IP Address is: "); DisplayIPValue(dwLastIP[i]);
                SYS_CONSOLE_MESSAGE("\r\n");
            }
        }

#if defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)
        if (stackNotifyCnt)
        {
            stackNotifyCnt = 0;
            ProcessNotification(stackNotifyHandle);
        }
#endif  // defined(TCPIP_STACK_USE_EVENT_NOTIFICATION)

#if defined(WF_UPDATE_FIRMWARE_TCPCLIENT_24G)
    void WF_FirmwareUpdate_TcpClient_24G(void);
    WF_FirmwareUpdate_TcpClient_24G();
#endif //defined(WF_UPDATE_FIRMWARE_TCPCLIENT_24G)

#if defined(HOST_CM_TEST)
       switch (g_event)
        {
            case WF_EVENT_CONNECTION_PERMANENTLY_LOST:
            case WF_EVENT_CONNECTION_FAILED:
                g_event = 0xff;             // clear current event
                // if host scan is active, it can be forced inactive by connection/re-connection process
                // so just reset host scan state to inactive.
                host_scan = FALSE;          // host scan inactive
                SYS_CONSOLE_MESSAGE("Reconnecting....\r\n");
                WF_Connect();
                break;
            case WF_EVENT_CONNECTION_SUCCESSFUL:
                g_event = 0xff;             // clear current event
                // if host scan is active, it can be forced inactive by connection/re-connection process
                // so just reset host scan state to inactive.
                host_scan = FALSE;          // host scan inactive
                break;
            case WF_EVENT_SCAN_RESULTS_READY:
                g_event = 0xff;             // clear current event
                host_scan = FALSE;          // host scan inactive
                // Scan results are valid - OK to retrieve
                if (SCANCXT.numScanResults > 0)
                {
                    SCAN_SET_DISPLAY(SCANCXT.scanState);
                    SCANCXT.displayIdx = 0;
                    while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState))
                         WFDisplayScanMgr();
                }
                break;
           case WF_EVENT_CONNECTION_TEMPORARILY_LOST:
                // This event can happened when CM in module is enabled.
                g_event = 0xff;         // clear current event
                // if host scan is active, it can be forced inactive by connection/re-connection process
                // so just reset host scan state to inactive.
                host_scan = FALSE;      // host scan inactive
                break;
            default:
                //sprintf(st,"skip event = %d\r\n",g_event);
                //SYS_CONSOLE_MESSAGE(st);
                break;
        }

       if (g_DhcpSuccessful)
       {

       /* Send and Receive UDP packets */
        if(UDPIsOpened(socket1))
        {
            // UDP TX every 10 msec
            if(SYS_TICK_Get() - timeudp >= SYS_TICK_TicksPerSecondGet() / 100)
            {
                timeudp = SYS_TICK_Get();
                tx_number++;
                LED0_IO ^= 1;
                sprintf(str,"rem=%12lu",tx_number);
                for(cntstr=16;cntstr<999;cntstr++)
                    str[cntstr]=cntstr;
                str[999]=0;
                // Send tx_number (formatted in a string)
                if(UDPIsTxPutReady(socket1,1000)!=0)
                {
                    UDPPutString(socket1,(BYTE *)str);
                    UDPFlush(socket1);
                    SYS_CONSOLE_MESSAGE(".");
                }
            }

            // UDP RX tx_number of remote board
            if(UDPIsGetReady(socket1)!=0)
            {
                LED1_IO ^= 1;
                UDPGetArray(socket1,(BYTE *)str,1000);
                str[16]=0;
                //sprintf((char*)LCDText,"%sloc=%12lu",str,tx_number); // Write on EXP16 LCD local and remote TX number
                //strcpypgm2ram(LCDText,str);
                //LCDUpdate();
                SYS_CONSOLE_MESSAGE("Rx");

            }
        }

        // Do host scan
         if((SYS_TICK_Get() - t1) >= SYS_TICK_TicksPerSecondGet() * 20)
        {
            t1 = SYS_TICK_Get();
            if (!host_scan)             // allow host scan if currently inactive
            {
                sprintf(st,"%d Scanning ..... event = %d\r\n",++scan_count, g_event);
                SYS_CONSOLE_MESSAGE(st);
                host_scan = TRUE;       // host scan active
                WF_Scan(0xff);          // scan on all channels
            }
        }
       } // DHCP status
       
#endif  //HOST_CM_TEST


    }
}
Ejemplo n.º 17
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );

    //Startup
    __builtin_disable_interrupts();

    // set the CP0 CONFIG register to indicate that
    // kseg0 is cacheable (0x3) or uncacheable (0x2)
    // see Chapter 2 "CPU for Devices with M4K Core"
    // of the PIC32 reference manual
    __builtin_mtc0(_CP0_CONFIG, _CP0_CONFIG_SELECT, 0xa4210583);

    // no cache on this chip!

    // 0 data RAM access wait states
    BMXCONbits.BMXWSDRM = 0x0;

    // enable multi vector interrupts
    INTCONbits.MVEC = 0x1;

    // disable JTAG to be able to use TDI, TDO, TCK, TMS as digital
    DDPCONbits.JTAGEN = 0;

    __builtin_enable_interrupts();

ANSELBbits.ANSB13 = 0; // 0 for digital, 1 for analog
ANSELBbits.ANSB15 = 0; // 0 for digital, 1 for analog

    T2CONbits.TCKPS = 0;	//Setting prescaler to 1 (0 corresponds to 1)
    PR2 = 39999;            //Setting PR for timer 2 to 39999
    TMR2 = 0;				//Setting Timer 2 to 0
    OC1CONbits.OCTSEL = 0;	//Telling OC1 to use timer 2
    OC1CONbits.OCM = 0b110;	//Telling OC1 to use PWM without the fault
    OC1RS = 20000;			//Setting initial duty cycle to 20000/(39999+1)*100% = 50%
    OC1R = 20000;			//Updating duty cycles to 20000/(39999+1)*100% = 50%
    T2CONbits.ON = 1;		//turn on timer
    OC1CONbits.ON = 1;		//turn on OC code

// set up USER pin as input
    TRISBbits.TRISB13 = 1; // set pin B13 to be digital INPUT
    // U1RXRbits.U1RXR = 0b0011; // set U1RX to pin B13 (Input pin from User button)

// set up LED1 pin as a digital output
    TRISBbits.TRISB7 = 0; // set pin B7 to be digital OUTPUT
    // LATBbits.LATB7 = 1;
    // RPB7Rbits.RPB7R = 0b0001; //set B7 to U1TX (Output pin for LED1)
    
// set up LED2 as OC1 using Timer2 at 1kHz
    // TRISBbits.TRISB15 = 0; // set B15 to digital OUTPUT
    // RPB15Rbits.RPB15R = 0b0101; // set B15 to U1TX (Output pin for OC1)

// set up A0 as AN0
    ANSELAbits.ANSA0 = 1;
    AD1CON3bits.ADCS = 3;
    AD1CHSbits.CH0SA = 0;
    AD1CON1bits.ADON = 1;
    
// Accelerometer
    acc_setup();
    volatile short accels[3]; // accelerations for the 3 axes
    volatile short mags[3]; // magnetometer readings for the 3 axes
    volatile short temp;

// Display
    display_init();
    
    while (1){
     // invert pin every 0.5s, set PWM duty cycle % to the pot voltage output %
        SYS_Tasks ( );
        /*
        if (accels[0]>0 && accels[1]>0){
            x_line_point = (float)((float)accels[0]/16000*64) + 64;
            y_line_point = (float)((float)accels[1]/16000*32) + 32;
  
                for (i=64;i<x_line_point;i++){
                    display_pixel_set(31, i, 1);
                    display_pixel_set(32, i, 1);
                    display_pixel_set(33, i, 1);
                    }
                for (j=32;j<y_line_point;j++){
                    display_pixel_set(j, 63, 1);
                    display_pixel_set(j, 64, 1);
                    display_pixel_set(j, 65, 1);
                }
        }
        else if (accels[0]>0 && accels[1]<0){
            x_line_point = (float)((float)accels[0]/16000*64) + 64;
            y_line_point = (float)((float)accels[1]/16000*32) + 32;
                for (i=64;i<x_line_point;i++){
                    display_pixel_set(31, i, 1);
                    display_pixel_set(32, i, 1);
                    display_pixel_set(33, i, 1);
                    }

                for (j=32;j>y_line_point;j--){
                    display_pixel_set(j, 63, 1);
                    display_pixel_set(j, 64, 1);
                    display_pixel_set(j, 65, 1);
                }
        }
        else if (accels[0]<0 && accels[1]>0){
            x_line_point = (float)((float)accels[0]/16000*64) + 64;
            y_line_point = (float)((float)accels[1]/16000*32) + 32;
                for (i=64;i>x_line_point;i--){
                    display_pixel_set(31, i, 1);
                    display_pixel_set(32, i, 1);
                    display_pixel_set(33, i, 1);
                    }

                for (j=32;j<y_line_point;j++){
                    display_pixel_set(j, 63, 1);
                    display_pixel_set(j, 64, 1);
                    display_pixel_set(j, 65, 1);
                }
        }
        else if (accels[0]<0 && accels[1]<0){
            x_line_point = (float)((float)accels[0]/16000*64) + 64;
            y_line_point = (float)((float)accels[1]/16000*32) + 32;
                for (i=64;i>x_line_point;i--){
                    display_pixel_set(31, i, 1);
                    display_pixel_set(32, i, 1);
                    display_pixel_set(33, i, 1);
                    }

                for (j=32;j>y_line_point;j--){
                    display_pixel_set(j, 63, 1);
                    display_pixel_set(j, 64, 1);
                    display_pixel_set(j, 65, 1);
                }
        }
        
        display_pixel_set(31,63,1);
        display_pixel_set(31,64,1);
        display_pixel_set(31,65,1);
        display_pixel_set(32,63,1);
        display_pixel_set(32,64,1);
        display_pixel_set(32,65,1);
        display_pixel_set(33,63,1);
        display_pixel_set(33,64,1);
        display_pixel_set(33,65,1);
        display_draw();
         * */
        
        }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 18
0
//
// Main application entry point.
//
int main(void)
{
    static SYS_TICK startTick = 0;
    static IPV4_ADDR dwLastIP[2] = { {-1}, {-1} };
    IPV4_ADDR           ipAddr;

    SYS_USERIO_LED_STATE LEDstate = SYS_USERIO_LED_DEASSERTED;
    int                 i, nNets;
    TCPIP_NET_HANDLE    netH;
    const char          *netName, *netBiosName;

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
    char mDNSServiceName[] = "MyWebServiceNameX ";     // base name of the service Must not exceed 16 bytes long
                                                       // the last digit will be incremented by interface
#endif  // defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)


    // perform system initialization
    SYS_Initialize(0);

    SYS_CONSOLE_MESSAGE("\r\n\n\n ---  TCPIP Demo Starts!  --- \r\n");
    SYS_OUT_MESSAGE("TCPIPStack " TCPIP_STACK_VERSION "  ""                ");

        // Display the names associated with each interface
    nNets = TCPIP_STACK_NumberOfNetworksGet();
    for(i = 0; i < nNets; i++)
    {

        netH = TCPIP_STACK_IndexToNet(i);
        netName = TCPIP_STACK_NetNameGet(netH);
        netBiosName = TCPIP_STACK_NetBIOSName(netH);

#if defined(TCPIP_STACK_USE_NBNS)
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS enabled\r\n", netName, netBiosName);
#else
        SYS_CONSOLE_PRINT("    Interface %s on host %s - NBNS disabled\r\n", netName, netBiosName);
#endif  // defined(TCPIP_STACK_USE_NBNS)

#if defined (TCPIP_STACK_USE_ZEROCONF_MDNS_SD)
        mDNSServiceName[sizeof(mDNSServiceName) - 2] = '1' + i;
        TCPIP_MDNS_ServiceRegister( netH
                , mDNSServiceName                   // name of the service
                ,"_http._tcp.local"                 // type of the service
                ,80                                 // TCP or UDP port, at which this service is available
                ,((const uint8_t *)"path=/index.htm")  // TXT info
                ,1                                  // auto rename the service when if needed
                ,NULL                               // no callback function
                ,NULL);                             // no application context
#endif //TCPIP_STACK_USE_ZEROCONF_MDNS_SD
    }

#if defined(WF_UPDATE_FIRMWARE_UART_24G)
    extern bool    WF_FirmwareUpdate_Uart_24G(void);
    WF_FirmwareUpdate_Uart_24G();
#endif

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while (1)
    {
        SYS_Tasks();

        // Blink LED0 every second.
        if (SYS_TICK_Get() - startTick >= SYS_TICK_TicksPerSecondGet() / 2ul)
        {
            startTick = SYS_TICK_Get();
            LEDstate ^= SYS_USERIO_LED_ASSERTED;
            SYS_USERIO_SetLED(SYS_USERIO_LED_0, LEDstate);
        }

        // if the IP address of an interface has changed
        // display the new value on the system console
        nNets = TCPIP_STACK_NumberOfNetworksGet();
        for (i = 0; i < nNets; i++)
        {
            netH = TCPIP_STACK_IndexToNet(i);
            ipAddr.Val = TCPIP_STACK_NetAddress(netH);
            if(dwLastIP[i].Val != ipAddr.Val)
            {
                dwLastIP[i].Val = ipAddr.Val;

                SYS_CONSOLE_MESSAGE(TCPIP_STACK_NetNameGet(netH));
                SYS_CONSOLE_MESSAGE(" IP Address: ");
                SYS_CONSOLE_PRINT("%d.%d.%d.%d \r\n", ipAddr.v[0], ipAddr.v[1], ipAddr.v[2], ipAddr.v[3]);
            }
        }

#if (WF_DEFAULT_NETWORK_TYPE == WF_NETWORK_TYPE_SOFT_AP)

        if (g_scan_done) {
           if (g_prescan_waiting) {
               SYS_CONSOLE_MESSAGE((const char*)"\n SoftAP prescan results ........ \r\n\n");
               SCANCXT.displayIdx = 0;
               extern void WFDisplayScanMgr(void);
               while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                   WFDisplayScanMgr();
               }
               SYS_CONSOLE_MESSAGE((const char*)"\r\n ");

       #if defined(WF_CS_TRIS)
                Demo_Wifi_Connect();
       #endif
               g_scan_done = 0;
               g_prescan_waiting = 0;
           }
        }
#endif // (WF_DEFAULT_NETWORK_TYPE == WF_NETWORK_TYPE_SOFT_AP)

#if defined(WF_UPDATE_FIRMWARE_UART_24G)
    WF_FirmwareUpdate_Uart_24G();
#endif

#if defined(WF_UPDATE_FIRMWARE_TCPCLIENT_24G)
    WF_FirmwareUpdate_TcpClient_24G();
#endif

    }
}
Ejemplo n.º 19
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );
    // string used for OLED
    char str[200];

    ANSELBbits.ANSB13 = 0; // make analog input digital
    U1RXRbits.U1RXR = 0b0000; // set U1RX to pin A2
    RPB15Rbits.RPB15R = 0b0101; // set B15 to U1TX

    TRISBbits.TRISB13 = 1;     // set up USER pin as input
    TRISBbits.TRISB7 = 0;    // set up LED1 pin as a digital output

    APP_USBDeviceEventHandler();
    
    __builtin_disable_interrupts();

    // set the CP0 CONFIG register to indicate that
    // kseg0 is cacheable (0x3) or uncacheable (0x2)
    // see Chapter 2 "CPU for Devices with M4K Core"
    // of the PIC32 reference manual
    __builtin_mtc0(_CP0_CONFIG, _CP0_CONFIG_SELECT, 0xa4210583);

    // no cache on this chip!

    // 0 data RAM access wait states
    BMXCONbits.BMXWSDRM = 0x0;

    // enable multi vector interrupts
    INTCONbits.MVEC = 0x1;

    // disable JTAG to be able to use TDI, TDO, TCK, TMS as digital
    DDPCONbits.JTAGEN = 0;

     // set up accelerometer
    acc_setup();

    __builtin_enable_interrupts();

    short accels[3];    // accelerations for the 3 axes
    short mags[3];      // magnetometer readings for the 3 axes
    short temp;         // temperature

    display_init();

    while ( true )
    {
        /* Maintain state machines of all polled MPLAB Harmony modules. */
                // read the accelerometer from all three axes
        // the accelerometer and the pic32 are both little endian by default (the lowest address has the LSB)
        // the accelerations are 16-bit twos compliment numbers, the same as a short
        acc_read_register(OUT_X_L_A, (unsigned char *) accels, 6);
        // need to read all 6 bytes in one transaction to get an update.
        acc_read_register(OUT_X_L_M, (unsigned char *) mags, 6);

        // read the temperature data. Its a right justified 12 bit two's compliment number
        acc_read_register(TEMP_OUT_L, (unsigned char *) &temp, 2);


        display_clear();
//      sprintf(str, "Hello world %d!", accels);

        int x_acc = accels[0]*64/16000;
        int y_acc = accels[1]*32/16000;
        int xxx,yyy;

        if (x_acc>=0){
            if(x_acc>64) x_acc=64;
            for (xxx=0;xxx<x_acc;xxx++){
                display_pixel_set(31,64-xxx,1);
                display_pixel_set(32,64-xxx,1);
                display_pixel_set(33,64-xxx,1);
            }
        }
        else{
            if(x_acc<-64) x_acc=-64;
            for (xxx=0;xxx>x_acc;xxx--){
                display_pixel_set(31,64-xxx,1);
                display_pixel_set(32,64-xxx,1);
                display_pixel_set(33,64-xxx,1);
            }
        }

        if (y_acc>=0){
            if(y_acc>32) y_acc=32;
            for (yyy=0;yyy<y_acc;yyy++){
                display_pixel_set(32-yyy,63,1);
                display_pixel_set(32-yyy,64,1);
                display_pixel_set(32-yyy,65,1);
            }
        }
        else{
            if(y_acc<-32) y_acc=-32;
            for (yyy=0;yyy>y_acc;yyy--){
                display_pixel_set(32-yyy,63,1);
                display_pixel_set(32-yyy,64,1);
                display_pixel_set(32-yyy,65,1);
            }
        }

        display_draw();

        SYS_Tasks ( );

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}
Ejemplo n.º 20
0
int main ( void )
{
    /* Initialize all MPLAB Harmony modules, including application(s). */
    SYS_Initialize ( NULL );

    __builtin_disable_interrupts();

    // set the CP0 CONFIG register to indicate that kseg0 is cacheable (0x3)
    __builtin_mtc0(_CP0_CONFIG, _CP0_CONFIG_SELECT, 0xa4210583);

    // 0 data RAM access wait states
    BMXCONbits.BMXWSDRM = 0x0;

    // enable multi vector interrupts
    INTCONbits.MVEC = 0x1;

    // disable JTAG to get pins back
    DDPCONbits.JTAGEN = 0;
    
    // initialize I2C
    initI2C2();
    
    // initialize IMU
    initIMU();
    
    // initialize SPI, LCD
//    SPI1_init();
//    LCD_init();
    
    __builtin_enable_interrupts();
    
//    LCD_clearScreen(BLACK);   
//    char message[MAX_LENGTH];  
    unsigned char data[14];
//    float accX, accY;
    _CP0_SET_COUNT(0);
    while ( true )
    {
        if (_CP0_GET_COUNT() > 480000) {    // 50 Hz     
            i2c_read_multiple(IMU_ADDRESS, OUT_TEMP_L, data, 14);
            temp_raw = data[1] << 8 | data[0];
            gyroX_raw = data[3] << 8 | data[2];
            gyroY_raw = data[5] << 8 | data[4];
            gyroZ_raw = data[7] << 8 | data[6];
            accX_raw = data[9] << 8 | data[8];
            accY_raw = data[11] << 8 | data[10];
            accZ_raw = data[13] << 8 | data[12];
            
//            accX = accX_raw * 2.0 / 32768; // accel in g
//            accY = accY_raw * 2.0 / 32768; // accel in g
//            accZ = accZ_raw * 2.0 / 32768; // accel in g
            
//            sprintf(message, "temp raw: %x    ", temp_raw);
//            LCD_drawString(10, 10, message, WHITE);
//            
//            sprintf(message, "accX: %f g    ", accX);
//            LCD_drawString(10, 20, message, WHITE);
//            
//            sprintf(message, "accY: %f g    ", accY);
//            LCD_drawString(10, 30, message, WHITE);
//            
//            sprintf(message, "accZ: %f g    ", accZ);
//            LCD_drawString(10, 40, message, WHITE);
//            
//            sprintf(message, "gyroX raw: %i    ", gyroX_raw);
//            LCD_drawString(10, 50, message, WHITE);
//            
//            sprintf(message, "gyroY raw: %i    ", gyroY_raw);
//            LCD_drawString(10, 60, message, WHITE);
//            
//            sprintf(message, "gyroZ raw: %i    ", gyroZ_raw);
//            LCD_drawString(10, 70, message, WHITE);
            
            _CP0_SET_COUNT(0);
        }
        
        /* Maintain state machines of all polled MPLAB Harmony modules. */
        SYS_Tasks ( );

    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}