Пример #1
0
/*
 *  ======== Timer_trigger ========
 */
Void Timer_trigger(Timer_Object *obj, UInt32 insts)
{
    UInt64 cpuCounts, timerCounts;
    Types_FreqHz timerfreq, cpufreq;
    UInt32 ratio;
    UInt32 period;
    UInt32 count;
    UInt key;
    
    /* get CPU frequency */
    BIOS_getCpuFreq(&cpufreq);
    cpuCounts = (cpufreq.hi * (1 < 0xffffffff)) + cpufreq.lo;

    /* get Timer frequency */
    Timer_getFreq(obj, &timerfreq);
    timerCounts = (timerfreq.hi * (1 < 0xffffffff)) + timerfreq.lo;

    ratio = cpuCounts/timerCounts;
    period = insts / ratio;
    count = ratio - (insts % ratio);

    if (period == 0) {
        period = 1;
    }

    /* follow proper procedure for dynamic period change */
    key = Hwi_disable();
    Timer_setPeriod(obj, period);
    Timer_start(obj);
    Timer_spinLoop(count);
    Hwi_restore(key);
}
Пример #2
0
void App_run(Application *me)
{
    uint8_t     i = 0;
	
    /* THREAD 0 */
    switch(me->_state)
    {
        case PAUSED:
            break;

        case RUNNING: {
            switch (app_getMsg())
            {
                case TIME_ELAPSED:
                	LED0 = ~LED0;
                	printf((frchar*)"\r\nonTimeElapsed(%d)", me->_cnt);
                    app_handled();
                    break; 	// return a main()
                    
                case TICKS_DONE:
                	LED1 = ~LED1;
                	printf((frchar*)"\r\n---- onTicksDone() ----\r\n");              	
                	Timer_start(&me->_tmr0);  // Relanzar Timer
                    app_handled();
                    break; 	// return a main()
                    
                 default:
                    break; 	// return a main()

            } // end switch 2
        } // end case
    } // end switch 1
} // end function
/*
 *  ======== TimestampProvider_startTimer ========
 */
Void TimestampProvider_startTimer()
{
    if (!TimestampProvider_useClockTimer) {
        Timer_start(MOD->timer);
    }

}
Пример #4
0
int main(int argc, char **argv) {
	int res;
	DenseMatrix a, b, c;
	int a_nr_rows, a_nr_cols;
	int b_nr_rows, b_nr_cols;

	Timer t;

	int nr_threads = atoi(argv[3]);
	int min_dim = atoi(argv[4]);

	res = DenseMatrix_mm_read_strassen(&a, argv[1], &a_nr_rows, &a_nr_cols);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to read DenseMatrix a");

	res = DenseMatrix_mm_read_strassen(&b, argv[2], &b_nr_rows, &b_nr_cols);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to read DenseMatrix b");

	res = DenseMatrix_init(&c, a.nr_rows, b.nr_cols);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to init matrix c");

	#if USE_OPEN_MP
		omp_set_dynamic(0);     		 // Explicitly disable dynamic teams
		omp_set_num_threads(nr_threads); // Use nr_threads threads for all consecutive parallel regions
	#endif

	Timer_start(&t);
	res = DenseMatrix_mt_strassen(&a, a.nr_cols, &b, b.nr_cols, &c, c.nr_cols, nr_threads, min_dim);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to multiply ab = c");
	Timer_end(&t);

	printf("strassen_mthread,%d,%d-by-%d,%d-by-%d,%d,%lf\n", nr_threads, a.nr_rows, a.nr_cols, b.nr_rows, b.nr_cols, min_dim, Timer_dur_sec(&t));

	return 0;
}
Пример #5
0
/*
 *  ======== Timer_reconfig ========
 *
 * 1. Init obj using params
 * 2. Timer_init()
 * 3. Configure timer (wrt emulation, frequency, etc.)
 * 4. Set period
 * 5. Timer_start()
 *
 */
Void Timer_reconfig (Timer_Object *obj, Timer_FuncPtr tickFxn, const 
    Timer_Params *params, Error_Block *eb)
{
    obj->controlRegInit = params->controlRegInit.source;
    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->prevThreshold = params->prevThreshold;
    obj->synchronous = params->synchronous;

    if (obj->periodType == Timer_PeriodType_MICROSECS) {
        if (!Timer_setPeriodMicroSecs(obj, obj->period)) {
            Error_raise(eb, Timer_E_cannotSupport, obj->period, 0);
        }
    }

    obj->arg = params->arg;
    obj->tickFxn = tickFxn;

    if (params->extFreq.lo) {                   /* (extFreq.hi is ignored) */
        obj->frequency.lo = params->extFreq.lo;
    }

    postInit(obj, eb);

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }
}
Пример #6
0
int main(int argc, char **argv) {
	int res;
	SparseMatrix a, b, c;
	Timer t;

	res = SparseMatrix_mm_read(&a, argv[1]);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to read DenseMatrix a");

	res = SparseMatrix_mm_read(&b, argv[2]);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to read DenseMatrix b");

	int size = a.nr_elems > b.nr_elems ? a.nr_elems : b.nr_elems;

	res = SparseMatrix_init(&c, a.nr_rows, b.nr_cols, size);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to init matrix c");

	Timer_start(&t);
	res = SparseMatrix_mult(&a, &b, &c);
	CHECK_ZERO_ERROR_RETURN(res, "Failed to multiply ab = c");
	Timer_end(&t);

	printf("s_single_thread,1,%d-by-%d,%d-by-%d,%lf\n", a.nr_rows, a.nr_cols, b.nr_rows, b.nr_cols, Timer_dur_sec(&t));

	return 0;
}
Пример #7
0
/*
 *  ======== Timer_trigger ========
 */
Void Timer_trigger(Timer_Object *obj, UInt insts)
{
    UInt key;

    /* follow proper procedure for dynamic period change */
    key = Hwi_disable();
    Timer_setPeriod(obj, insts);
    Timer_start(obj);
    Hwi_restore(key);
}
Пример #8
0
/*
 *  ======== IpcPower_postResume ========
 */
