Ejemplo n.º 1
0
/* There are three possibilities for the step rate calculation that keep the
   step rate error to under 0.2% of the desired value, from within 0.5 to 2KHz:
   from 78 to 20Khz, Prescale is 1:8, Rollover = (F_PB/8-1)/PPS
   from 10 to 77Hz, Prescale is 1:64, Rollover = (F_PB/64-1)/PPS
   from 0.5 to 10Hz, Set rollover for a constant 1Khz, and increment to reach
   the desired time, Prescale is 1:8, Rollover = (F_PB/8-1)/1000 and the number
   of times to repeat is (1000-1)/PPS + 1                                     */
char Stepper_Init(unsigned short int rate)
{
    unsigned short int overflowPeriod;
    if (rate > TWENTY_KILOHERTZ) return ERROR;
    dbprintf("\nInitializing Stepper Module");
    stepCount = 0;
    stepperMode = full;
    stepperSpeed = rate;
    overflowReps = 0;
    // Initialize hardware (no current flow)
    COIL_A_DIRECTION = 1;
    COIL_B_DIRECTION = 1;
    ShutDownDrive();
    TRIS_COIL_A_DIRECTION = 0;
    TRIS_COIL_A_ENABLE = 0;
    TRIS_COIL_B_DIRECTION = 0;
    TRIS_COIL_B_ENABLE = 0;
    // Calculate overflow time and prescalar
    overflowPeriod = CalculateOverflowPeriod(rate);
    dbprintf("\nOverflow Period: %u",overflowPeriod);
    dbprintf("\nNumber of Reps: %u",overflowReps);
    // Setup timer and interrupt
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_8, overflowPeriod);
//    OpenTimer5(T5_ON | T5_IDLE_STOP | T5_GATE_OFF | T5_PS_1_8 | T5_SOURCE_INT,overflowPeriod);
//    OpenTimer5(T5_ON | T5_PS_1_8 | T5_SOURCE_INT, overflowPeriod);
    ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_3 );
    mT3IntEnable(1);
    stepperState = inited;
    return SUCCESS;
}
Ejemplo n.º 2
0
//determines the amount of time before the timer interrupts
void Timer3Init(int Time)
{
    int frequency = 0;
    //the frequency is calculated as follows : 10000000 / Prescaler / Hertz
    //Hertz is calculates as follows : 1 / (((msec per div) / 40) * 10^-3))

    if (Time == 0)
    {
        frequency = 50; //  10000000/1/200000 = 50
    }
    else if (Time == 1)
    {
        frequency = 125; // 10000000/1/80000 = 125
    }
    else if (Time == 2)
    {
        frequency = 250; // 10000000/1/40000 = 250
    }
    else if (Time == 3)
    {
        frequency = 500; // 10000000/1/20000 = 500
    }
    else if (Time == 4)
    {
        frequency = 1250; // 10000000/1/8000 = 1250
    }

    OpenTimer3(T3_ON | T3_IDLE_CON | T3_SOURCE_INT | T3_PS_1_1 | T3_GATE_OFF, frequency);

    mT3SetIntPriority(1);
    mT3IntEnable(1);

}
Ejemplo n.º 3
0
// setup timers and initialize motors to off
void MotorInit(void)
{
    int i;

    M1_FORWARD_TRIS = OUTPUT_PIN;
    M1_FORWARD_IO = 0;
    M1_BACKWARD_TRIS = OUTPUT_PIN;
    M1_BACKWARD_IO = 0;
    M2_FORWARD_TRIS = OUTPUT_PIN;
    M2_FORWARD_IO = 0;
    M2_BACKWARD_TRIS = OUTPUT_PIN;
    M2_BACKWARD_IO = 0;
    M3_FORWARD_TRIS = OUTPUT_PIN;
    M3_FORWARD_IO = 0;
    M3_BACKWARD_TRIS = OUTPUT_PIN;
    M3_BACKWARD_IO = 0;
    M4_FORWARD_TRIS = OUTPUT_PIN;
    M4_FORWARD_IO = 0;
    M4_BACKWARD_TRIS = OUTPUT_PIN;
    M4_BACKWARD_IO = 0;

    OpenOC1(OC_ON | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE,2560,2560);
    OpenOC2(OC_ON | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE,2560,2560);
    OpenOC3(OC_ON | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE,2560,2560);
    //OpenOC4(OC_ON | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE,2560,2560);
    OpenTimer3(T3_ON | T3_PS_1_1, MOTOR_TIMER_PERIOD);

}
/*********************************************************************
* Function: void TouchInit(void)
*
* PreCondition: none
*
* Input: none
*
* Output: none
*
* Side Effects: none
*
* Overview: sets ADC 
*
* Note: none
*
********************************************************************/
void TouchInit(void){
#define TIME_BASE (GetPeripheralClock()*SAMPLE_PERIOD)/4000000

    // Initialize ADC
	AD1CON1 = 0x080E0;  			// Turn on, auto-convert
	AD1CON2 = 0;					// AVdd, AVss, int every conversion, MUXA only
	AD1CON3 = 0x1FFF;			    // 31 Tad auto-sample, Tad = 256*Tcy
#if defined(__dsPIC33F__) || defined(__PIC24H__)
	AD1CHS0 = ADC_POT;
	AD1PCFGL = 0;                   // All inputs are analog  
	AD1PCFGLbits.PCFG11 = AD1PCFGLbits.PCFG12 = 1;    
#else
    AD1CHS = ADC_POT;  
    AD1PCFG = 0;                    // All inputs are analog   
#endif 
	AD1CSSL = 0;					// No scanned inputs
  
#ifdef __PIC32MX__
    OpenTimer3(T3_ON | T3_PS_1_8, TIME_BASE);
    ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_4);
#else
    // Initialize Timer3
    TMR3 = 0;
    PR3 = TIME_BASE;
    T3CONbits.TCKPS = 1;         // Set prescale to 1:8
    IFS0bits.T3IF = 0;           // Clear flag
    IEC0bits.T3IE = 1;           // Enable interrupt
    T3CONbits.TON = 1;           // Run timer  
#endif
}
Ejemplo n.º 5
0
extern void timerStart(timer * pTimer, const timerCalc * pTimerCalc)
{
  pTimer->m_TimerCalc = *pTimerCalc;

  const uint16_t        PrescalerBits = pTimer->m_TimerCalc.PrescalerBits;
  const uint16_t        PriorityBits  = pTimer->m_TimerCalc.PriorityBits;
  const uint16_t        Ticks         = pTimer->m_TimerCalc.Ticks;
  const timer_tCallback pCallback     = pTimer->m_pCallback;

  pTimer->m_OverflowCount = pTimer->m_TimerCalc.OverflowCount;

  switch (pTimer->m_TimerNumber) {
    case 1: 
      OpenTimer1(T1_ON | T1_SOURCE_INT | PrescalerBits, Ticks);
      ConfigIntTimer1((pCallback == NULL ? T1_INT_OFF : T1_INT_ON) | PriorityBits);
      break;
    case 2: 
      OpenTimer2(T2_ON | T2_SOURCE_INT | PrescalerBits, Ticks);
      ConfigIntTimer2((pCallback == NULL ? T2_INT_OFF : T2_INT_ON) | PriorityBits);
      break;
    case 3: 
      OpenTimer3(T3_ON | T3_SOURCE_INT | PrescalerBits, Ticks);
      ConfigIntTimer3((pCallback == NULL ? T3_INT_OFF : T3_INT_ON) | PriorityBits);
      break;
    case 4: 
      OpenTimer4(T4_ON | T4_SOURCE_INT | PrescalerBits, Ticks);
      ConfigIntTimer4((pCallback == NULL ? T4_INT_OFF : T4_INT_ON) | PriorityBits);
      break;
    case 5: 
      OpenTimer5(T5_ON | T5_SOURCE_INT | PrescalerBits, Ticks);
      ConfigIntTimer5((pCallback == NULL ? T5_INT_OFF : T5_INT_ON) | PriorityBits);
      break;
  }
}
Ejemplo n.º 6
0
// 20Hz ISR
void initTimer3Interrupt(void)
{
    OpenTimer3(T3_ON | T3_PS_1_256, 15625);
    mT3SetIntPriority(1);
    mT3ClearIntFlag();
    mT3IntEnable(1);
}
Ejemplo n.º 7
0
/*  Function:
    void SYSTEM_TickInit(void)
    Initialize Timer3 timer for 500usec system timer
    *****************************************************************************/