Void IpcPower_postResume(Void)
{
    /* Restore timer registers */
    Timer_restoreRegisters(tickTimerHandle, NULL);
    Timer_start(tickTimerHandle);

    /* Call all user registered resume callback functions */
    IpcPower_callUserFxns(IpcPower_Event_RESUME);

    IpcPower_resumeCount++;
}
Пример #9
0
int main(int argc, char * argv[]) {
    FILE * input_file;
    int size;

    // Check for arg and validity of that arg.
    if(argc != 2) {
        printf("Error: Expected the name of a system definition file.\n");
        return EXIT_FAILURE;
    }
    if((input_file = fopen(argv[1], "r")) == NULL) {
        printf("Error: Can not open the system definition file.\n");
        return EXIT_FAILURE;
    }

    // Get the size of the gaussian equation, then create arrays to hold it.
    // WARNING: this should be malloc'd. Creating a[size][size] results in
    // segfaults for large ``size``. (on my machine, 1100+ will do it)
    fscanf(input_file, "%d", &size);
    floating_type * a = malloc(size * size * sizeof(floating_type));
    floating_type * b = malloc(size * sizeof(floating_type));
    // Populate arrays with coefficients.
    for(int row = 0; row < size; ++row) {
        for(int col = 0; col < size; ++col) {
            fscanf(input_file, "%lf", &a[row * size + col]); // Nasty type unsafety!
        }
        fscanf(input_file, "%lf", &b[row]); // Here too!
    }
    fclose(input_file);

    // Solve the equation.
    Timer stopwatch;
    Timer_start(&stopwatch);
    int error;
    gaussian_solve(size, a, b, &error);
    Timer_stop(&stopwatch);

    // Print the solution.
    if(error) {
        printf("System is degenerate\n");
    } else {
        printf("\nSolution is\n");
        for(int i = 0; i < size; ++i) {
            printf(" x(%4d) = %9.5f\n", i, b[i]);
        }
        printf("\nExecution time = %ld milliseconds\n", Timer_time(&stopwatch));
    }

    free(a);
    free(b);

    return EXIT_SUCCESS;
}
Пример #10
0
void Timer_attachInterrupt(void (*f)(void)){
	// 割り込みフラグクリア
	*TIMER_IRQ_CLR = 0;
	// 関数ポインタセット
	timerIRQ_func = f;

	// タイマー開始
	Timer_start();

	// 割り込み有効
	enable_timer_interrupt();
	enable_IRQ();
}
Пример #11
0
/*
 *  ======== Timer_reconfig ========
 *  1. Init obj using params
 *  2. Reconfig Hwi
 *  3. Timer_init()
 *  4. Timer configuration (wrt emulation, external frequency etc)
 *  5. Timer_setPeriod()
 *  6. Timer_start()
 */
Void Timer_reconfig (Timer_Object *obj, Timer_FuncPtr tickFxn,
const Timer_Params *params, Error_Block *eb)
{
    Hwi_Params hwiParams;

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->altclk = params->altclk;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->prevThreshold = params->prevThreshold;
    obj->rollovers = 0;
    obj->savedCurrCount = 0;

    if (obj->altclk) {         /* if using altclk the freq is always 16MHz */
        obj->extFreq.lo = 16000000;
        obj->extFreq.hi = 0;
    }
    else {                     /* else use specified extFreq */
        obj->extFreq.lo = params->extFreq.lo;
        obj->extFreq.hi = params->extFreq.hi;
    }

    if (obj->periodType == Timer_PeriodType_MICROSECS) {
        if (!Timer_setPeriodMicroSecs(obj, obj->period)) {
            Error_raise(eb, Timer_E_cannotSupport, obj->period, 0);
        }
    }

    obj->arg = params->arg;
    obj->tickFxn = tickFxn;

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        hwiParams.arg = (UArg)obj;

        Hwi_reconfig (obj->hwi, Timer_isrStub, &hwiParams);
    }

    Timer_postInit(obj, eb);

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }
}
Пример #12
0
int main( int argc, char *argv[] )
{
    FILE          *input_file;
    size_t         size;

    if( argc != 2 ) {
        printf( "Error: Expected the name of a system definition file.\n" );
        return EXIT_FAILURE;
    }

    if( (input_file = fopen( argv[1], "r" )) == NULL ) {
        printf("Error: Can not open the system definition file.\n");
        return EXIT_FAILURE;
    }

    // Get the size.
    fscanf( input_file, "%d", &size );

    // Allocate the arrays.
    floating_type a[size][size];
    floating_type b[size];

    // Get coefficients.
    for( size_t i = 0; i < size; ++i ) {
        for( size_t j = 0; j < size; ++j ) {
            fscanf( input_file, "%lf", &a[i][j] );  // Nasty type unsafety!
        }
        fscanf( input_file, "%lf", &b[i] );  // Here too!
    }
    fclose( input_file );

    Timer stopwatch;
    Timer_start( &stopwatch );
    int error;
    gaussian_solve( size, a, b, &error );
    Timer_stop( &stopwatch );

    if( error ) {
        printf( "System is degenerate\n" );
    }
    else {
        printf( "\nSolution is\n" );
        for( size_t i = 0; i < size; ++i ) {
            printf( " x(%4d) = %9.5f\n", i, b[i] );
        }

        printf( "\nExecution time = %ld milliseconds\n", Timer_time( &stopwatch ) );
    }

    return EXIT_SUCCESS;
}
Пример #13
0
/*
 *  ======== Timer_reconfig ========
 *  1. Init obj using params
 *  2. Reconfig Hwi
 *  3. Timer_init()
 *  4. Timer configuration (wrt emulation, external frequency etc)
 *  5. Timer_setPeriod()
 *  6. Timer_start()
 */
Void Timer_reconfig(Timer_Object *obj, Timer_FuncPtr tickFxn,
        const Timer_Params *params, Error_Block *eb)
{
    Timer_initObj(obj, tickFxn, params);

    /* since timer requires a stub func, no Hwi reconfig is needed */
   
    /* leave it to caller to check eb */
    Timer_postInit(obj, eb);
    
    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }
}
Пример #14
0
/*
 *  ======== Timer_startup ========
 *  Here after main(). Called from BIOS_start()
 */
Void Timer_startup()
{
    Timer_Object *obj;

    if (Timer_startupNeeded) { 
        obj = Timer_module->handle;
        /* if timer was statically created/constructed */
        if ((obj != NULL) && (obj->staticInst)) {
            if (obj->startMode == Timer_StartMode_AUTO) {
                Timer_start(obj);
            }
        }
    }
}
Пример #15
0
/*
 *  ======== Timer_reconfig ========
 *  1. Init obj using params
 *  2. Reconfig Hwi
 *  3. Timer_init()
 *  4. Timer configuration (wrt emulation, external frequency etc)
 *  5. Timer_setPeriod()
 *  6. Timer_start()
 */
Void Timer_reconfig (Timer_Object *obj, Timer_FuncPtr tickFxn, const Timer_Params *params, 
    Error_Block *eb)
{
    Hwi_Params hwiParams;

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;

    if (obj->periodType == Timer_PeriodType_MICROSECS) {
        if (!Timer_setPeriodMicroSecs(obj, obj->period)) {
            Error_raise(eb, Timer_E_cannotSupport, obj->period, 0);
        }
    }

    obj->arg = params->arg;
    obj->tickFxn = tickFxn;

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        if (obj->id == 0) {
            hwiParams.arg = (UArg)obj;

            if (obj->runMode == Timer_RunMode_CONTINUOUS) {
                Hwi_reconfig (obj->hwi, Timer_periodicStub, &hwiParams);
            }
            else {
                Hwi_reconfig (obj->hwi, Timer_oneShotStub, &hwiParams);
            }
        }
        else {
            hwiParams.arg = obj->arg;
            Hwi_reconfig (obj->hwi, obj->tickFxn, &hwiParams);
        }
    }

    postInit(obj, eb);

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }
}
Пример #16
0
uint8 Button_initialize(uint32 khz, uint32 sampleInterval, uint32 timeoutInterval)
{
    if (Cb_initialize(&buttonBuffer, BUTTON_BUFFER_SIZE, sizeof(ButtonValue), (void*)(&buttonBufferData)) == -1)
        return -1;
    
	if (Timer_initialize(Timer2, khz, sampleInterval) == -1)
        return -1;
    
    maxunset = (uint32)(timeoutInterval/sampleInterval);
    
    Timer_connectFunction(Timer2, valueButton);
    Timer_start(Timer2);

    return 0;
}
Пример #17
0
/*
 *  ======== Timer_trigger ========
 *
 *  1. stop timer
 *  2. write the period with insts
 *  3. start the timer.
 *
 */
Void Timer_trigger(Timer_Object *obj, UInt32 insts)
{
    UInt key;

    /* follow proper procedure for dynamic period change */
    key = Hwi_disable();

    /* Force SMCLK for sweep timer */
    obj->controlRegInit &= ~0x0100;     /* clear ACLK bit */
    obj->controlRegInit |= 0x0200;      /* enable SMCLK */

    Timer_stop(obj);
    
    Timer_setPeriod(obj, insts);
    Timer_start(obj);
    Hwi_restore(key);
}
Пример #18
0
/*
 *  ======== Timer_startup ========
 *  Here after call to main().  Called from BIOS_start().
 */
Void Timer_startup()
{
    Int i;
    Timer_Object *obj;

    if (Timer_startupNeeded) {
        for (i = 0; i < Timer_numTimerDevices; i++) {
            obj = Timer_module->handles[i];
            /* if timer was statically created/constructed */
            if ((obj != NULL) && (obj->staticInst)) {
                if (obj->startMode == Timer_StartMode_AUTO) {
                        Timer_start(obj);
                }
            }
        }
    }
}
Пример #19
0
/*
 *  ======== Timer_reconfig ========
 *  1. Init obj using params
 *  2. Reconfig Hwi
 *  3. Timer_init()
 *  4. Timer configuration (wrt emulation, external frequency etc)
 *  5. Timer_setPeriod()
 *  6. Timer_start()
 */
Void Timer_reconfig (Timer_Object *obj, Timer_FuncPtr tickFxn, const Timer_Params *params, 
    Error_Block *eb)
{
    Hwi_Params hwiParams;
    UInt arBit;

    /* determine controlReg 'ar' value (continuous / oneshot) */
    arBit = (params->runMode == Timer_RunMode_CONTINUOUS) ? 1 : 0;

    obj->controlRegInit = ((arBit << 1) |
                           (params->controlRegInit.ptv  << 2) |
                           (params->controlRegInit.ce   << 5) |
                           (params->controlRegInit.free << 6));

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->arg = params->arg;
    obj->tickFxn = tickFxn;
    if (params->extFreq.lo) {
        obj->extFreq.lo = params->extFreq.lo;
    }

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        hwiParams.arg = obj->arg;
        Hwi_reconfig (obj->hwi, obj->tickFxn, &hwiParams);
    }

    postInit(obj, eb);

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }
}
Пример #20
0
/***************************************
 *                                     * 
 *       C O N S T R U C T O R         *
 *                                     *
 ***************************************/
void App_ctor(Application *me) {
	
    /***************************************
     *                                     *
     *     		B U T T O N S              *
     *                                     *
     ***************************************/
    Timer_ctor(&me->_tmr0, 	// objeto a construir
        (void*)me,			// parent
        100,				// periodo del pulso : 1000ms
        10,					// Cantidad de pulsos: 10
        tmr0_onTimeElapsed,	// Evento en cada flanco descendente de pulso
        tmr0_onTicksDone);	// Evento al completar los 10 pulsos
							
 	Timer_start(&me->_tmr0);
 	
	me->_state = RUNNING;  		// estado inicial
	me->_cnt = 0;				// cantidad de pulsos emitidos dentro cada tren de pulsos
	PORTD = 0x00;				// apagar todos los leds
	app_handled();				// default message: NONEWS

}//
Пример #21
0
/*
 *  ======== Timer_Instance_init ========
 * 1. Select timer based on id
 * 2. Mark timer as in use
 * 3. Save timer handle if necessary (needed by TimestampProvider on 64).
 * 4. Init obj using params
 * 5. Create Hwi if tickFxn !=NULL
 * 6. Timer_init()
 * 7. Timer configuration (wrt emulation, external frequency etc)
 * 8. Timer_setPeriod()
 * 9. Timer_start()
 */