void SYSTEM_TickInit(void)
{
  OpenTimer3(T3_ON | T3_PS_1_256, TICK_PERIOD);
  ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_1);

/*  OpenTimer4(T4_ON | T4_PS_1_256, TICK4_PERIOD);
  ConfigIntTimer4(T4_INT_ON | T4_INT_PRIOR_1);*/

}
Ejemplo n.º 8
0
void PWM_Init(void)
{
#ifdef _TARGET_440H
#else
	// Tmr1 Init
	// STEP 1. configure the Timer1
	OpenTimer3(T3_ON | T3_SOURCE_INT | T3_IDLE_CON | T3_PS_1_1, TMR3_RELOAD);

    // Enable OC | 16 bit Mode  | Timer1 is selected | Continuous O/P   | OC Pin High , S Compare value, Compare value
    OpenOC1( OC_ON | OC_TIMER_MODE16 | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE , 0, 0 );
    OpenOC2( OC_ON | OC_TIMER_MODE16 | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE , 0, 0 );
#endif
}
Ejemplo n.º 9
0
// Exported functions
void buzzer_setup()
{
  pinMode(BUZZER_PIN, OUTPUT);
  pin_write(BUZZER_PIN, LOW);
  buzzing = false;
  is_buzzer_on = false;
  alarm = 1;

  // There are two timers capable of PWM, 2 and 3. We are using 2 for the modem,
  // so use 3 for the buzzer.
  OpenTimer3(T3_ON | T3_PS_1_8, PWM_PERIOD);
  ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_5);
}
Ejemplo n.º 10
0
//Timer 3 setup function
int sysServiceConfigT3(unsigned int T3conval, unsigned int T3perval,
                        unsigned int T3intconval){
    //Todo: is there any way to have a compile time semaphore here?
    if(T3_already_confgured){
        return -1;
    }
    else{
        T3_already_confgured = 1;
        OpenTimer3(T3conval, T3perval);
        ConfigIntTimer3(T3intconval);
        return 0;
    }
}
Ejemplo n.º 11
0
void TMR3_init(unsigned int reload , void (*func)())
{
	// Enagle TMR1 interrrupt,16 bit counter, with internal clock, No prescalar
	OpenTimer3(TIMER_INT_ON & T3_16BIT_RW & T3_SOURCE_INT & T3_PS_1_1 & T3_SYNC_EXT_OFF );
	// Reload value for 1ms overflow
	WriteTimer3(reload);
	// Make timer1 interrupt high priority
  	//IPR2bits.TMR3IP = 1;

	tmr[2].reload = reload;
	tmr[2].func = func;

}
Ejemplo n.º 12
0
/**
 * Backlight is open drain on pin D2, controlled by OC4, using Timer 3
 * Contrast uses normal CMOS with OC3, also driven by Timer 3
 */
void lcd_init(void) {
	//Set backlight to open drain
	mPORTDOpenDrainOpen( BIT_2 );

	//Start the timer for contrast/brightness PWM
	OpenTimer3(T3_ON, LCD_PWMPERIOD);

	//Enable contrast control
	OpenOC3( OC_ON | OC_TIMER_MODE16 | OC_TIMER3_SRC | OC_CONTINUE_PULSE | OC_LOW_HIGH , LCD_PWMPERIOD, 0x500 );

	//Enable brightness control
	OpenOC4( OC_ON | OC_TIMER_MODE16 | OC_TIMER3_SRC | OC_CONTINUE_PULSE | OC_LOW_HIGH , LCD_PWMPERIOD, 0x500 );
}
Ejemplo n.º 13
0
void HCSR04_Init(){
    OpenTimer2(T2_ON | T2_PS_1_64 | T2_32BIT_MODE_ON, 0xFFFF);
    OpenTimer3(T3_ON | T3_PS_1_64, 0xFFFF);

    OpenCapture5(IC_ON | IC_IDLE_CON | IC_CAP_32BIT | IC_INT_1CAPTURE | IC_EVERY_EDGE | IC_FEDGE_RISE);

    SetPriorityIntIC5(IC_INT_PRIOR_4 | IC_INT_SUB_PRIOR_3);

    EnableIntIC5;

    lastDistance = 0.0;
    reading = 0;
    scale = (SOUND_SPEED*3200.0)/GetPeripheralClock(); // 6400 = 64 * 100 = prescale * cm/m. 3200 = Ida e volta
}
void setupPWMForIR()
{
    // init OC3 module
    OpenOC3(OC_OFF | OC_TIMER3_SRC | OC_PWM_FAULT_PIN_DISABLE, 0, 0);

    // init Timer3 mode and period (PR2) 40 kHz freq: 1 / 40 kHz = (X + 1) / 80MHz * 1
    //80 000 / 20 = X + 1 = 3999
    //80 000 / 38 = X + 1 = 2104
    //80 000 / 36 = X + 1 = 2221
    //80 000 / 40 = X + 1 = 2001
    OpenTimer3(T3_ON | T3_PS_1_1 | T3_SOURCE_INT, MAX_DUTY);

    SetDCOC3PWM(PR3 / 2);
}
Ejemplo n.º 15
0
Archivo: ask.c Proyecto: 10to7/RFIDler
// h/w clock ASK emulator - initialise data pointers for ISR and start timer 2
// args: clock pulsewidth (NOT period!), data as array of 0/1, repeat
void write_ASK_HW_clock(unsigned int pulse, BYTE *data, unsigned int tpb, unsigned int repeat)
{
    // convert to ticks
    pulse= CONVERT_TO_TICKS(pulse);
    // we only need to tick once per bit
    pulse *= (unsigned long) tpb;

    // point globals at data for ISR
    EMU_ThisBit= *data;
    EMU_Data= data + 1;
    EMU_Reset_Data= data;
    EMU_DataBitRate= 1;
    EMU_SubCarrier_T0= 1;

    EMU_Repeat= repeat;

    // if we're manchester or bi-phase encoding, we want to clock twice as fast so we can toggle on half-bit
    if(RFIDlerConfig.Manchester || RFIDlerConfig.BiPhase)
    {
        pulse /= 2;
        EMU_SubCarrier_T0 *= 2;
        EMU_DataBitRate *= 2;
    }

    // make sure no clock is running
    stop_HW_clock();
    
    // set mode
    EmulationMode= MOD_MODE_ASK_OOK;

    // make sure nobody's using our timer
    CloseTimer3();

    // tri-state on, clock low
    READER_CLOCK_ENABLE_ON();
    CLOCK_COIL= LOW;

    // emulator mode
    COIL_MODE_EMULATOR();

    // this is also a semaphore so the rest of the code knows we're running
    mLED_Emulate_On();

    // start timer - ISR will send data
    OpenTimer3( T3_ON | T3_PS_1_1 | T3_SOURCE_INT, pulse - 1L);
    mT3SetIntPriority(6);
    mT3ClearIntFlag();
    mT3IntEnable(TRUE);
}
Ejemplo n.º 16
0
void TickInit(void)
{

    // Initialize Timer4
    #ifdef __PIC32MX__
    OpenTimer3(T3_ON | T3_PS_1_8, TICK_PERIOD);
    ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_4);
    #else
    TMR3 = 0;
    PR3 = TICK_PERIOD;
    IFS0bits.T3IF = 0;  //Clear flag
    IEC0bits.T3IE = 1;  //Enable interrupt
    T3CONbits.TON = 1;  //Run timer
    #endif
    
}
Ejemplo n.º 17
0
inline void Timer3_Setup(void)
{
    OpenTimer3(
            T3_OFF &
            T3_IDLE_CON &
            T3_GATE_OFF &
            T3_PS_1_256 &
            T3_SOURCE_INT,
            39063); //for 250 ms.

    ConfigIntTimer3(
            T3_INT_PRIOR_3 &
            T3_INT_ON
                    );

    return;
}
Ejemplo n.º 18
0
/**
 * \brief The PIC18 init function.
 *
 * \todo Initialize the USART and timer/ccp.
 */
void pic18_init(void)
{
	/* 
	 * Setup the interrupts, all interrupts are by default low prio and
	 * global low priority interrupts should be disabled.
	 */
	IPR1 = IPR2 = INTCON = 0;
	RCONbits.IPEN = 1;
	INTCONbits.GIEH = 1;

	/* 
	 * Open the usart for 9600 baud and eight bit transmission,
	 * no interrupts. For more info about this call see the C18
	 * library manual.
	 */
	OpenUSART(
			USART_TX_INT_OFF & USART_RX_INT_OFF &
			USART_ASYNCH_MODE & USART_EIGHT_BIT &
			USART_CONT_RX & USART_BRGH_HIGH,
			127
			);
	
	/* Set the pins for the USART. */
	TRISCbits.TRISC6 = 0;
	TRISCbits.TRISC7 = 1;

	/*
	 * Let's use CCP2 and Timer3, this is mainly due to CCP1
	 * being an enhanced CCP that we don't really need.
	 */
	OpenTimer3(
			TIMER_INT_ON & T3_16BIT_RW &
			T3_SOURCE_INT & T1_CCP1_T3_CCP2 &
			T3_PS_1_8
			);

	/* Make sure the timer is OFF. */
	T3CONbits.TMR3ON = 0;
	TMR3L = TMR3H = 0;

	/* Reset the CCP2 module. */
	CCP2OFF();
}
Ejemplo n.º 19
0
void initPIC() {
    SYSTEMConfig(SYS_FREQ, SYS_CFG_ALL);

    initLEDs();
    initSerialNU32v2();

    // Setup and turn off electromagnets
    EMAG1 = 0;
    EMAG2 = 0;
    TRISEbits.TRISE7 = 0;
    TRISCbits.TRISC1 = 0;

    // Direction Output
    DIR = 1;
    TRISAbits.TRISA9 = 0;

    setup_counters();

    CloseADC10();
#define PARAM1  ADC_MODULE_ON | ADC_FORMAT_INTG | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON
#define PARAM2  ADC_VREF_AVDD_AVSS | ADC_OFFSET_CAL_DISABLE | ADC_SCAN_ON | ADC_SAMPLES_PER_INT_16 | ADC_ALT_BUF_OFF | ADC_ALT_INPUT_OFF
#define PARAM3  ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_31
#define PARAM4  ENABLE_AN0_ANA | ENABLE_AN1_ANA | ENABLE_AN2_ANA | ENABLE_AN3_ANA | ENABLE_AN5_ANA | ENABLE_AN15_ANA
    OpenADC10(PARAM1, PARAM2, PARAM3, PARAM4, 0);
    EnableADC10();

    // 20kHz PWM signal, duty from 0-1000, pin D3
    OpenTimer2(T2_ON | T2_PS_1_4, MAX_DUTY);
    OpenOC4(OC_ON | OC_TIMER2_SRC | OC_PWM_FAULT_PIN_DISABLE, 0, 0);
    SetDCOC4PWM(0);

    // 200 Hz ISR
    OpenTimer3(T3_ON | T3_PS_1_256, (6250/4 - 1));
    //OpenTimer3(T3_ON | T3_PS_1_256, (62500 - 1));
    mT3SetIntPriority(1);
    mT3ClearIntFlag();
    mT3IntEnable(1);

    INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
    INTEnableSystemMultiVectoredInt();
}
Ejemplo n.º 20
0
// h/w clock PSK emulator - initialise data pointers for ISR and start timer 2
// args: clock period, data as array of 0/1, fc per bit, sub-carrier ticks, repeat
void write_PSK1_HW_clock(unsigned int period, BYTE *data, unsigned int fcpb, unsigned int c0, unsigned int repeat)
{
    // convert to ticks
    period= CONVERT_TO_TICKS(period);
    // for psk we want a full clock cycle, not a tick
    period *= 2;

    // point globals at data for ISR
    EMU_ThisBit= *data;
    EMU_Data= data + 1;
    EMU_Reset_Data= data;
    EMU_DataBitRate= fcpb;
    EMU_SubCarrier_T0= c0;
    EMU_Repeat= repeat;

    // set mode
    EmulationMode= MOD_MODE_PSK1;

    // make sure no clock is running
    stop_HW_clock();

    // make sure nobody's using our timers
    CloseTimer3();

    // tri-state on, clock low
    READER_CLOCK_ENABLE_ON();
    CLOCK_COIL= LOW;

    // emulator mode
    COIL_MODE_EMULATOR();

    // this is also a semaphore so the rest of the code knows we're running
    mLED_Emulate_On();

    // start timer - ISR will send data
    OpenTimer3( T3_ON | T3_PS_1_1 | T3_SOURCE_INT, period / 2L - 1L);
    mT3SetIntPriority(6);
    mT3ClearIntFlag();
    mT3IntEnable(TRUE);
}
Ejemplo n.º 21
0
Archivo: fsk.c Proyecto: 10to7/RFIDler
// h/w clock FSK emulator - initialise data pointers for ISR and start timer 2
// args: clock pulsewidth (NOT period!), data as array of 0/1, T0 sub-carrier ticks, T1 sub-carrier ticks, repeat
void write_FSK_HW_clock(unsigned long pulse, BYTE *data, unsigned int tpb, unsigned int t0, unsigned int t1, unsigned int repeat)
{
    // convert to ticks
    pulse= CONVERT_TO_TICKS(pulse);

    // point globals at data for ISR
    EMU_ThisBit= *data;
    EMU_Data= data + 1;
    EMU_Reset_Data= data;
    EMU_Repeat= repeat;
    EMU_DataBitRate= tpb;
    EMU_SubCarrier_T0= t0;
    EMU_SubCarrier_T1= t1;

    // set mode
    EmulationMode= MOD_MODE_FSK;

    // make sure no clock is running
    stop_HW_clock();

    // make sure nobody's using our timer
    CloseTimer3();

    // emulator mode
    COIL_MODE_EMULATOR();

    // tri-state on, clock low
    READER_CLOCK_ENABLE_ON();
    CLOCK_COIL= LOW;

    // this is also a semaphore so the rest of the code knows we're running
    mLED_Emulate_On();

    // start timer - ISR will send data
    OpenTimer3( T3_ON | T3_PS_1_1 | T3_SOURCE_INT, pulse - 1L);
    mT3SetIntPriority(6);
    mT3ClearIntFlag();
    mT3IntEnable(TRUE);
}
Ejemplo n.º 22
0
Archivo: ir.c Proyecto: nevers/preamp
void initIR(void) {
    TRISCbits.TRISC2 = 1; //Set pin 2 of PORTC to input as it used for capturing
    INTCON = 0; //Disable all interrupts

    // Configure timer 1 - It is used for demodulating the NEC command and address.
    OpenTimer1(TIMER_INT_ON & T1_16BIT_RW & T1_SOURCE_INT & T1_PS_1_1 & T1_SOURCE_CCP);

    // Configure timer 3
    OpenTimer3(TIMER_INT_ON & T3_16BIT_RW & T3_SOURCE_INT & T3_PS_1_8);

    // Disable all timers
    T1CONbits.TMR1ON = 0;
    T3CONbits.TMR3ON = 0;

    // Configure interrupts
    PIE1bits.TMR1IE = 1;
    PIE2bits.TMR3IE = 1;
    INTCONbits.PEIE = 1;
    INTCONbits.GIE = 1; //Enable global interrupts

    resetIR();
    disableIR();
}
Ejemplo n.º 23
0
void timersInit()
{
    //T4 is input from encoder. Read from TMR4 to see number of ticks counted.
    T4CON = 0x0;                //T4 disabled
    T4CONSET = 0x0002;          //T4 External Clock Source, 1:1 prescaler
    TMR4 = 0x0;                 //Reset T4 counter
    PR4 = 0xffff;               //Set T4 period to max
    //mT4ClearIntFlag();          //clear interrupt flag
    //mT4SetIntPriority(7);       //set Timer4 Interrupt Priority
    //mT4IntEnable(1);            //enable timer4 interrupts
    T4CONSET = 0x8000;          //T4 enable

    //T5 is input from encoder. Read from TMR5 to see number of ticks counted.
    T5CON = 0x0;                //T5 disabled
    T5CONSET = 0x0002;          //T5 External Clock Source, 1:1 prescaler
    TMR5 = 0x0;                 //Reset T5
    PR5 = 0xffff;               //Set T5 period to max
    //mT5ClearIntFlag();          //clear T5 interrupt flag
    //mT5SetIntPriority(2);       //set Timer5 Interrupt Priority
    //mT5IntEnable(1);            //enable timer5 interrupts
    T5CONSET = 0x8000;          //T5 enable

        //The following code snippet opens and uses Timer1,2,3 as an interrupt.
        //Open Timer1 with 1:8 prescaler (80MHz -> 10MHz), with period of 1250, therefore tick = 8kHz.
        OpenTimer1(T1_ON | T1_PS_1_8 | T1_SOURCE_INT, 1000);
        ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_2);

        OpenTimer2(T2_ON | T2_PS_1_8 | T2_SOURCE_INT, 1000);
        ConfigIntTimer2(T2_INT_ON | T2_INT_PRIOR_2);

        OpenTimer3(T3_ON | T3_PS_1_8 | T3_SOURCE_INT, 1000);
        ConfigIntTimer1(T3_INT_ON | T3_INT_PRIOR_2);

        INTEnableSystemMultiVectoredInt();

}
Ejemplo n.º 24
0
char Stepper_ChangeStepRate(unsigned short int rate)
{
    unsigned short int overflowPeriod;
    if ((rate > TWENTY_KILOHERTZ)||(stepperState == off)) return ERROR;
    dbprintf("\nChanging step rate");
    //T5CONbits.ON = 0; // halt timer5
    //overflowPeriod = CalculateOverflowPeriod(rate);
    //WritePeriod5(overflowPeriod);
    //if (stepperState != halted) {
    //    T3CONbits.ON = 1; // restart timer3
    //}
    // Calculate overflow time and prescalar
    overflowPeriod = CalculateOverflowPeriod(rate);
    dbprintf("\nOverflow Period: %u",overflowPeriod);
    dbprintf("\nNumber of Reps: %u",overflowReps);
    // Setup timer and interrupt
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_8, overflowPeriod);
//    OpenTimer5(T5_ON | T5_IDLE_STOP | T5_GATE_OFF | T5_PS_1_8 | T5_SOURCE_INT,overflowPeriod);
//    OpenTimer5(T5_ON | T5_PS_1_8 | T5_SOURCE_INT, overflowPeriod);
    ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_3 );
    mT3IntEnable(1);
    stepperSpeed = rate;
    return SUCCESS;
}
Ejemplo n.º 25
0
int setupTimer(int timer, int frequency, int priority)
{
    int tX_on;
    int tX_source_int;
    int tX_int_on;
    int tX_ps_1_X;

    long countTo = SYS_FREQ / frequency;

    switch (timer)
    {
        case 1:
            tX_on = T1_ON;
            tX_source_int = T1_SOURCE_INT;
            tX_int_on = T1_INT_ON;

            while (1)
            {
                if (countTo >= 65536)
                {
                    countTo = countTo / 8;
                    if (countTo >= 65536)
                    {
                        countTo = countTo / 8;
                        if (countTo >= 65536)
                        {
                            countTo = countTo / 8;
                            if (countTo >= 65536)
                            {
                                return 0;
                            }
                            tX_ps_1_X = T1_PS_1_256;
                            break;
                        }
                        tX_ps_1_X = T1_PS_1_64;
                        break;
                    }
                    tX_ps_1_X = T1_PS_1_8;
                    break;
                }
                else
                {
                    tX_ps_1_X = T1_PS_1_1;
                    break;
                }
            }
            OpenTimer1(tX_on | tX_source_int | tX_ps_1_X, countTo);
            ConfigIntTimer1(tX_int_on | priority);
            break;

        case 2:
            tX_on = T2_ON;
            tX_source_int = T2_SOURCE_INT;
            tX_int_on = T2_INT_ON;

            while (1)
            {
                if (countTo >= 65536)
                {
                    countTo = countTo / 2;
                    if (countTo >= 65536)
                    {
                        countTo = countTo / 2;
                        if (countTo >= 65536)
                        {
                            countTo = countTo / 2;
                            if (countTo >= 65536)
                            {
                                countTo = countTo / 2;
                                if (countTo >= 65536)
                                {
                                    countTo = countTo / 2;
                                    if (countTo >= 65536)
                                    {
                                        countTo = countTo / 2;
                                        if (countTo >= 65536)
                                        {
                                            countTo = countTo / 2;
                                            if (countTo >= 65536)
                                            {
                                                return 0;
                                            }
                                            tX_ps_1_X = T2_PS_1_256;
                                            break;
                                        }
                                        tX_ps_1_X = T2_PS_1_64;
                                        break;
                                    }
                                    tX_ps_1_X = T2_PS_1_32;
                                    break;
                                }
                                tX_ps_1_X = T2_PS_1_16;
                                break;
                            }
                            tX_ps_1_X = T2_PS_1_8;
                            break;
                        }
                        tX_ps_1_X = T2_PS_1_4;
                        break;
                    }
                    tX_ps_1_X = T2_PS_1_2;
                    break;
                }
                else
                {
                    tX_ps_1_X = T2_PS_1_1;
                    break;
                }
            }
            OpenTimer2(tX_on | tX_source_int | tX_ps_1_X, countTo);
            ConfigIntTimer2(tX_int_on | priority);
            break;

        case 3:
            tX_on = T3_ON;
            tX_source_int = T3_SOURCE_INT;
            tX_int_on = T3_INT_ON;

            while (1)
            {
                if (countTo >= 65536)
                {
                    countTo = countTo / 2;
                    if (countTo >= 65536)
                    {
                        countTo = countTo / 2;
                        if (countTo >= 65536)
                        {
                            countTo = countTo / 2;
                            if (countTo >= 65536)
                            {
                                countTo = countTo / 2;
                                if (countTo >= 65536)
                                {
                                    countTo = countTo / 2;
                                    if (countTo >= 65536)
                                    {
                                        countTo = countTo / 2;
                                        if (countTo >= 65536)
                                        {
                                            countTo = countTo / 2;
                                            if (countTo >= 65536)
                                            {
                                                return 0;
                                            }
                                            tX_ps_1_X = T3_PS_1_256;
                                            break;
                                        }
                                        tX_ps_1_X = T3_PS_1_64;
                                        break;
                                    }
                                    tX_ps_1_X = T3_PS_1_32;
                                    break;
                                }
                                tX_ps_1_X = T3_PS_1_16;
                                break;
                            }
                            tX_ps_1_X = T3_PS_1_8;
                            break;
                        }
                        tX_ps_1_X = T3_PS_1_4;
                        break;
                    }
                    tX_ps_1_X = T3_PS_1_2;
                    break;
                }
                else
                {
                    tX_ps_1_X = T3_PS_1_1;
                    break;
                }
            }
            OpenTimer3(tX_on | tX_source_int | tX_ps_1_X, countTo);
            ConfigIntTimer3(tX_int_on | priority);
            break;

        case 4:
            tX_on = T4_ON;
            tX_source_int = T4_SOURCE_INT;
            tX_int_on = T4_INT_ON;

            while (1)
            {
                if (countTo >= 65536)
                {
                    countTo = countTo / 2;
                    if (countTo >= 65536)
                    {
                        countTo = countTo / 2;
                        if (countTo >= 65536)
                        {
                            countTo = countTo / 2;
                            if (countTo >= 65536)
                            {
                                countTo = countTo / 2;
                                if (countTo >= 65536)
                                {
                                    countTo = countTo / 2;
                                    if (countTo >= 65536)
                                    {
                                        countTo = countTo / 2;
                                        if (countTo >= 65536)
                                        {
                                            countTo = countTo / 2;
                                            if (countTo >= 65536)
                                            {
                                                return 0;
                                            }
                                            tX_ps_1_X = T4_PS_1_256;
                                            break;
                                        }
                                        tX_ps_1_X = T4_PS_1_64;
                                        break;
                                    }
                                    tX_ps_1_X = T4_PS_1_32;
                                    break;
                                }
                                tX_ps_1_X = T4_PS_1_16;
                                break;
                            }
                            tX_ps_1_X = T4_PS_1_8;
                            break;
                        }
                        tX_ps_1_X = T4_PS_1_4;
                        break;
                    }
                    tX_ps_1_X = T4_PS_1_2;
                    break;
                }
                else
                {
                    tX_ps_1_X = T4_PS_1_1;
                    break;
                }
            }
            OpenTimer4(tX_on | tX_source_int | tX_ps_1_X, countTo);
            ConfigIntTimer4(tX_int_on | priority);
            break;
    }
    return 1;
}
Ejemplo n.º 26
0
int main(void) {
	timesec=0;
	// set PIC32 to max computing power
	SYSTEMConfig(SYS_FREQ, SYS_CFG_ALL);
	INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR);
	INTEnableSystemMultiVectoredInt();   
    initLEDs(); 	
    LED0 = 1;
    LED1 = 1;
    initSerialNU32v2();
	setup_counters();

  	CloseADC10();
  	#define PARAM1  ADC_MODULE_ON | ADC_FORMAT_INTG | ADC_CLK_AUTO | ADC_AUTO_SAMPLING_ON
  	#define PARAM2  ADC_VREF_AVDD_AVSS | ADC_OFFSET_CAL_DISABLE | ADC_SCAN_ON | ADC_SAMPLES_PER_INT_16 | ADC_ALT_BUF_OFF | ADC_ALT_INPUT_OFF
  	#define PARAM3  ADC_CONV_CLK_INTERNAL_RC | ADC_SAMPLE_TIME_31
  	#define PARAM4  ENABLE_AN0_ANA | ENABLE_AN1_ANA | ENABLE_AN2_ANA | ENABLE_AN3_ANA | ENABLE_AN5_ANA | ENABLE_AN15_ANA
  	OpenADC10( PARAM1, PARAM2, PARAM3, PARAM4,0);
  	EnableADC10();


    // Setup and turn off electromagnets
    EMAG1 = 0; EMAG2 = 0; 
    TRISEbits.TRISE7 = 0; TRISCbits.TRISC1 = 0;
	//Direction Output
	DIR = 1;
  	TRISAbits.TRISA9 = 0;
	//g-select Outputs
	GSEL1 = 0; GSEL2 = 0;
  	TRISEbits.TRISE2 = 0; TRISCbits.TRISC13= 0;
  	//0g Inputs
  	TRISAbits.TRISA0 = 1;
  	TRISAbits.TRISA4 = 1;

  	// 20kHz PWM signal, duty from 0-1000, pin D3
  	OpenTimer2(T2_ON | T2_PS_1_4, 1000);
  	OpenOC4(OC_ON | OC_TIMER2_SRC | OC_PWM_FAULT_PIN_DISABLE, 0, 0);
  	HBridgeDuty = 0;
  	SetDCOC4PWM(HBridgeDuty);

    // 20Hz ISR
    OpenTimer3(T3_ON | T3_PS_1_256, 15625);
    mT3SetIntPriority(1);
    mT3ClearIntFlag();
    mT3IntEnable(1);


	while(1) {
		if(start){
			EMAG2=0;
			SetDCOC4PWM(100);
			delaysec(delay1);
			SetDCOC4PWM(1000);		
			delaysec(delay2);
			SetDCOC4PWM(500);
			delaysec(delay3);
			EMAG2=1;
			SetDCOC4PWM(0);	

//			EMAG1=0;
//			SetDCOC4PWM(900);
//			DIR = 0;
//			delaysec(delay1);
//			SetDCOC4PWM(0);
//			delaysec(delay2);
//			SetDCOC4PWM(700);
//			delaysec(delay1);
//			SetDCOC4PWM(1000);
//			EMAG1=1;

			start=0;
		}
	}
}
Ejemplo n.º 27
0
/**************************************************************************************************
Initialise the video components
***************************************************************************************************/
void initVideo(void) {

    AutoLineWrap = 1;

    // test if there is a monitor plugged into the VGA connector
    CNPUASET = (1 << 4);                                            // set a pullup on the video output pin
    uSec(300);                                                      // allow it to settle
    //vga = !PORTAbits.RA4;                                           // the pin will be pulled low if the monitor is there
    CNPUACLR = (1 << 4);

    ////////////////////////////
    // setup SPI2 which is the video generator.  the output of this module is a stream of bits which are the pixels in a horiz scan line
    //if(vga)
        PPSOutput(3, RPA4, SDO2);                                    // B5 is the video out for VGA [color]]
    //else
    //    PPSOutput(3, RPB2, SDO2);                                   // B2 is the video out for composite
    PPSInput(4, SS2, RPB9);                                         // B9 is the framing input [horizontal synch]
    #define P_VIDEO_SPI         2                                   // the SPI peripheral used for video
    #define P_SPI_INPUT         SPI2BUF                             // input buffer for the SPI peripheral
    #define P_SPI_INTERRUPT     _SPI2_TX_IRQ                        // interrupt used by the SPI peripheral when it needs more data

    ////////////////////////////
    // the horizontal sync uses Timer 3 and Output Compare 3 to generate the pulse and interrupt level 7
    PPSOutput(4, RPB14, OC3);                                       // B14 is the horizontal sync output (ie, the output from OC3)
    #define P_VID_OC_OPEN       OpenOC3                             // the function used to open the output compare
    #define P_VID_OC_REG        OC3R                                // the output compare register

    ////////////////////////////
    // the vertical sync uses B13
    TRISBCLR = (1<<13);                                             // Vert sync output used by VGA
    #define P_VERT_SET_HI		LATBSET = (1 << 13)                 // set vert sync hi
    #define P_VERT_SET_LO		LATBCLR = (1 << 13)                 // set vert sync lo

    // calculate the paramaters for each video mode and setup Timer 3 to generate the horiz synch and interrupt on its leading edge
    //if(vga) {
        // set up for VGA output
	    HRes = VGA_HRES;                                            // HRes is the number of horiz pixels to use
	    HBuf = VGA_HBUFF * 32;                                      // HBuf is the horiz buffer size (in pixels)
        ConfigBuffers(Option[O_LINES24]);                           // setup the buffer pointers and VBuf, VRes
		VC[0] = VGA_VSYNC_N;										// setup the table used to count lines
		VC[1] = VGA_POSTEQ_N;
	    P_VID_OC_OPEN(OC_ON | OC_TIMER3_SRC | OC_CONTINUE_PULSE, 0, VGA_HSYNC_T);	// enable the output compare which is used to time the width of the horiz sync pulse
	    OpenTimer3( T3_ON | T3_PS_1_1 | T3_SOURCE_INT, VGA_LINE_T-1);	            // enable timer 3 and set to the horizontal scanning frequency
	//}
    /*else if(Option[O_PAL]) {
		// this is for the PAL composite output and is the same as VGA with timing differences
	    VBuf = VRes = PAL_VRES;
	    HRes = PAL_HRES;
	    HBuf = PAL_HBUFF * 32;                                      // HBuf is the horiz buffer size (in pixels)
        ConfigBuffers(0);
	    SvSyncT = PAL_LINE_T - C_HSYNC_T;
		VC[0] = C_VSYNC_N;
		VC[1] = PAL_POSTEQ_N;
		VC[2] = PAL_VRES;
		VC[3] = PAL_PREEQ_N;
	    P_VID_OC_OPEN(OC_ON | OC_TIMER3_SRC | OC_CONTINUE_PULSE, 0, C_HSYNC_T);	    // enable the output compare which is used to time the width of the horiz sync pulse
	    OpenTimer3(T3_ON | T3_PS_1_1 | T3_SOURCE_INT, PAL_LINE_T-1);	            // enable timer 3 and set to the horizontal scanning frequency
    }
    */
    
    /*
	else {
		// this is for the NTSC composite output and is similar again
	    VBuf = VRes = NTSC_VRES;
	    HRes = NTSC_HRES;
	    HBuf = NTSC_HBUFF * 32;                                     // HBuf is the horiz buffer size (in pixels)
        ConfigBuffers(0);
	    SvSyncT = NTSC_LINE_T - C_HSYNC_T;
		VC[0] = C_VSYNC_N;
		VC[1] = NTSC_POSTEQ_N;
		VC[2] = NTSC_VRES;
		VC[3] = NTSC_PREEQ_N;
	    P_VID_OC_OPEN(OC_ON | OC_TIMER3_SRC | OC_CONTINUE_PULSE, 0, C_HSYNC_T);	    // enable the output compare which is used to time the width of the horiz sync pulse
	    OpenTimer3(T3_ON | T3_PS_1_1 | T3_SOURCE_INT, NTSC_LINE_T-1);	            // enable timer 3 and set to the horizontal scanning frequency
	}
    */

    // set priority level 7 for the timer 3 interrupt (horiz synch) and enable it
    mT3SetIntPriority(7);
    mT3IntEnable(1);

    // initialise the state machine and set the count so that the first interrupt will increment the state
	VState = SV_PREEQ;
    VCount = 1;

    // setup the SPI channel then DMA channel which will copy the memory bitmap buffer to the SPI channel
    //if(vga) {
        // open the SPI in framing mode.  Note that SPI_OPEN_DISSDI will disable the input (which we do not need)
	    SpiChnOpen(P_VIDEO_SPI, SPICON_ON | SPICON_MSTEN | SPICON_MODE32 | SPICON_FRMEN | SPICON_FRMSYNC | SPICON_FRMPOL | SPI_OPEN_DISSDI, VGA_PIX_T);
        SPI2CON2 = (1<<9) | (1<<8);                                         // instruct the SPI module to ignore any errors that might occur
        DmaChnOpen(1, 1, DMA_OPEN_DEFAULT);                                 // setup DMA 1 to send data to SPI channel 2
        DmaChnSetEventControl(1, DMA_EV_START_IRQ_EN | DMA_EV_START_IRQ(P_SPI_INTERRUPT));
	    DmaChnSetTxfer(1, (void*)VideoBuf, (void *)&P_SPI_INPUT, HBuf/8, 4, 4);
    //}
    /*
    else {
	    SpiChnOpen(P_VIDEO_SPI, SPICON_ON | SPICON_MSTEN | SPICON_MODE32 | SPICON_FRMEN | SPICON_FRMSYNC | SPICON_FRMPOL | SPI_OPEN_DISSDI, C_PIX_T);
        SPI2CON2 = (1<<9) | (1<<8);                                         // instruct the SPI module to ignore any errors that might occur
        DmaChnOpen(1, 1, DMA_OPEN_DEFAULT);    	                            // setup DMA 1 is the blank padding at the start of a scan line
        DmaChnSetEventControl(1, DMA_EV_START_IRQ_EN | DMA_EV_START_IRQ(P_SPI_INTERRUPT));
	    DmaChnSetTxfer(1, (void*)zero, (void *)&P_SPI_INPUT, C_BLANKPAD, 4, 4);
    	DmaChnOpen( 0, 0, DMA_OPEN_DEFAULT);		                        // setup DMA 0 to pump the data from the graphics buffer to the SPI peripheral
    	DmaChnSetEventControl(0, DMA_EV_START_IRQ_EN | DMA_EV_START_IRQ(P_SPI_INTERRUPT));
	    DmaChnSetTxfer(0, (void*)VideoBuf, (void *)&P_SPI_INPUT, HBuf/8 + 6, 4, 4);
    	DmaChnSetControlFlags(0, DMA_CTL_CHAIN_EN | DMA_CTL_CHAIN_DIR);    	// chain DMA 0 so that it will start on completion of the DMA 1 transfer
    }
     */
}
Ejemplo n.º 28
0
void  ADC_TmrInit (void)
{
    OpenTimer3(T3_ON | T3_PS_1_8 | T3_SOURCE_INT, 0);                  /* Timer 3 enabled with 1:8 prescaler                        */
}    
Ejemplo n.º 29
0
// ************************************************************
// Main application entry point.
// ************************************************************
int main(void)
{
    static DWORD t = 0;	
    static DWORD dwLastIP = 0;
#if defined (EZ_CONFIG_STORE)
    static DWORD ButtonPushStart = 0;
#endif
    UINT8         channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN;  // WF_PRESCAN
    tWFScanResult bssDesc;
#if 0	
    INT8 TxPower;   // Needed to change MRF24WG transmit power. 
#endif

    // Initialize application specific hardware
    InitializeBoard();

    // Initialize TCP/IP stack timer
    TickInit();                        //  Timer 3 interrupt for refreshing motor status inside here
    demo_TickInit();

    #if defined(STACK_USE_MPFS2)
    // Initialize the MPFS File System
	// Generate a WifiGDemoMPFSImg.c file using the MPFS utility (refer to Convert WebPages to MPFS.bat)
	// that gets compiled into source code and programmed into the flash of the uP.
    MPFSInit();
    #endif
	
    // Initialize Stack and application related NV variables into AppConfig.
    InitAppConfig();

    // Initialize core stack layers (MAC, ARP, TCP, UDP) and
    // application modules (HTTP, SNMP, etc.)
    StackInit();

    Exosite_Init("microchip","dv102412",IF_WIFI, 0);

#if 0	
    // Below is used to change MRF24WG transmit power. 
    // This has been verified to be functional (Jan 2013) 
    if (AppConfig.networkType == WF_SOFT_AP)
    {
        WF_TxPowerGetMax(&TxPower);                       
        WF_TxPowerSetMax(TxPower);       
    }
#endif

    // Run Self Test if SW0 pressed on startup
    if(SW0_IO == 1)
        SelfTest();

    #ifdef STACK_USE_TELNET_SERVER
        // Initialize Telnet and
        // Put Remote client in Remote Character Echo Mode
        TelnetInit();
        putc(0xff, stdout);     // IAC = Interpret as Command
        putc(0xfe, stdout);     // Type of Operation = DONT
        putc(0x22, stdout);     // Option = linemode
        putc(0xff, stdout);     // IAC = Interpret as Command
        putc(0xfb, stdout);     // Type of Operation = DO
        putc(0x01, stdout);     // Option = echo
    #endif


    #if defined ( EZ_CONFIG_SCAN )
    // Initialize WiFi Scan State Machine NV variables
    WFInitScan();
    #endif
	
    // WF_PRESCAN: Pre-scan before starting up as SoftAP mode  
    WF_CASetScanType(MY_DEFAULT_SCAN_TYPE);
    WF_CASetChannelList(channelList, sizeof(channelList));
		
    if (WFStartScan() == WF_SUCCESS) {
       SCAN_SET_DISPLAY(SCANCXT.scanState);
       SCANCXT.displayIdx = 0;
    }
	
    // Needed to trigger g_scan_done		
    WFRetrieveScanResult(0, &bssDesc);		
  	
    #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    // Initialize Zeroconf Link-Local state-machine, regardless of network type.
    ZeroconfLLInitialize();
    #endif
	
    #if defined(STACK_USE_ZEROCONF_MDNS_SD)
    // Initialize DNS Host-Name from TCPIPConfig.h, regardless of network type.
    mDNSInitialize(MY_DEFAULT_HOST_NAME);
    mDNSServiceRegister(
            // (const char *) AppConfig.NetBIOSName,        // base name of the service. Ensure uniformity with CheckHibernate().
            (const char *) "DemoWebServer",          // base name of the service. Ensure uniformity with CheckHibernate().
            "_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
            );
    mDNSMulticastFilterRegister();
    #endif
	
    #if defined(WF_CONSOLE)
    // Initialize the WiFi Console App
    WFConsoleInit();
    #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.
   #ifndef PERIOD
#define PERIOD  3120        //  set 3120 for get to timer interrupt every 20ms, 40MHz PBUS, div by 256
#endif
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_256, PERIOD);
    while(1)
    {
         if (AppConfig.networkType == WF_SOFT_AP) {
            if (g_scan_done) {
                if (g_prescan_waiting) {
                     SCANCXT.displayIdx = 0;
                     while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                         WFDisplayScanMgr();
                     }
				
                     #if defined(WF_CS_TRIS)
                     WF_Connect();
                     #endif
                     g_scan_done = 0;
                     g_prescan_waiting = 0;
                }
            }
         }

        #if defined (EZ_CONFIG_STORE)
        // Hold SW0 for 4 seconds to reset to defaults.
        if (SW0_IO == 1u) {  // Button is pressed
            button_state = 1;
            if (ButtonPushStart == 0)  //Just pressed
                ButtonPushStart = TickGet();
            else
                if(TickGet() - ButtonPushStart > 4*TICK_SECOND)
                    RestoreWifiConfig();
        } 
        else 
        {
            ButtonPushStart = 0; //Button release reset the clock
        }
		
        if (AppConfig.saveSecurityInfo)
        {
            // set true by WF_ProcessEvent after connecting to a new network
            // get the security info, and if required, push the PSK to EEPROM
            if ((AppConfig.SecurityMode == WF_SECURITY_WPA_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA2_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE))
            {
                // only need to save when doing passphrase
                tWFCPElements profile;
                UINT8 connState;
                UINT8 connID;
                WF_CMGetConnectionState(&connState, &connID);
                WF_CPGetElements(connID, &profile);
                
                memcpy((char*)AppConfig.SecurityKey, (char*)profile.securityKey, 32);
                AppConfig.SecurityMode--; // the calc psk is exactly one below for each passphrase option
                AppConfig.SecurityKeyLength = 32;                

                SaveAppConfig(&AppConfig);
            }
            
            AppConfig.saveSecurityInfo = FALSE;
        }
        #endif // EZ_CONFIG_STORE
		
        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*3ul))))
        {
            t = TickGet();
            LED0_INV();
        }

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

        // This task invokes each of the core stack application tasks
        if (cloud_mode == 0)
          StackApplications();

        // Enable WF_USE_POWER_SAVE_FUNCTIONS 
        WiFiTask();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
        ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
        #endif

        Exosite_Demo();
        // Process application specific tasks here.
        // Any custom modules or processing you need to do should
        // go here.
        #if defined(WF_CONSOLE)
		WFConsoleProcess();
		WFConsoleProcessEpilogue();
		#endif

		// If the local IP address has changed (ex: due to DHCP lease change)
		// write the new IP address to the LCD display, UART, and Announce 
		// service
		if(dwLastIP != AppConfig.MyIPAddr.Val) 
		{
			dwLastIP = AppConfig.MyIPAddr.Val;	
			DisplayIPValue(AppConfig.MyIPAddr);			
		
			#if defined(STACK_USE_ANNOUNCE)
			AnnounceIP();
	 		#endif
		
			#if defined(STACK_USE_ZEROCONF_MDNS_SD)
			mDNSFillHostRecord();
	 		#endif
		}

    }
}
Ejemplo n.º 30
0
int main(void)
{
    int  value;
    int junk;
    millisec = 0;
    value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() );

    // Enable the cache for the best performance
    CheKseg0CacheOn();

    //Setupt input for inteface button JF8 (RA01) (0x02)
    TRISASET = 0x02;
    //RED LED - JF9 (RA04)  (0x10)
    TRISACLR = 0x10;
    ODCACLR = 0x10;
    LATASET = 0x10;
    //Green LED -JF7 (RE9)  (0x200)
    TRISECLR = 0x200;
    ODCECLR = 0x200;
    LATESET = 0x200;
    //Setupt Input for DataFlag Button - JF10 - RA5 0x20
    TRISASET = 0x20;
    //Setup Output for Clutch Hold (Launch) JE1 RD14 0x4000
    //This function is active low, driving the FET on the PDU
    TRISDCLR = 0x4000;
    ODCDCLR = 0x4000;
    LATDSET = 0x4000; //Default state is high (off)

    CAN1Init();//CAN1 ACCL 500kbs
    CAN2Init();//Motec 1mbs
    DelayInit();

    initUART2(); // GPS UART
    prevButton1 = 0;
    prevButton2 = 0;
    millisec = 0;

   // Configure Timer 2 to request a real-time interrupt once per millisecond.
   // The period of Timer 2 is (16 * 5000)/(80 MHz) = 1 ms.
   OpenTimer2(T2_ON | T2_IDLE_CON | T2_SOURCE_INT | T2_PS_1_16 | T2_GATE_OFF, 5000);

   // Configure the CPU to respond to Timer 2's interrupt requests.
   INTEnableSystemMultiVectoredInt();
   INTSetVectorPriority(INT_TIMER_2_VECTOR, INT_PRIORITY_LEVEL_2);
   INTClearFlag(INT_T2);
   INTEnable(INT_T2, INT_ENABLED);

   //UART GPS Interrupts
   INTSetVectorPriority(INT_UART_2_VECTOR ,INT_PRIORITY_LEVEL_1); //Make sure UART interrupt is top priority
   INTClearFlag(INT_U2RX);
   INTEnable(INT_U2RX, INT_ENABLED);


    value = OSCCON;
    while (!(value & 0x00000020))
    {
        value = OSCCON;    // Wait for PLL lock to stabilize
    }

    deviceAttached = FALSE;

    //Initialize the stack
    USBInitialize(0);

    shouldLog = FALSE;
    shouldStop = FALSE;
    //count = 0;
    angularRateInfoRec = FALSE;
    accelerationSensorRec = FALSE;
    HRaccelerationSensorRec = FALSE;

       //init tim er 3 to convert adc at 100hz
    OpenTimer3(T3_ON|T3_PS_1_256|T3_SOURCE_INT, 1562);

    //initialize i2c for the psoc
    initI2CPSoC();
    
    state = wait;
    logNum = 0;

    initI2CEEPROM();
    short addy = 0x0000;
    BYTE num = 0x00;
    logNum = readEEPROM(addy);
    if(logNum >= 0xEF)  //Address stored in EEPROM  if greater than 0xEF reset to zero, limited to a single byte with current code configuration
    {
        writeEEPROM(addy, 0x00);
    }
    char GroupString[550];//Group Names (Line1)
    char UnitString[550];//Units (line2)
    char ParamString[650];//Paramater Names (line3)
    sprintf(GroupString,"Time,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Drivetrain,Drivetrain,Electrical,Drivetrain,Drivetrain,Drivetrain,Drivetrain,Engine,Engine,Engine,Engine,Electrical,Electrical,Electrical,Electrical,Electrical,Electrical,Suspension,Suspension,Suspension,Suspension,Suspension,Drivetrain,Driver\n");
    sprintf(UnitString,"ms,deg/s,deg/s,deg/s,m/s^2,m/s^2,m/s^2,m/s^2,m/s^2,m/s^2,rpm,%,kpa,degF,degF,lambda,psi,degF,na,na,psi,psi,V,mph,mph,mph,mph,s,gal,degF,degBTDC,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,\n");
    sprintf(ParamString, "Millisec,pitch(deg/sec),roll(deg/sec),yaw(deg/sec),lat(m/s^2),long(m/s^2),vert(m/s^2),latHR(m/s^2),longHR(m/s^2),vertHR(m/s^2),rpm,tps(percent),MAP(kpa),AT(degF),ect(degF),lambda,fuel pres,egt(degF),launch,neutral,brake pres,brake pres filtered,BattVolt(V),ld speed(mph), lg speed(mph),rd speed(mph),rg speed(mph),run time(s),fuel used,Oil Temp (deg F), Ignition Adv (degBTDC),Overall Consumption(mV),Overall Production(mV),Fuel Pump(mV),Fuel Injector(mV),Ignition(mV),Vref(mV),Back Left(mV),Back Right(mV),Front Left(mV),Front Right(mV),Steering Angle(mV),Brake Temp(mV),Data Flag,GPRMC,Time,Valid,Lat,N/S,Long,E/W,Speed,Course,Date,Variation,E/W\n");

    LATACLR = 0x10; //Turn on Red LED
   // LATECLR = 0x200;

    UARTSendString(UART2,PMTK_HOT_RESTART);
    int i = 0;
    while(!UARTTransmissionHasCompleted(UART2)){
        i++;
    }

    while(1)
    {
        GPSDataRead();
        GPSSentenceParse();
        ClutchHold(); //This function handles the venting direction of the clutch actuator
        DataFlagFunc(); //This function handles the updates of the data flag variable
        //USB stack process function
        USBTasks();

        switch(state){
            case wait:
                USBTasks();
                millisec = 0;
                if(CheckLogStateChange() == 1){ //start the transition from wait to log
                    state = startLog;
                }
                break;
            case startLog:
                //if thumbdrive is plugged in
                if(USBHostMSDSCSIMediaDetect())
                {
                    deviceAttached = TRUE;
                    //now a device is attached
                    //See if the device is attached and in the right format
                    if(FSInit())
                    {
                        //Opening a file in mode "w" will create the file if it doesn't
                        //  exist.  If the file does exist it will delete the old file
                        //  and create a new one that is blank.
                        logNum = readEEPROM(addy);
                        sprintf(nameString, "test%d.csv", logNum);
                        myFile = FSfopen(nameString,"w");
                        FSfwrite(GroupString,1,strlen(GroupString),myFile);
                        FSfwrite(UnitString,1,strlen(UnitString),myFile);
                        FSfwrite(ParamString,1, strlen(ParamString),myFile);
                        millisec = 0;
                        //LATDSET = 0x4000; //Send sync pulse (aeroprobe)
                       // while(millisec < 1000){} //Wait 1s then move to log, the aeroprobe ADC waits 1s.
                            state = log;
                        LATECLR = 0x200; //Turn on Green
                        LATASET = 0x10; //Turn off Red
                    }
                }
                break;
            case log:
                //This uses MOTEC as the master timer.  Data is only written to the USB after all the motec Data is received
                if(motec0Read && motec1Read && motec2Read && motec3Read && motec4Read && motec5Read){
                    WriteToUSB();
                }
                else{}//Wait for motec data to write the next row
                if(CheckLogStateChange() == 2){ //Start the transition from log to wait
                    state = stopLog;
                }
                if(millisec > 2000){
                    LATDCLR = 0x4000; //After 2 seconds pass no need to keep output high
                }
                //Add a function to check for a flag button and set a variable
                break;
            case stopLog:
                //Always make sure to close the file so that the data gets written to the drive.
                FSfwrite("endFile", 1, 7, myFile);
                FSfclose(myFile);
                state = wait;
                logNum++;
                writeEEPROM(addy, logNum);
                LATACLR = 0x10; //Turn on Red
                LATESET = 0x200; //Turn off Green
                break;
            default:
                state = wait;
                break;
        }


        //CAN Handlers
        CANRxMessageBuffer* CAN1RxMessage = CAN1RxMsgProcess();
        if(CAN1RxMessage){
            WriteAccelData(CAN1RxMessage); //Accel is on CAN 1
        }
        CANRxMessageBuffer* CAN2RxMessage = CAN2RxMsgProcess();
        if(CAN2RxMessage){
            writeCan2Msg(CAN2RxMessage); //Motec is on CAN 2
        }
    }
    return 0;
}