Int Timer_Instance_init(Timer_Object *obj, Int id, Timer_FuncPtr tickFxn, const Timer_Params *params, Error_Block *eb)
{
    UInt key;
    Int i, status;
    Hwi_Params hwiParams;
    UInt tempId = 0xffff;

    if (id >= Timer_NUM_TIMER_DEVICES) {
        if (id != Timer_ANY) {
            Error_raise(eb, Timer_E_invalidTimer, id, 0);
            return (1);
        }
    }

    key = Hwi_disable();

    if (id == Timer_ANY) {
        for (i = 0; i < Timer_NUM_TIMER_DEVICES; i++) {
            if ((Timer_anyMask & (1 << i))
                && (Timer_module->availMask & (1 << i))) {
                Timer_module->availMask &= ~(1 << i);
                tempId = i;
                break;
            }
        }
    }
    else if (Timer_module->availMask & (1 << id)) {
        Timer_module->availMask &= ~(1 << id);
        tempId = id;
    }

    Hwi_restore(key);

    obj->staticInst = FALSE;

    if (tempId == 0xffff) {
        Error_raise(eb, Timer_E_notAvailable, id, 0);
        return (2);
    }
    else {
        obj->id = tempId;
    }

    /* if timer id == 0 */
    if (obj->id == 0) {
        obj->ctmid  = 0;
        obj->intNum = 17;
    }
    else if (obj->id == 1) {
        obj->ctmid  = 1;
        obj->intNum = 18;
    }

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->extFreq.lo = params->extFreq.lo;
    obj->extFreq.hi = params->extFreq.hi;

    if (obj->periodType == Timer_PeriodType_MICROSECS) {
        if (!Timer_setPeriodMicroSecs(obj, obj->period)) {
            Error_raise(eb, Timer_E_cannotSupport, obj->period, 0);
                Hwi_restore(key);
            return (4);
        }
    }

    obj->arg = params->arg;
    obj->tickFxn = tickFxn;

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        /* CTM doesn't need to be acknowledged, no stub required */
        hwiParams.arg = obj->arg;
        obj->hwi = Hwi_create (obj->intNum, obj->tickFxn,
                               &hwiParams, eb);

        if (obj->hwi == NULL) {
            return (3);
        }
    }
    else {
        obj->hwi = NULL;
    }

    Timer_module->handles[obj->id] = obj;

    status = Timer_postInit(obj, eb);

    if (status) {
        return (status);
    }

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }

    return (0);
}
Пример #22
0
/*
 *  ======== TimestampProvider_startTimer ========
 *  This function is only called if we are using a dedicated timer for 
 *  timestamp. It is called so that the Timestamp count starts before main.
 *
 *  This function is called as part of Startup.lastFxns, which is after module
 *  startup so that the Timer has been initialized, but before main in order to
 *  start the Timestamp count as soon as possible.
 */
Void TimestampProvider_startTimer()
{
    Timer_start(MOD->timer);
}
Пример #23
0
void lightSetInputFn() {
	//return pin to input and start the second timer.
	Timer_stop(timer1);
	GPIOPinTypeGPIOInput(GPIO_PORTE_BASE, GPIO_PIN_1);
	Timer_start(timer2);
}
Пример #24
0
void ReadLightW(Semaphore_Handle Sema, unsigned int *results){
		char RMS_str[5];
		char RMS_cnt_str[5];
		//Set pins as output and set light sensor high.
		GPIOPinTypeGPIOOutput(GPIO_PORTE_BASE, GPIO_PIN_1);
		GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_1, GPIO_PIN_1);
		Timer_start(timer1);
		//Turn on timer1 for 12 microseconds.
		//Pend on LightSema
		Semaphore_pend(Sema, BIOS_WAIT_FOREVER);

		switch (adState) {
		case 0: // no line dtected
			if (*results && (black_count >= 20)){ //make sure it is a full line.
				Clock_start(DataClock);
				wasWhite = 0;	//record state.
				adState = 1;	//next state.
			}
			break;
		case 1: //first rising edge detected

			//falling edge of first line
			if (!(*results) && !wasWhite && (black_count >= 20)) {
				wasWhite = 1;
				adState = 2;
				if ((black_count <= 40) && (black_count >= 20)) {	//single line detected
					if (drive_state == FOLLOW1 || prev_follow_state == FOLLOW1){
						//First black line found, progress to follow2
						//		and start acquiring data.
						drive_state = FOLLOW2;
						prev_follow_state = FOLLOW2;
						RMS_cnt = 0;
						RMS = 0;
						Clock_start(DataClock);
					}
					else if (drive_state == FOLLOW2 || prev_follow_state == FOLLOW2){
						//Second black line found, progress to follow3
						//		and stop acquiring data.
						prev_follow_state = FOLLOW3;
						drive_state = FOLLOW3;
						Clock_stop(DataClock);
						//RMS /= RMS_cnt;		//finalize RMS
						//RMS = sqrt(RMS);
						intToStr(RMS_cnt, RMS_cnt_str, 4);
						strcpy(FullBufferPtr, "\0");
						strcpy(FullBufferPtr, "R=\0");	//Clear the fullBuffer.
						intToStr(RMS, RMS_str, 4);
						strcat(FullBufferPtr, RMS_str);
						strcat(FullBufferPtr, "\nC=\0");
						strcat(FullBufferPtr, RMS_cnt_str);
						strcat(FullBufferPtr, "\n\0");
						writeFrame("",FullBufferPtr);
						//Semaphore_post(TxDataSema);		//Let writeFrame continue.
						//Clock_stop(DataClock);
					}
				}else if (black_count > 40){ //double line detected
					StopDrivingFn();
					Clock_stop(DataClock);
				}
				black_count = 0;

			}
			break;
		case 2: //first falling edge detected
			if (*results && wasWhite && (black_count >= 20)){
				wasWhite = 0;
				adState = 3;
			}

			break;
		case 3: //second rising edge detected

			//falling edge of second line
			if (!(*results) && !wasWhite && (black_count >= 20)) {
				wasWhite = 1;
				adState = 4;
				if ((black_count <= 40) && (black_count >= 20)) {	//single line detected
					if (drive_state == FOLLOW1 || prev_follow_state == FOLLOW1){
						//First black line found, progress to follow2
						//		and start acquiring data.
						drive_state = FOLLOW2;
						prev_follow_state = FOLLOW2;
						RMS_cnt = 0;
						RMS = 0;
						Clock_start(DataClock);
					}
					else if (drive_state == FOLLOW2 || prev_follow_state == FOLLOW2){
						//First black line found, progress to follow3
						//		and stop acquiring data.
						prev_follow_state = FOLLOW3;
						drive_state = FOLLOW3;
						//Clock_stop(DataClock);
						Clock_stop(DataClock);
						//RMS /= RMS_cnt;		//finalize RMS
						//RMS = sqrt(RMS);
						intToStr(RMS_cnt, RMS_cnt_str, 4);
						strcpy(FullBufferPtr, "\0");
						strcpy(FullBufferPtr, "R=\0");	//Clear the fullBuffer.
						intToStr(RMS, RMS_str, 4);
						strcat(FullBufferPtr, RMS_str);
						strcat(FullBufferPtr, "\nC=\0");
						strcat(FullBufferPtr, RMS_cnt_str);
						strcat(FullBufferPtr, "\n\0");
						writeFrame("",FullBufferPtr);
						//Semaphore_post(TxDataSema);		//Let writeFrame continue.
					}
				}else if (black_count > 40){//double line detected
					//StopDrivingFn();
					Clock_stop(DataClock);
				}
				black_count = 0;
			}
			break;
		case 4: //second falling edge detected. Done collecting data.
			//Clock_stop(DataClock);
			//StopAcquireData();

			Clock_stop(DataClock);
			//RMS /= RMS_cnt;		//finalize RMS
			//RMS = sqrt(RMS);
			intToStr(RMS_cnt, RMS_cnt_str, 4);
			strcpy(FullBufferPtr, "\0");
			strcpy(FullBufferPtr, "R=\0");	//Clear the fullBuffer.
			intToStr(RMS, RMS_str, 4);
			strcat(FullBufferPtr, RMS_str);
			strcat(FullBufferPtr, "\nC=\0");
			strcat(FullBufferPtr, RMS_cnt_str);
			strcat(FullBufferPtr, "\n\0");
			writeFrame("",FullBufferPtr);
			//Semaphore_post(TxDataSema);		//Let writeFrame continue.
			//push whats remaining in the buffer out to transfer it.
			strcpy(FullBufferPtr, "\0");
			strcat(pingptr1, "\n\0");
			strcpy(FullBufferPtr, pingptr1);
			Semaphore_post(TxDataSema);
			strcpy(pingptr1, "\0");
			numChars = 0;
			wasWhite = 0;
			adState = 0;
			break;
		default:
			break;
		}

}
Пример #25
0
/**
 * Application entry point.
 */
int main( int argc, char **argv )
{
	pthread_t *threads = NULL;
	int numPorts = -1;
	struct ThreadOutData **outData = NULL;
	struct hostent *hostInfo = NULL;
	int counter = 0;
	int currentPort = -1;
	int i = 0;

	AppConfig appConfig;

	programName = argv[0];
	AppConfig_init( &appConfig );
	AppConfig_parseCommandLine( &appConfig, argc, argv );

	threads = (pthread_t *)calloc( appConfig.numThreads, sizeof( pthread_t ) );
	numPorts = appConfig.toPort - appConfig.fromPort;
	outData = malloc( sizeof( struct ThreadOutData ) * numPorts );

	Timer_start();

	hostInfo = resolveHostInfo( appConfig.hostName );

	if( hostInfo == NULL )
	{
		fprintf( stderr, "Unable to resolve host: %s\n", appConfig.hostName );
		return EXIT_FAILURE;
	}

	printf( "Scanning open ports on %s (%s)\n", inet_ntoa( *((struct in_addr *)hostInfo->h_addr_list[0] ) ), appConfig.hostName );

	currentPort = appConfig.fromPort;
	while( currentPort < appConfig.toPort )
	{
		int threadsCreated = 0;
		unsigned int i = 0;
		for( i = 0; i < appConfig.numThreads; i++ )
		{
			if( currentPort <= appConfig.toPort )
			{
				struct ThreadInData *inData = (struct ThreadInData*)malloc( sizeof( struct ThreadInData ) );
				memset( inData, 0, sizeof( struct ThreadInData ) );
				inData->hostInfo = hostInfo;
				inData->port = currentPort;
				pthread_create( &threads[ i ], NULL, threadRun, (void *)inData );
				currentPort++;
				threadsCreated++;
			}
		}

		for( i = 0; i < threadsCreated; i++ )
		{
			pthread_join( threads[ i ], (void **)&outData[ counter ] );
			counter++;
		}
	}

	for( i = 0; i < numPorts; i++ )
	{
		void ( *printFunction )( struct ThreadOutData * ) = printOpenClosed;
		if( FORMAT_PLUSES_MINUSES == appConfig.printFormat )
		{
			printFunction = printPlusesMinuses;
		}
		if( outData[ i ]->isOpen || appConfig.showOnlyOpen == 0 )
		{
			printFunction( outData[ i ] ); 
		}
		free( outData[ i ]->serviceName );
	}

	Timer_stop();

	printf( "Elapsed time: %ld seconds\n", Timer_getElapsedTime() );

	if( threads != NULL )
		free( threads );

	return EXIT_SUCCESS;
}
Пример #26
0
int play(Game *game) {

    /* Variables */
    int mouseClick = 0;
    int mouseX = 0;
    int mouseY = 0;
    SDL_Event event;
    SDL_Rect tempSourceRect;
    SDL_Rect tempDestRect;
    int i = 0;
    int j = 0;
    int collision = NO_COLLISION;
    int blocksLeft = 0;
    char frameUseText[16]; /* Holds "Frame use: 100%" */
    SDL_Surface *frameUseSurface = NULL;
    int lifeSpacing = 0;
    int playing = TRUE;
    int previousScore = 0;
    SDL_Surface *scoreSurface = NULL;
    char scoreText[20]; /* Should be plenty... */

    /* Objects */
    Timer frameTimer;
    Paddle paddle;
    Ball ball;

    /* Set up paddle */
    paddle.image = game->paddleSprites;
    paddle.screen = game->screen;

    /* Set up ball */
    ball.r = 8;
    ball.x = 320;
    ball.y = 240;
    ball.xVelocity = 0;
    ball.yVelocity = 0;
    ball.screen = game->screen;
    ball.image = game->ballSprites;

    sprintf(scoreText, "Score: %i", game->score);
    scoreSurface = TTF_RenderText_Blended(game->scoreFont, scoreText, game->textColour);

    while(playing && game->lives >= 0) {

        Timer_start(&frameTimer);

        /* == Event handling == */
        mouseClick = 0;
        while(SDL_PollEvent(&event)) {

            if(event.type == SDL_QUIT) {
                game->lives = -1;
                return FALSE; /* A better way to quit would be nice..
                                    Maybe the escape key.. */
            }

            if(event.type == SDL_MOUSEMOTION) {
                mouseX = event.motion.x;
                mouseY = event.motion.y;
            }

            if(event.type == SDL_MOUSEBUTTONDOWN) {
                mouseX = event.button.x;
                mouseY = event.button.y;
                mouseClick++;
            }
            if(event.type == SDL_KEYDOWN) {
                switch(event.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        game->lives = -1;
                        return FALSE;
                        break;
                    case SDLK_d:
                        game->debug = !(game->debug);
                        break;
                    case SDLK_s: /* Skip level */
                        if(game->debug) {
                            playing = FALSE;
                        }
                        break;
                    case SDLK_l: /* Extra life */
                        if(game->debug) {
                            game->lives += 1;
                        }
                        break;
                }
            }
        }

        /* == Logic == */
        /* Are we still playing? */
        blocksLeft = 0;
        for(i = 0; i < 30; i++) {
            for(j = 0; j < 10; j++) {
                if(game->level[j][i].type) {
                    blocksLeft++;
                }
            }
        }

        previousScore = game->score;

        if(!blocksLeft) {
            playing = FALSE;
            SDL_Delay(500); /* Give the player a pause to see that they have won the level */
        }

        if((!ball.yVelocity) && mouseClick) { /* Click to start the ball */
            ball.yVelocity = BALL_VELOCITY;
        }

        paddle.x = mouseX;

        if(Ball_checkWallCollisions(&ball) == SIDE_WALL) {
            Mix_PlayChannel(-1, game->beep[10], 0);
            ball.xVelocity = -ball.xVelocity;

        }

        if(Ball_checkWallCollisions(&ball) == TOP_WALL) {
            Mix_PlayChannel(-1, game->beep[10], 0);
            ball.yVelocity = -ball.yVelocity;
        }

        if(Ball_checkWallCollisions(&ball) == BOTTOM_WALL) {
            game->lives -= 1;
            /* Reset ball */
            ball.xVelocity = 0;
            ball.yVelocity = 0;
            ball.x = 320;
            ball.y = 240;
        }

        /* Paddle collision detection */
        if(Ball_checkPaddleCollisions(&ball, paddle.x) != NO_COLLISION) {
            /* Preserve ball velocity, but change angle depending on collision point */
            Mix_PlayChannel(-1, game->beep[10], 0);
            ball.xVelocity = BALL_VELOCITY * sin(Ball_checkPaddleCollisions(&ball, paddle.x) / 30.56);
            ball.yVelocity = -BALL_VELOCITY * cos(Ball_checkPaddleCollisions(&ball, paddle.x) / 30.56);
        }

        /* Check for collisions with the bricks */
        /* Find the closest bricks.. */
        /* This WILL be buggy. If we hit between two bricks, it will behave like hitting a corner. */
        /* Eventually, add code to check for two bricks next to one another.. If two corner collisions
         * are detected at the same time, treat as an edge, etc. */
        collision = NO_COLLISION;
        for(i = ball.y / 16 - 1; i <= ball.y / 16 + 1; i++) {
            if(i >= 0 && i < 30) {
                for(j = ball.x / 64 - 1; j <= ball.x / 64 + 1; j++) {
                    if(j >= 0 && j < 10 && collision == NO_COLLISION && game->level[j][i].type != 0) {
                        collision = Ball_checkBlockCollisions(&ball, j, i);
                        if(collision != NO_COLLISION) {
                            game->level[j][i].type = 0;
                            Mix_PlayChannel(-1, game->beep[game->level[j][i].colour], 0);
                            game->score += 10;
                        }
                    }
                }
            }
        }

        /* would a switch statement be better? */
        if(collision == CORNER) {
            ball.xVelocity = -ball.xVelocity;
            ball.yVelocity = -ball.yVelocity;
        }
        else if(collision == SIDE) {
            ball.xVelocity = -ball.xVelocity;
        }
        else if(collision == WIDTH) {
            ball.yVelocity = -ball.yVelocity;
        }

        Ball_move(&ball);

        /* == Rendering == */
        /* Render the background */
        tempDestRect.x = 0;
        tempDestRect.y = 0;
        SDL_BlitSurface(game->background, NULL, game->screen, &tempDestRect);
        tempDestRect.x = 320;
        SDL_BlitSurface(game->background, NULL, game->screen, &tempDestRect);
        tempDestRect.y = 240;
        SDL_BlitSurface(game->background, NULL, game->screen, &tempDestRect);
        tempDestRect.x = 0;
        SDL_BlitSurface(game->background, NULL, game->screen, &tempDestRect);

        /* Render the tiles */
        for(i = 0; i < 30; i++) {
            for(j = 0; j < 10; j++) {
                if(game->level[j][i].type) { /* Only type 0 is not rendered */
                    tempSourceRect.x = game->level[j][i].colour * 64;
                    tempSourceRect.w = 64;
                    tempSourceRect.y = game->level[j][i].type * 16;
                    tempSourceRect.h = 16;
                    tempDestRect.x = j * 64;
                    tempDestRect.y = i * 16;
                    SDL_BlitSurface(game->blockSprites, &tempSourceRect, game->screen, &tempDestRect);
                }
            }
        }

        /* Render the ball */
        Ball_render(&ball);

        /* Render the paddle */
        Paddle_render(&paddle);

        /* render the lives */
        tempDestRect.y = 456;
        if(game->lives > 5) {
            lifeSpacing = 8;
        }
        else {
            lifeSpacing = 20;
        }

        for(i = 0; i < game->lives; i++) {
            tempDestRect.x = 8 + i * lifeSpacing;
            SDL_BlitSurface(game->ballSprites, NULL, game->screen, &tempDestRect);
        }

        /* Score */
        if(previousScore != game->score) {
            sprintf(scoreText, "Score: %i", game->score);
            if(scoreSurface != NULL) {
                SDL_FreeSurface(scoreSurface);
            }
            scoreSurface = TTF_RenderText_Blended(game->scoreFont, scoreText, game->textColour);
        }
        SDL_BlitSurface(scoreSurface, NULL, game->screen, NULL);

        /* Frame use, before flipping screen */
        if(game->debug) {
            sprintf(frameUseText, "Frame use: %.0f%%", (100.0 * Timer_timePassed(&frameTimer)) / (1000.0 / FRAMELIMIT));
            frameUseSurface = TTF_RenderText_Solid(game->scoreFont, frameUseText, game->textColour);
            tempDestRect.x = 0;
            tempDestRect.y = 25;
            SDL_BlitSurface(frameUseSurface, NULL, game->screen, &tempDestRect);
            SDL_FreeSurface(frameUseSurface);
        }

        /* Flip screen */
        if(SDL_Flip(game->screen)) {
            fprintf(stderr, "Error flipping screen.\n");
            exit(EXIT_FAILURE);
        }

        /* Frame limiting */
        if(Timer_timePassed(&frameTimer) < (1000 / FRAMELIMIT)) {
            SDL_Delay(1000 / FRAMELIMIT - Timer_timePassed(&frameTimer));
        }
    }
    SDL_FreeSurface(scoreSurface);
    return game->lives;
}
Пример #27
0
/*
 *  ======== Timer_Instance_init ========
 * 1. Select timer based on id
 * 2. Mark timer as in use
 * 3. Save timer handle if necessary (needed by TimestampProvider on 64).
 * 4. Init obj using params
 * 5. Create Hwi if tickFxn !=NULL
 * 6. Timer_init()
 * 7. Timer configuration (wrt emulation, external frequency etc)
 * 8. Timer_setPeriod()
 * 9. Timer_start()
 */
Int Timer_Instance_init(Timer_Object *obj, Int id, Timer_FuncPtr tickFxn, const Timer_Params *params, Error_Block *eb)
{
    UInt key;
    Int i, status;
    Hwi_Params hwiParams;
    UInt tempId = 0xffff;

    if (id >= Timer_NUM_TIMER_DEVICES) {
        if (id != Timer_ANY) {
            Error_raise(eb, Timer_E_invalidTimer, id, 0);
            return (1);
        }
    }

    key = Hwi_disable();

    if (id == Timer_ANY) {
        for (i = 0; i < Timer_NUM_TIMER_DEVICES; i++) {
            if ((Timer_anyMask & (1 << i))
                && (Timer_module->availMask & (1 << i))) {
                Timer_module->availMask &= ~(1 << i);
                tempId = i;
                break;
            }
        }
    }
    else if (Timer_module->availMask & (1 << id)) {
        Timer_module->availMask &= ~(1 << id);
        tempId = id;
    }

    Hwi_restore(key);

    obj->staticInst = FALSE;

    if (tempId == 0xffff) {
        Error_raise(eb, Timer_E_notAvailable, id, 0);
        return (2);
    }
    else {
        obj->id = tempId;
    }

    /* if timer id == 0, use systick */
    if (obj->id == 0) {
        obj->ctmid = 0;
        obj->intNum = 15;
    }
    /* if timer id == 1, must select which CTM timer based on core id */
    else {
        if (Core_getId() == 0) {
            obj->ctmid = 0;
            obj->intNum = 18;
        }
        else {
            obj->ctmid = 1;
            obj->intNum = 22;
        }
    }

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->extFreq.lo = params->extFreq.lo;
    obj->extFreq.hi = params->extFreq.hi;

    if (obj->periodType == Timer_PeriodType_MICROSECS) {
        if (!Timer_setPeriodMicroSecs(obj, obj->period)) {
            Error_raise(eb, Timer_E_cannotSupport, obj->period, 0);
            Hwi_restore(key);
            return (4);
        }
    }
  
    obj->arg = params->arg;
    obj->tickFxn = tickFxn;

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        /* we'll enable the interrupt when we're ready */
        hwiParams.enableInt = FALSE;

        /* SysTick needs to be acknowledged, use stub functions */
        if (obj->id == 0) {
            hwiParams.arg = (UArg)obj;
        
            if (obj->runMode == Timer_RunMode_CONTINUOUS) {
                obj->hwi = Hwi_create (obj->intNum, Timer_periodicStub, 
                    &hwiParams, eb);
            }
            else {
                obj->hwi = Hwi_create (obj->intNum, Timer_oneShotStub, 
                    &hwiParams, eb);
            }
        }
        /* CTM doesn't need to be acknowledged, no stub required */        
        else {
            hwiParams.arg = obj->arg;
            obj->hwi = Hwi_create (obj->intNum, obj->tickFxn,
                    &hwiParams, eb);
        }

        if (obj->hwi == NULL) {
            return (3);
        }
    }
    else {
        obj->hwi = NULL;
    }

    Timer_module->handles[obj->id] = obj;

    status = postInit(obj, eb);

    if (status) {
        return (status);
    }

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }

    return (0);
}
Пример #28
0
/*
 *  ======== Timer_Instance_init ========
 * 1. Select timer based on id
 * 2. Mark timer as in use
 * 3. Save timer handle if necessary (needed by TimestampProvider on 64).
 * 4. Init obj using params
 * 5. Create Hwi if tickFxn !=NULL
 * 6. Timer_init()
 * 7. Timer configuration (wrt emulation, external frequency etc)
 * 8. Timer_setPeriod()
 * 9. Timer_start()
 */
Int Timer_Instance_init(Timer_Object *obj, Int id, Timer_FuncPtr tickFxn, const Timer_Params *params, Error_Block *eb)
{
    UInt key;
    Int i, status;
    Hwi_Params hwiParams;
    UInt arBit;
    UInt tempId = 0xffff;

    if (id >= Timer_NUM_TIMER_DEVICES) {
        if (id != Timer_ANY) {
            Error_raise(eb, Timer_E_invalidTimer, id, 0);
            return (1);
        }
    }

    key = Hwi_disable();

    if (id == Timer_ANY) {
        for (i = 0; i < Timer_NUM_TIMER_DEVICES; i++) {
            if ((Timer_anyMask & (1 << i))
                && (Timer_module->availMask & (1 << i))) {
                Timer_module->availMask &= ~(1 << i);
                tempId = i;
                break;
            }
        }
    }
    else if (Timer_module->availMask & (1 << id)) {
        Timer_module->availMask &= ~(1 << id);
        tempId = id;
    }

    Hwi_restore(key);

    obj->staticInst = FALSE;
    if (tempId == 0xffff) {
        Error_raise(eb, Timer_E_notAvailable, id, 0);
        return (2);
    }
    else {
        obj->id = tempId;
    }

    Timer_module->handles[obj->id] = obj;


    /* determine controlReg 'ar' value (continuous / oneshot) */
    arBit = (params->runMode == Timer_RunMode_CONTINUOUS) ? 1 : 0;


    obj->controlRegInit = ((arBit << 1) |
                           (params->controlRegInit.ptv  << 2) |
                           (params->controlRegInit.ce   << 5) |
                           (params->controlRegInit.free << 6));

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->arg = params->arg;
    obj->intNum = intNumDef[obj->id];
    obj->tickFxn = tickFxn;

    /* extFreq.hi is ignored */
    if (params->extFreq.lo) {
        obj->extFreq.lo = params->extFreq.lo;
    }

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        hwiParams.arg = obj->arg;
        obj->hwi = Hwi_create (obj->intNum, obj->tickFxn, &hwiParams, eb);

        if (obj->hwi == NULL) {
            return (3);
        }
    }
    else {
        obj->hwi = NULL;
    }

    status = postInit(obj, eb);

    if (status) {
        return (status);
    }

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }

    return (0);
}
Пример #29
0
/*
 *  ======== Timer_Instance_init ========
 * 1. Select timer based on id
 * 2. Mark timer as in use
 * 3. Save timer handle if necessary (needed by TimestampProvider on 64).
 * 4. Init obj using params
 * 5. Create Hwi if tickFxn !=NULL
 * 6. Timer_init()
 * 7. Timer configuration (wrt emulation, external frequency etc)
 * 8. Timer_setPeriod()
 * 9. Timer_start()
 */
Int Timer_Instance_init(Timer_Object *obj, Int id, Timer_FuncPtr tickFxn, const Timer_Params *params, Error_Block *eb)
{
    UInt key;
    Int status;
    Hwi_Params hwiParams;
    UInt tempId = 0xffff;

    if ((id != 0) && (id != Timer_ANY)) {
        Error_raise(eb, Timer_E_invalidTimer, id, 0);
        return (1);
    }

    key = Hwi_disable();

    if (id == Timer_ANY) {
        if ((Timer_anyMask & 1) && (Timer_module->availMask & 1)) {
            Timer_module->availMask &= ~(1);
            tempId = 0;
        }
    }
    else if (Timer_module->availMask & 1) {
        Timer_module->availMask &= ~(1);
        tempId = id;
    }

    Hwi_restore(key);

    obj->staticInst = FALSE;

    if (tempId == 0xffff) {
        Error_raise(eb, Timer_E_notAvailable, id, 0);
        return (NO_TIMER_AVAIL);
    }
    else {
        obj->id = tempId;
    }

    Timer_module->handle = obj;

    obj->runMode = params->runMode;
    obj->startMode = params->startMode;
    obj->period = params->period;
    obj->periodType = params->periodType;
    obj->extFreq.lo = params->extFreq.lo;
    obj->extFreq.hi = params->extFreq.hi;

    if (obj->periodType == Timer_PeriodType_MICROSECS) {
        if (!Timer_setPeriodMicroSecs(obj, obj->period)) {
            Error_raise(eb, Timer_E_cannotSupport, obj->period, 0);
            Hwi_restore(key);
            return (BAD_PERIOD);
        }
    }
  
    obj->arg = params->arg;
    obj->intNum = 15;
    obj->tickFxn = tickFxn;

    if (obj->tickFxn) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, (params->hwiParams));
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        hwiParams.arg = (UArg)obj;

        if (obj->runMode == Timer_RunMode_CONTINUOUS) {
            obj->hwi = Hwi_create (obj->intNum, Timer_periodicStub, 
                &hwiParams, eb);
        }
        else {
            obj->hwi = Hwi_create (obj->intNum, Timer_oneShotStub, 
                &hwiParams, eb);
        }

        if (obj->hwi == NULL) {
            return (NO_HWI_OBJ);
        }
    }
    else {
        obj->hwi = NULL;
    }

    status = postInit(obj, eb);

    if (status) {
        return (status);
    }

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }

    return (0);
}
Пример #30
0
/*
 *  ======== Timer_Instance_init ========
 * 1. Select timer based on id
 * 2. Mark timer as in use
 * 3. Save timer handle if necessary (needed by TimestampProvider on 64).
 * 4. Init obj using params
 * 5. Create Hwi if tickFxn !=NULL
 * 6. Timer_init()
 * 7. Timer configuration (wrt emulation, external frequency etc)
 * 8. Timer_setPeriod()
 * 9. Timer_start()
 */
Int Timer_Instance_init(Timer_Object *obj, Int id, Timer_FuncPtr tickFxn, const Timer_Params *params, Error_Block *eb)
{
    UInt key;
    Int i, status;
    Hwi_Params hwiParams;
    UInt tempId = 0xffff;

    /* make sure id is not greater than number of 32-bit timer devices */
    if (id >= Timer_numTimerDevices ) {
        if (id != Timer_ANY) {
            Error_raise(eb, Timer_E_invalidTimer, id, 0);
            return (1);
        }
    }

    key = Hwi_disable();
    if (id == Timer_ANY) {
        for (i = 0; i < Timer_numTimerDevices; i++) {
            if ((Timer_anyMask & (1 << i)) &&
                (Timer_module->availMask & (1 << i))) {
                Timer_module->availMask &= ~(1 << i);
                tempId = i;
                break;
            }
        }
    }
    else if (Timer_module->availMask & (1 << id)) {
        Timer_module->availMask &= ~(1 << id);
        tempId = id;
    }

    Hwi_restore(key);

    obj->staticInst = FALSE;

    if (tempId == 0xffff) {
        Error_raise(eb, Timer_E_notAvailable, id, 0);
        return (2);
    }
    else {
        obj->id = tempId;
    }
    
    Timer_module->handles[obj->id] = obj;

    /* initialize the timer state object */
    Timer_initObj(obj, tickFxn, params);

    /* create the Hwi object if function is specified */
    if (obj->tickFxn != NULL) {
        if (params->hwiParams) {
            Hwi_Params_copy(&hwiParams, params->hwiParams);
        }
        else {
            Hwi_Params_init(&hwiParams);
        }

        hwiParams.eventId = Timer_module->device[obj->id].eventId;

        hwiParams.arg = (UArg)obj;
        obj->hwi = Hwi_create(obj->intNum, Timer_stub, &hwiParams, eb);

        if (obj->hwi == NULL) {
            return (4);
        }
    }
    else {
        obj->hwi = NULL;
    }

    status = Timer_postInit(obj, eb);

    if (status) {
        return (status);
    }

    if (obj->startMode == Timer_StartMode_AUTO) {
        Timer_start(obj);
    }

    return (0);
}