void wlan_mac_schedule_event(u8 scheduler_sel, u32 delay, void(*callback)()){
	u32 k;

	u64 timestamp = get_usec_timestamp();

	for (k = 0; k<SCHEDULER_NUM_EVENTS; k++){
		if(scheduler_in_use[scheduler_sel][k] == 0){ //Found an empty schedule element
			scheduler_in_use[scheduler_sel][k] = 1; //We are using this schedule element
			scheduler_callbacks[scheduler_sel][k] = (function_ptr_t)callback;
			scheduler_timestamps[scheduler_sel][k] = timestamp+(u64)delay;

			if(scheduler_sel == SCHEDULE_FINE){
				if(timer_running[TIMER_CNTR_FAST] == 0){
					timer_running[TIMER_CNTR_FAST] = 1;
					XTmrCtr_SetResetValue(&TimerCounterInst, TIMER_CNTR_FAST, FAST_TIMER_DUR_US*(TIMER_FREQ/1000000));
					XTmrCtr_Start(&TimerCounterInst, TIMER_CNTR_FAST);
				}

			} else if(scheduler_sel == SCHEDULE_COARSE) {
				if(timer_running[TIMER_CNTR_SLOW] == 0){
					timer_running[TIMER_CNTR_SLOW] = 1;
					XTmrCtr_SetResetValue(&TimerCounterInst, TIMER_CNTR_SLOW, SLOW_TIMER_DUR_US*(TIMER_FREQ/1000000));
					XTmrCtr_Start(&TimerCounterInst, TIMER_CNTR_SLOW);
				}
			}
			return;
		}
	}
	warp_printf(PL_ERROR,"ERROR: %d schedules already filled\n",SCHEDULER_NUM_EVENTS);
}
Exemple #2
0
int TmrCtrIntr(XIntc * IntcInstancePtr, XTmrCtr * TmrCtrInstancePtr, u16 DeviceID, u16 IntrID, u8 TmrCtrNumber){
	int Status;

	/*连接一个设备句柄,当识别中断后,与中断源相关的句柄将运行。IntcInstancePtr为中断控制器,
	  IntrID为定时器的中断号,XTmrCtr_InterruptHandler为中断的句柄,TmrCtrInstancePtr为回调参数。*/

	Status = XIntc_Connect(IntcInstancePtr, IntrID, (XInterruptHandler)XTmrCtr_InterruptHandler, (void *)TmrCtrInstancePtr);
	if(Status != XST_SUCCESS)
		return XST_FAILURE;
	//启动中断控制器
	Status = XIntc_Start(IntcInstancePtr, XIN_REAL_MODE);
	if(Status != XST_SUCCESS)
			return XST_FAILURE;
	//使能中断
	XIntc_Enable(IntcInstancePtr, IntrID);
	//允许处理器处理中断
	microblaze_enable_interrupts();
	if(Status != XST_SUCCESS)
			return XST_FAILURE;
	//设定用于定时器的句柄
	XTmrCtr_SetHandler(TmrCtrInstancePtr, timer_int_handler, TmrCtrInstancePtr);
	//设置定时器选项
	XTmrCtr_SetOptions(TmrCtrInstancePtr, TmrCtrNumber, XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);
	//设置定时器计数的周期数加到1s(在50MHZ条件下)
	//中断为 = 0xFFFFFFFF - 0x2FAF080(=50000000) => 0xFD050F80
	XTmrCtr_SetResetValue(TmrCtrInstancePtr, TmrCtrNumber, 0xFD050F80);
	//启动定时器
	XTmrCtr_Start(TmrCtrInstancePtr, TmrCtrNumber);
	xil_printf("The value of count = %d\n\r", count);
	return XST_SUCCESS;
}
Exemple #3
0
Fichier : main.c Projet : aaasz/SHP
int main() {
    int one_out1, one_out2, one_out3;
    int two_out, three_out, four_out;
    int five_out1, five_out2;
    int six_out, seven_out;
    int eight_out;
    xil_printf("Microblaze:\n");
    XTmrCtr_Initialize(&TimerInst, 0);
    XTmrCtr_SetResetValue(&TimerInst, 0, 0);
    XTmrCtr_Start(&TimerInst, 0);
    StartIF_TS = XTmrCtr_GetValue(&TimerInst, 0);
    function_one(10000000, &one_out1, &one_out2, &one_out3);
    function_two(one_out1, &two_out);
    function_three(one_out2, &three_out);
    function_four(one_out3, &four_out);
    function_five(two_out, three_out, four_out, &five_out1, &five_out2);
    function_six(five_out1, &six_out);
    function_seven(five_out2, &seven_out);
    function_eight(six_out, seven_out, &eight_out);
    xil_printf("Rezultat = %d \n", eight_out);
    FinishIF_TS = XTmrCtr_GetValue(&TimerInst, 0);
    TimeSA = (FinishIF_TS - StartIF_TS) / (50000000 / 1000);
    xil_printf("0\n");
    xil_printf("%d\n", TimeSA);
    xil_printf("SERIALSTOP");
    return 0;
}
Exemple #4
0
int wl_timer_initialize(){
	int status = 0;
	XTmrCtr *TmrCtrInstancePtr = &TimerCounter;

	XTmrCtr_Config *TmrCtrConfigPtr;
	//Initialize the timer counter
	status = XTmrCtr_Initialize(TmrCtrInstancePtr, TMRCTR_DEVICE_ID);
	if (status == XST_DEVICE_IS_STARTED) {
		xil_printf("Timer was already running; clear/init manually\n");
		TmrCtrConfigPtr = XTmrCtr_LookupConfig(TMRCTR_DEVICE_ID);
		TmrCtrInstancePtr->BaseAddress = TmrCtrConfigPtr->BaseAddress;
		TmrCtrInstancePtr->IsReady = XIL_COMPONENT_IS_READY;
		XTmrCtr_Stop(TmrCtrInstancePtr, 0);
		XTmrCtr_Reset(TmrCtrInstancePtr, 0);
		status = XTmrCtr_Initialize(TmrCtrInstancePtr, TMRCTR_DEVICE_ID);
	}
	if (status != XST_SUCCESS) {
		xil_printf("w3_node_init: Error in XtmrCtr_Initialize (%d)\n", status);
	}

	// Set timer 0 to into a "count down" mode
	XTmrCtr_SetOptions(TmrCtrInstancePtr, 0, (XTC_DOWN_COUNT_OPTION));

	///Timer Setup///
	XTmrCtr_SetResetValue(TmrCtrInstancePtr,1,0); //Sets it so issuing a "start" command begins at counter=0
	/////////////////


	return status;
}
void timer_handler(void *CallBackRef, u8 TmrCtrNumber){
	u16 k;
	u8 restart_timer;
	u64 timestamp;

	restart_timer = 0;
	timestamp = get_usec_timestamp();

	switch(TmrCtrNumber){
		case TIMER_CNTR_FAST:
			for(k = 0; k<SCHEDULER_NUM_EVENTS; k++){
				if(scheduler_in_use[SCHEDULE_FINE][k] == 1){
					restart_timer = 1;
					if(timestamp > scheduler_timestamps[SCHEDULE_FINE][k]){
						scheduler_in_use[SCHEDULE_FINE][k] = 0; //Free up schedule element before calling callback in case that function wants to reschedule
						scheduler_callbacks[SCHEDULE_FINE][k]();
					}
				}
			}
			if(restart_timer){
				timer_running[TIMER_CNTR_FAST] = 1;
				XTmrCtr_SetResetValue(&TimerCounterInst, TIMER_CNTR_FAST, FAST_TIMER_DUR_US*(TIMER_FREQ/1000000));
				XTmrCtr_Start(&TimerCounterInst, TIMER_CNTR_FAST);
			} else {
				timer_running[TIMER_CNTR_FAST] = 0;
			}
		break;
		case TIMER_CNTR_SLOW:
			for(k = 0; k<SCHEDULER_NUM_EVENTS; k++){
				if(scheduler_in_use[SCHEDULE_COARSE][k] == 1){
					restart_timer = 1;
					if(timestamp > scheduler_timestamps[SCHEDULE_COARSE][k]){
						scheduler_in_use[SCHEDULE_COARSE][k] = 0; //Free up schedule element before calling callback in case that function wants to reschedule
						scheduler_callbacks[SCHEDULE_COARSE][k]();
					}
				}
			}
			if(restart_timer){
				timer_running[TIMER_CNTR_SLOW] = 1;
				XTmrCtr_SetResetValue(&TimerCounterInst, TIMER_CNTR_SLOW, SLOW_TIMER_DUR_US*(TIMER_FREQ/1000000));
				XTmrCtr_Start(&TimerCounterInst, TIMER_CNTR_SLOW);
			} else {
				timer_running[TIMER_CNTR_SLOW] = 0;
			}
		break;
	}
}
Exemple #6
0
void vbx_timestamp_init(XTmrCtr *inst_ptr, u32 freq)
{
	vbx_timestamp_tmrctr = inst_ptr;
	vbx_timestamp_tmrctr_freq = freq;

	// XTmrCtr_SetOptions(vbx_timestamp_tmrctr, 0,
	//                    XTC_CASCADE_MODE_OPTION);
	XTmrCtr_SetResetValue(vbx_timestamp_tmrctr, 0, 0);
}
		/* This is a default implementation of what is otherwise an application defined
		callback function used to install the tick interrupt handler.  It is provided as
		an application callback because the kernel will run on lots of different
		MicroBlaze and FPGA configurations - not all of which will have the same timer
		peripherals defined or available.  vApplicationSetupTimerInterrupt() is declared
		as a weak symbol, allowing the application writer to provide their own
		implementation, if this default implementation is not suitable. */
		void vApplicationSetupTimerInterrupt( void )
		{
		portBASE_TYPE xStatus;
		const unsigned char ucTickTimerCounterNumber = ( unsigned char ) 0U;
		const unsigned char ucRunTimeStatsCounterNumber = ( unsigned char ) 1U;
		const unsigned long ulCounterValue = ( ( XPAR_TMRCTR_0_CLOCK_FREQ_HZ / configTICK_RATE_HZ ) - 1UL );
		extern void vPortTickISR( void *pvUnused );

			/* Initialise the timer/counter. */
			xStatus = XTmrCtr_Initialize( &xTickTimerInstance, XPAR_TMRCTR_0_DEVICE_ID );

			if( xStatus == XST_SUCCESS )
			{
				/* Install the tick interrupt handler as the timer ISR.
				*NOTE* The xPortInstallInterruptHandler() API function must be used for
				this purpose. */
				xStatus = xPortInstallInterruptHandler( XPAR_INTC_0_TMRCTR_0_VEC_ID, vPortTickISR, NULL );
			}

			if( xStatus == pdPASS )
			{
				/* Enable the timer interrupt in the interrupt controller.
				*NOTE* The vPortEnableInterrupt() API function must be used for this
				purpose. */
				vPortEnableInterrupt( XPAR_INTC_0_TMRCTR_0_VEC_ID );

				/* Configure the timer interrupt handler.  This installs the handler
				directly, rather than through the Xilinx driver.  This is done for
				efficiency. */
				XTmrCtr_SetHandler( &xTickTimerInstance, ( void * ) vPortTickISR, NULL );

				/* Set the correct period for the timer. */
				XTmrCtr_SetResetValue( &xTickTimerInstance, ucTickTimerCounterNumber, ulCounterValue );

				/* Enable the interrupts.  Auto-reload mode is used to generate a
				periodic tick.  Note that interrupts are disabled when this function is
				called, so interrupts will not start to be processed until the first
				task has started to run. */
				XTmrCtr_SetOptions( &xTickTimerInstance, ucTickTimerCounterNumber, ( XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION | XTC_DOWN_COUNT_OPTION ) );

				/* Start the timer. */
				XTmrCtr_Start( &xTickTimerInstance, ucTickTimerCounterNumber );




				/* The second timer is used as the time base for the run time stats.
				Auto-reload mode is used to ensure the timer does not stop. */
				XTmrCtr_SetOptions( &xTickTimerInstance, ucRunTimeStatsCounterNumber, XTC_AUTO_RELOAD_OPTION );

				/* Start the timer. */
				XTmrCtr_Start( &xTickTimerInstance, ucRunTimeStatsCounterNumber );
			}

			/* Sanity check that the function executed as expected. */
			configASSERT( ( xStatus == pdPASS ) );
		}
Exemple #8
0
void usleep(unsigned int duration){
	XTmrCtr *TmrCtrInstancePtr = &TimerCounter;
	XTmrCtr_SetResetValue(TmrCtrInstancePtr,0,duration*(TIMER_FREQ/1000000));
	XTmrCtr_Start(TmrCtrInstancePtr,0);
	volatile u8 isExpired = 0;
	while(isExpired!=1){
		isExpired = XTmrCtr_IsExpired(TmrCtrInstancePtr,0);
	}
	XTmrCtr_Reset(TmrCtrInstancePtr,0);
	return;
}
Exemple #9
0
/* This is an application defined callback function used to install the tick
interrupt handler.  It is provided as an application callback because the kernel
will run on lots of different MicroBlaze and FPGA configurations - not all of
which will have the same timer peripherals defined or available.  This example
uses the AXI Timer 0.  If that is available on your hardware platform then this
example callback implementation should not require modification.   The name of
the interrupt handler that should be installed is vPortTickISR(), which the
function below declares as an extern. */
void vApplicationSetupTimerInterrupt( void )
{
portBASE_TYPE xStatus;
const unsigned char ucTimerCounterNumber = ( unsigned char ) 0U;
const unsigned long ulCounterValue = ( ( TIMER_CLOCK_FREQ / configTICK_RATE_HZ ) - 1UL );
extern void vPortTickISR( void *pvUnused );

	/* Initialise the timer/counter. */
	xStatus = XTmrCtr_Initialize( &xTimer0Instance, TIMER_DEVICE_ID );

	if (xStatus == XST_DEVICE_IS_STARTED)
	{
		xTimer0Instance.IsReady = XIL_COMPONENT_IS_READY;
		XTmrCtr_Stop( &xTimer0Instance, TIMER_DEVICE_ID );
		XTmrCtr_Reset( &xTimer0Instance, TIMER_DEVICE_ID );
		xStatus = XTmrCtr_Initialize( &xTimer0Instance, TIMER_DEVICE_ID );
		xStatus = XST_SUCCESS;
	}

	if( xStatus == XST_SUCCESS )
	{
		/* Install the tick interrupt handler as the timer ISR.
		*NOTE* The xPortInstallInterruptHandler() API function must be used for
		this purpose. */
		xStatus = xPortInstallInterruptHandler(TIMER_INTR_ID, vPortTickISR, NULL );
	}

	if( xStatus == pdPASS )
	{
		/* Enable the timer interrupt in the interrupt controller.
		*NOTE* The vPortEnableInterrupt() API function must be used for this
		purpose. */
		vPortEnableInterrupt(TIMER_INTR_ID);

		/* Configure the timer interrupt handler. */
		XTmrCtr_SetHandler( &xTimer0Instance, ( void * ) vPortTickISR, NULL );

		/* Set the correct period for the timer. */
		XTmrCtr_SetResetValue( &xTimer0Instance, ucTimerCounterNumber, ulCounterValue );

		/* Enable the interrupts.  Auto-reload mode is used to generate a
		periodic tick.  Note that interrupts are disabled when this function is
		called, so interrupts will not start to be processed until the first
		task has started to run. */
		XTmrCtr_SetOptions( &xTimer0Instance, ucTimerCounterNumber, ( XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION | XTC_DOWN_COUNT_OPTION ) );

		/* Start the timer. */
		XTmrCtr_Start( &xTimer0Instance, ucTimerCounterNumber );
	}

	/* Sanity check that the function executed as expected. */
	configASSERT( ( xStatus == pdPASS ) );
}
Exemple #10
0
int init_timer(int deviceID, XTmrCtr *timer, u32 timer_freq, u32 target_freq, XTmrCtr_Handler interruptHandler) {
	// Init timer
	if(XTmrCtr_Initialize(timer, deviceID) != XST_SUCCESS) return XST_FAILURE;

	// Self test
	if(XTmrCtr_SelfTest(timer, 0) != XST_SUCCESS) return XST_FAILURE;

	// Setup handler to be called when timer expires
	XTmrCtr_SetHandler(timer, interruptHandler, (void*) timer);

	// Enable interrupts and auto-reset so timer runs forever
	XTmrCtr_SetOptions(timer, 0, XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);

	// Set reset value to cause timer to roll-over before it reaches zero at the specified frequency
	XTmrCtr_SetResetValue(timer, 0, ((unsigned int) 0xFFFFFFFF) - (timer_freq / target_freq));

	// Yey!
	return XST_SUCCESS;
}
//----------------------------------------------------
// MAIN FUNCTION
//----------------------------------------------------
int main (void)
{

  printf("Animation Test\n\r");
  int status;
  char c;
  //----------------------------------------------------
  // INITIALIZE THE PERIPHERALS & SET DIRECTIONS OF GPIO
  //----------------------------------------------------
  // Initialize Push Buttons
  status = XGpio_Initialize(&BTNInst, BTNS_DEVICE_ID);
  if(status != XST_SUCCESS) return XST_FAILURE;

  // Set all buttons direction to inputs
  XGpio_SetDataDirection(&BTNInst, 1, 0xFF);

  //----------------------------------------------------
  // SETUP THE TIMER
  //----------------------------------------------------
  status = XTmrCtr_Initialize(&TMRInst, TMR_DEVICE_ID);
  if(status != XST_SUCCESS) return XST_FAILURE;
  XTmrCtr_SetHandler(&TMRInst, TMR_Intr_Handler, &TMRInst);
  XTmrCtr_SetOptions(&TMRInst, 0, XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);
  XTmrCtr_SetResetValue(&TMRInst, 0, TMR_LOAD);
  XTmrCtr_Start(&TMRInst,0);


  // Initialize interrupt controller
  status = IntcInitFunction(INTC_DEVICE_ID, &TMRInst, &BTNInst,&DmaInstance);
  if(status != XST_SUCCESS) return XST_FAILURE;

  //Lab7 addition starts  here
  //Initialize DMA controller
 // XDma_Config(DMA_DEVICE_ID);
  //Lab7 addition ends  here
  while(1){
// Infinite loop - Do nothing
       }

  // Never reached on normal execution
  return (0);
  }
Exemple #12
0
void Timer_Init(XTmrCtr *TmrCtrInstancePtr, u8 TmrCtrNumber, u16 DeviceId)
{

	/*
	 * Initialize the timer counter so that it's ready to use,
	 * specify the device ID that is generated in xparameters.h
	 */
	XTmrCtr_Initialize(TmrCtrInstancePtr, DeviceId);

	/*
	 * Setup the handler for the timer counter that will be called from the
	 * interrupt context when the timer expires, specify a pointer to the
	 * timer counter driver instance as the callback reference so the handler
	 * is able to access the instance data
	 */
	XTmrCtr_SetHandler(TmrCtrInstancePtr, TimerCounterHandler, TmrCtrInstancePtr);

	/*
	 * Enable the interrupt of the timer counter so interrupts will occur
	 * and use auto reload mode such that the timer counter will reload
	 * itself automatically and continue repeatedly, without this option
	 * it would expire once only
	 */
	XTmrCtr_SetOptions(TmrCtrInstancePtr, TmrCtrNumber,	XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);

	/*
	 * Set a reset value for the timer counter such that it will expire
	 * eariler than letting it roll over from 0, the reset value is loaded
	 * into the timer counter when it is started
	 */
	XTmrCtr_SetResetValue(TmrCtrInstancePtr, TmrCtrNumber, RESET_VALUE);

	/*
	 * Start the timer counter such that it's incrementing by default,
	 * then wait for it to timeout a number of times
	 */
	XTmrCtr_Start(TmrCtrInstancePtr, TmrCtrNumber);

}
/**
*
* This function sets up a custom timer which the driver will use for MicroBlaze
* systems.
*
* @param	None.
*
* @return
*		- XST_SUCCESS if a timer controller exists for use.
*		- XST_FAILURE otherwise.
*
* @note		A timer controller must be present in the system.
*
******************************************************************************/
u32 DpRxSs_SetupTimerHandler(void)
{
	u32 Status;

	Status = XTmrCtr_Initialize(&TmrCtrInst, XTMR_CTRL_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/* Set a custom timer handler for improved delay accuracy on MicroBlaze
	 * systems since the driver does not assume/have a dependency on the
	 * system having a timer in the FPGA.
	 * Note: This only has an affect for MicroBlaze systems since the Zynq
	 * ARM SoC contains a timer, which is used when the driver calls the
	 * delay function. */
	XDpRxSs_SetUserTimerHandler(&DpRxSsInst, &DpRxSs_CustomWaitUs,
					&TmrCtrInst);

	XTmrCtr_SetResetValue(DpRxSsInst.DpPtr->UserTimerPtr, 0, 0);
	XTmrCtr_Reset(DpRxSsInst.DpPtr->UserTimerPtr, 0);

	return XST_SUCCESS;
}
Exemple #14
0
int main (void) {
	int old_count = 0;
	
	gpio_init();
	XGpio_DiscreteWrite(&led,1,0);
	XGpio_DiscreteWrite(&ledPush,1,0x1);
	xil_printf("-- Entering main() --\r\n");
	XTmrCtr_Initialize(&XTC, XPAR_OPB_TIMER_1_DEVICE_ID );
	XTmrCtr_SetOptions(&XTC, 0, XTC_DOWN_COUNT_OPTION | XTC_INT_MODE_OPTION |
    XTC_AUTO_RELOAD_OPTION );
	XTmrCtr_SetHandler(&XTC, TimerCounterHandler, &XTC);
  microblaze_register_handler( (XInterruptHandler)XTmrCtr_InterruptHandler,
    &XTC );
 	microblaze_enable_interrupts();
	XTmrCtr_SetResetValue ( &XTC, 0, 50*1000000L );
	XTmrCtr_Start( &XTC, 0 );
	XGpio_DiscreteWrite(&ledPush,1,0x3);
	while(1) {
	  if (gpio_check()) break;
	  if ( old_count != intr_count ) {
		  xil_printf("  TmrCtr update %d\r\n", intr_count );
		  XGpio_DiscreteWrite(&led,1,3);
		  XGpio_DiscreteWrite(&ledPush,1,0x10 | (intr_count&0xF));
		  old_count = intr_count;
		}
	}
  if ( XTmrCtr_IsExpired( &XTC, 0 ) ) {
		xil_printf("  TmrCtr Timed out\r\n" );
  } else {
	 xil_printf("  TmrCtr un-Timeout\r\n" );
  }
	XTmrCtr_Stop(&XTC, 0 );
	microblaze_disable_interrupts();
    XGpio_DiscreteWrite(&ledPush,1,0x10);
    xil_printf("-- Exiting main() --\r\n");
    return 0;
}
Exemple #15
0
/**
 * This function sets up a custom timer which the driver will use for MicroBlaze
 * systems.
 *
 * @param	InstancePtr is a pointer to the XDp instance.
 * @param	TimerCounterPtr is a pointer to the timer instance.
 * @param	TimerId is the ID of the timer controller to use for delays.
 *
 * @return
 *		- XST_SUCCESS if a timer controller exists for use.
 *		- XST_FAILURE otherwise.
 *
 * @note	A timer controller must be present in the system.
 *
*******************************************************************************/
static u32 Dprx_SetupTimerHandler(XDp *InstancePtr, XTmrCtr *TimerCounterPtr,
                                  u16 TimerId)
{
    u32 Status;

    Status = XTmrCtr_Initialize(TimerCounterPtr, TimerId);
    if (Status != XST_SUCCESS) {
        return XST_FAILURE;
    }

    /* Set a custom timer handler for improved delay accuracy on MicroBlaze
     * systems since the driver does not assume/have a dependency on the
     * system having a timer in the FPGA.
     * Note: This only has an affect for MicroBlaze systems since the Zynq
     * ARM SoC contains a timer, which is used when the driver calls the
     * delay function. */
    XDp_SetUserTimerHandler(InstancePtr, &Dprx_CustomWaitUs,
                            TimerCounterPtr);

    XTmrCtr_SetResetValue(InstancePtr->UserTimerPtr, 0, 0);
    XTmrCtr_Reset(InstancePtr->UserTimerPtr, 0);

    return XST_SUCCESS;
}
Exemple #16
0
int main(void) {
    u32 cmd;
    u32 count;
    u32 GenerateValue, CaptureDuration;
    u8 NumberOfTimes;
    u32 count1, count2;
    u32 status;
    u8 iop_pins[8];
    u32 timer_pin;

    // Initialize Pmod
    pmod_init(0,1);
    /*
     * Configuring Pmod IO switch
     * Timer is connected to bit[0] of the Channel 1 of AXI GPIO instance
     * This configuration is changed later
     */
    config_pmod_switch(TIMER, GPIO_1, GPIO_2, GPIO_3,
                       GPIO_4, GPIO_5, GPIO_6, GPIO_7);
    // by default tristate timer output
    Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,1);

    while(1){
        while(MAILBOX_CMD_ADDR==0); // wait for CMD to be issued
        cmd = MAILBOX_CMD_ADDR;
        
        switch(cmd){
            case CONFIG_IOP_SWITCH:
                // read new pin configuration
                timer_pin = MAILBOX_DATA(0);
                iop_pins[0] = GPIO_0;
                iop_pins[1] = GPIO_1;
                iop_pins[2] = GPIO_2;
                iop_pins[3] = GPIO_3;
                iop_pins[4] = GPIO_4;
                iop_pins[5] = GPIO_5;
                iop_pins[6] = GPIO_6;
                iop_pins[7] = GPIO_7;
                // set new pin configuration
                iop_pins[timer_pin] = TIMER;
                config_pmod_switch(iop_pins[0], iop_pins[1], iop_pins[2], 
                                   iop_pins[3], iop_pins[4], iop_pins[5], 
                                   iop_pins[6], iop_pins[7]);
                Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,1);
                MAILBOX_CMD_ADDR = 0x0;
                break;
                
            case STOP_TIMER:
                XTmrCtr_Stop(&TimerInst_0, 0);
                XTmrCtr_Stop(&TimerInst_0, 1);
                MAILBOX_CMD_ADDR = 0x0;
                break;

            case GENERATE_FOREVER:
                // tri-state control negated so output can be driven
                Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,0);
                // get period value in multiple of 10 ns clock period
                GenerateValue=MAILBOX_DATA(0);
                XTmrCtr_SetResetValue(&TimerInst_0, 0, GenerateValue);
                XTmrCtr_SetOptions(&TimerInst_0, 0,
                        XTC_AUTO_RELOAD_OPTION | XTC_CSR_LOAD_MASK |
                        XTC_CSR_EXT_GENERATE_MASK | XTC_CSR_DOWN_COUNT_MASK);
                XTmrCtr_Start(&TimerInst_0, 0);
                MAILBOX_CMD_ADDR = 0x0;
                break;

            case GENERATE_N_TIMES:
                // tri-state control negated so output can be driven
                Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,0);
                // bits 7:0 number of times, rest is period
                GenerateValue=MAILBOX_DATA(0)>>8;
                NumberOfTimes=MAILBOX_DATA(0) & 0xff;
                XTmrCtr_SetResetValue(&TimerInst_0, 0, GenerateValue);
                XTmrCtr_SetOptions(&TimerInst_0, 0,
                        XTC_AUTO_RELOAD_OPTION | XTC_CSR_LOAD_MASK |
                        XTC_CSR_EXT_GENERATE_MASK | XTC_CSR_DOWN_COUNT_MASK);
                XTmrCtr_Start(&TimerInst_0, 0);
                while(NumberOfTimes){
                    // wait for NumberOfTimes to count down to 0
                    status=XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0);
                    if(status & 0x100){
                        // wait for the asserted edge, reset the flag
                        XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0, status);
                        NumberOfTimes--;
                    }
                }
                XTmrCtr_Stop(&TimerInst_0, 0);
                MAILBOX_CMD_ADDR = 0x0;
                break;

            case EVENT_OCCURED:
                // tri-state control asserted to enable input to capture
                Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,1);
                // get period value in multiple of 10 ns clock period
                CaptureDuration=MAILBOX_DATA(0);
                /*
                 * Use timer module 0 for event counts
                 * Use timer module 1 for the duration
                 * Load timer 1's Load register
                 */
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1,
                                    TLR0, CaptureDuration);
                /*
                 * 0001 0010 0010 =>  no cascade, no all timers,
                 *                    no pwm, clear interrupt status,
                 *                    disable timer, no interrupt,
                 *                    load timer, hold capture value,
                 *                    disable external capture,
                 *                    disable external generate,
                 *                    down counter, generate mode
                 */
                // clear int flag and load counter
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1, TCSR0, 0x122);
                // enable timer 1 in compare mode, no load counter
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1, TCSR0, 0x082);
                /*
                 * 0001 1000 1001 =>  no cascade, no all timers,
                 *                    no pwm, clear interrupt status,
                 *                    enable timer, no interrupt,
                 *                    no load timer, hold capture value,
                 *                    enable external capture,
                 *                    disable external generate,
                 *                    up counter, capture mode
                 */
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0, 0x189);
                while(1) {
                    if((XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 1,
                                        TCSR0) & 0x100)){
                        // if duration over then get out, disable counter 1
                        XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1,
                                            TCSR0, 0x100);
                        MAILBOX_DATA(0)=0;
                        break;
                    }
                    if((XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0) & 0x100)){
                        // wait for the asserted edge, disable counter 0
                        XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                            TCSR0, 0x100);
                        MAILBOX_DATA(0)=1;
                        break;
                    }
                }
                MAILBOX_CMD_ADDR = 0x0;
                break;

            case COUNT_EVENTS:
                // tri-state control asserted to enable input to capture
                Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,1);
                // get period value in multiple of 10 ns clock period
                CaptureDuration=MAILBOX_DATA(0);
                count=0;
                /*
                 * Use timer module 0 for event counts
                 * Use timer module 1 for the duration
                 * Load timer 1's Load register
                 */
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1,
                                    TLR0, CaptureDuration);
                /*
                 * 0001 0010 0010 =>  no cascade, no all timers, no pwm,
                 *                    clear interrupt status, disable timer,
                 *                    no interrupt, load timer,
                 *                    hold capture value,
                 *                    disable external capture,
                 *                    disable external generate,
                 *                    down counter, generate mode
                 */
                // clear int flag and load counter
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1, TCSR0, 0x122);
                // enable timer 1 in compare mode, no load counter
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1, TCSR0, 0x082);
                /* 0001 1000 1001 =>  no cascade, no all timers, no pwm,
                 *                    clear interrupt status, enable timer,
                 *                    no interrupt, no load timer,
                 *                    hold capture value,
                 *                    enable external capture,
                 *                    disable external generate, up counter,
                 *                    capture mode
                 */
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0, 0x189);
                while(1) {
                    if((XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 1,
                                        TCSR0) & 0x100)){
                        // if duration over then get out, disable counter 1
                        XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 1,
                                        TCSR0, 0x100);
                        break;
                    }
                    if((XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0) & 0x100)){
                        // wait for the asserted edge
                        XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0, 0x189);
                        count++;
                    }
                }
                MAILBOX_DATA(0)=count;
                MAILBOX_CMD_ADDR = 0x0;
                break;

            case MEASURE_PERIOD:
                // tri-state control asserted to enable input to capture
                Xil_Out32(XPAR_GPIO_0_BASEADDR+0x08,1);
                /*
                 * Use timer module 0 for event capture
                 * Use module 1 for the maximum duration
                 */
                count1=0;
                count2=0;
                /*
                 * 0001 1000 1001 =>  no cascade, no all timers, no pwm,
                 *                    clear interrupt status, enable timer,
                 *                    no interrupt, no load timer,
                 *                    hold capture value,
                 *                    enable external capture,
                 *                    disable external generate,
                 *                    up counter, capture mode
                 */
                // clear capture flag and enable capture mode
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0, 0x189);
                // skip high or 1st asserted edge
                while(!(XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0) & 0x100));
                // dummy read
                XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0, TLR0);
                // clear capture flag and enable capture mode
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0, 0x189);
                // wait for 1st asserted edge
                while(!(XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0) & 0x100));
                // read counter value
                count1=XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0, TLR0);
                // reset interrupt flag
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0, 0x189);
                // wait for 2nd asserted edge
                while(!(XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0,
                                        TCSR0) & 0x100));
                // read counter value
                count2=XTmrCtr_ReadReg(XPAR_TMRCTR_0_BASEADDR, 0, TLR0);
                // clear capture flag and disable
                XTmrCtr_WriteReg(XPAR_TMRCTR_0_BASEADDR, 0, TCSR0, 0x100);
                MAILBOX_DATA(0)=count2-count1;
                MAILBOX_CMD_ADDR = 0x0;
                break;
                
             default:
                MAILBOX_CMD_ADDR = 0x0;
                break;
            }
    }
    return 0;
}
void vApplicationSetupHardware( void )
{
	XScuGic * InterruptController = prvGetInterruptControllerInstance();
	int iPinNumberEMIO = 54;
	u32 uPinDirectionEMIO = 0x0;
	u32 uPinDirection = 0x1;
	print("##### Application Starts #####\n\r");
	print("\r\n");
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-1 :AXI GPIO Initialization
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	u32 xStatus = XGpio_Initialize(&GPIOInstance_Ptr,XPAR_AXI_GPIO_0_DEVICE_ID);
	if(XST_SUCCESS != xStatus)
		print("GPIO INIT FAILED\n\r");
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-2 :AXI GPIO Set the Direction
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	XGpio_SetDataDirection(&GPIOInstance_Ptr, 1,1);
	//set up GPIO interrupt
	XGpio_InterruptEnable(&GPIOInstance_Ptr, 0x1);
	XGpio_InterruptGlobalEnable(&GPIOInstance_Ptr);

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-3 :AXI Timer Initialization
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	xStatus = XTmrCtr_Initialize(&TimerInstancePtr, XPAR_AXI_TIMER_0_DEVICE_ID);
	if(XST_SUCCESS != xStatus)
		print("TIMER INIT FAILED \n\r");
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-4 :Set Timer Handler
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	XTmrCtr_SetHandler(&TimerInstancePtr, Timer_InterruptHandler, &TimerInstancePtr);
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-5 :Setting timer Reset Value
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	XTmrCtr_SetResetValue(&TimerInstancePtr, 0, 0x0F000000);
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-6 :Setting timer Option (Interrupt Mode And Auto Reload )
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	XTmrCtr_SetOptions(&TimerInstancePtr, XPAR_AXI_TIMER_0_DEVICE_ID, (XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION | XTC_DOWN_COUNT_OPTION));
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-7 :PS GPIO Intialization
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	GpioConfigPtr = XGpioPs_LookupConfig(XPAR_PS7_GPIO_0_DEVICE_ID);
	if(GpioConfigPtr == NULL)
		print(" PS GPIO config lookup FAILED \n\r");
	xStatus = XGpioPs_CfgInitialize(&psGpioInstancePtr, GpioConfigPtr, GpioConfigPtr->BaseAddr);
	if(XST_SUCCESS != xStatus)
		print(" PS GPIO INIT FAILED \n\r");
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-8 :PS GPIO pin setting to Output
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	XGpioPs_SetDirectionPin(&psGpioInstancePtr, 54, uPinDirection);
	XGpioPs_SetOutputEnablePin(&psGpioInstancePtr, 54,1);
//	XGpioPs_SetDirectionPin(&psGpioInstancePtr, 8,uPinDirection);
//	XGpioPs_SetOutputEnablePin(&psGpioInstancePtr, 8, 1);
	print(" INITED MIO \n\r");
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-9 :EMIO PIN Setting to Input port
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	XGpioPs_SetDirectionPin(&psGpioInstancePtr,	iPinNumberEMIO, uPinDirectionEMIO);
	XGpioPs_SetOutputEnablePin(&psGpioInstancePtr, iPinNumberEMIO, 0);
	//XGpioPs_IntrEnable(&psGpioInstancePtr, XGPIOPS_BANK2, 0x1);
	// instance, bank, edge, rising, single edge
	XGpioPs_IntrEnablePin(&psGpioInstancePtr, iPinNumberEMIO);
	XGpioPs_SetIntrType(&psGpioInstancePtr, XGPIOPS_BANK2, 1, 1, 0);
	XGpioPs_SetCallbackHandler(&psGpioInstancePtr, (void *) &psGpioInstancePtr, EMIO_Button_InterruptHandler);

	print(" INITED FIRST EMIO \n\r");
	// EMIO output
	XGpioPs_SetDirectionPin(&psGpioInstancePtr, 55, uPinDirection);
	XGpioPs_SetOutputEnablePin(&psGpioInstancePtr, 55, 1);

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Step-10 : SCUGIC interrupt controller Initialization
	//Registration of the Timer ISR
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	u32 Status = XScuGic_Connect(InterruptController,
							 XPAR_FABRIC_AXI_TIMER_0_INTERRUPT_INTR,
							 (Xil_ExceptionHandler)XTmrCtr_InterruptHandler,
							 (void *)&TimerInstancePtr);

	if (Status != XST_SUCCESS) {
		print(" Error connection timer interrupt \n \r");
	}

	Status = XScuGic_Connect(InterruptController,
							XPAR_FABRIC_AXI_GPIO_0_IP2INTC_IRPT_INTR,
							 (Xil_ExceptionHandler)Button_InterruptHandler,
							 (void *)&GPIOInstance_Ptr);
	if (Status != XST_SUCCESS) {
		print(" Error connection button interrupt \n \r");
	}

	/*
	 * Connect the device driver handler that will be called when an
	 * interrupt for the device occurs, the handler defined above performs
	 * the specific interrupt processing for the device.
	 */
	Status = XScuGic_Connect(InterruptController,
							XPS_GPIO_INT_ID,
							(Xil_ExceptionHandler)XGpioPs_IntrHandler,
							(void *)&psGpioInstancePtr);
	if (Status != XST_SUCCESS) {
		print(" Error connection button EMIO interrupt \n \r");
	}

	/*
	* Enable the interrupt for the device and then cause (simulate) an
	* interrupt so the handlers will be called
	*/
	XScuGic_Enable(InterruptController, XPAR_FABRIC_AXI_GPIO_0_IP2INTC_IRPT_INTR);
	XScuGic_Enable(InterruptController, XPS_GPIO_INT_ID);
	XScuGic_Enable(InterruptController, XPAR_FABRIC_AXI_TIMER_0_INTERRUPT_INTR);

	// turn off all LEDs
	XGpioPs_WritePin(&psGpioInstancePtr, iPinNumber, 0);
	XGpioPs_WritePin(&psGpioInstancePtr, 55, 0);

	print(" End of init \n\r");
}
/**
* This function does a minimal test on the timer counter device and driver as a
* design example.  The purpose of this function is to illustrate how to use the
* XTmrCtr component.  It initializes a timer counter and then sets it up in
* compare mode with auto reload such that a periodic interrupt is generated.
*
* This function uses interrupt driven mode of the timer counter.
*
* @param	IntcInstancePtr is a pointer to the Interrupt Controller
*		driver Instance
* @param	TmrCtrInstancePtr is a pointer to the XTmrCtr driver Instance
* @param	DeviceId is the XPAR_<TmrCtr_instance>_DEVICE_ID value from
*		xparameters.h
* @param	IntrId is XPAR_<INTC_instance>_<TmrCtr_instance>_VEC_ID
*		value from xparameters.h
* @param	TmrCtrNumber is the number of the timer to which this
*		handler is associated with.
*
* @return
*		- XST_SUCCESS if the Test is successful
*		- XST_FAILURE if the Test is not successful
*
* @note		This function contains an infinite loop such that if interrupts
*		are not working it may never return.
*
*****************************************************************************/
int TmrCtrFastIntrExample(XIntc* IntcInstancePtr,
			XTmrCtr* TmrCtrInstancePtr,
			u16 DeviceId,
			u16 IntrId,
			u8 TmrCtrNumber)
{
	int Status;
	int LastTimerExpired = 0;

	/*
	 * Initialize the timer counter so that it's ready to use,
	 * specify the device ID that is generated in xparameters.h
	 */
	Status = XTmrCtr_Initialize(TmrCtrInstancePtr, DeviceId);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Perform a self-test to ensure that the hardware was built
	 * correctly, use the 1st timer in the device (0)
	 */
	Status = XTmrCtr_SelfTest(TmrCtrInstancePtr, TmrCtrNumber);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Connect the timer counter to the interrupt subsystem such that
	 * interrupts can occur.  This function is application specific.
	 */
	Status = TmrCtrSetupIntrSystem(IntcInstancePtr,
					TmrCtrInstancePtr,
					DeviceId,
					IntrId,
					TmrCtrNumber);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * Setup the handler for the timer counter that will be called from the
	 * interrupt context when the timer expires, specify a pointer to the
	 * timer counter driver instance as the callback reference so the
	 * handler is able to access the instance data
	 */
	XTmrCtr_SetHandler(TmrCtrInstancePtr, TimerCounterHandler,
					   TmrCtrInstancePtr);

	/*
	 * Enable the interrupt of the timer counter so interrupts will occur
	 * and use auto reload mode such that the timer counter will reload
	 * itself automatically and continue repeatedly, without this option
	 * it would expire once only
	 */
	XTmrCtr_SetOptions(TmrCtrInstancePtr, TmrCtrNumber,
				XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);

	/*
	 * Set a reset value for the timer counter such that it will expire
	 * eariler than letting it roll over from 0, the reset value is loaded
	 * into the timer counter when it is started
	 */
	XTmrCtr_SetResetValue(TmrCtrInstancePtr, TmrCtrNumber, RESET_VALUE);

	/*
	 * Start the timer counter such that it's incrementing by default,
	 * then wait for it to timeout a number of times
	 */
	XTmrCtr_Start(TmrCtrInstancePtr, TmrCtrNumber);

	while (1) {
		/*
		 * Wait for the first timer counter to expire as indicated by
		 * the shared variable which the handler will increment
		 */
		while (TimerExpired == LastTimerExpired) {
		}
		LastTimerExpired = TimerExpired;

		/*
		 * If it has expired a number of times, then stop the timer
		 * counter and stop this example
		 */
		if (TimerExpired == 3) {

			XTmrCtr_Stop(TmrCtrInstancePtr, TmrCtrNumber);
			break;
		}
	}

	TmrCtrDisableIntr(IntcInstancePtr, DeviceId);
	return XST_SUCCESS;
}
Exemple #19
0
/****************************************************************************
 *
 * FUNCTION:
 *
 * main
 *
 * DESCRIPTION:
 *
 * This is the entry point for the example.  The embedded system automatically
 * calls main.
 *
 * ARGUMENTS:
 *
 * None.
 *
 * RETURN VALUE:
 *
 * None.
 *
 * NOTES:
 *
 * None.
 *
 ****************************************************************************/
int main() {
	XStatus Status;
	int PreviousCount = 0;

	/* Using printf with the UART Lite assumes that the layer 0 device
	 * driver was selected for the UART Lite in the XPS and the standard
	 * I/O peripheral in XPS was set to the UART Lite
	 */printf("\n\rStarting the Application\n\r");

	/*************************** GPIO Setup *******************************/

	/* The second GPIO example uses the higher level (layer 1) driver to
	 * blink the LEDs, First initialize the GPIO component
	 */
	Status = XGpio_Initialize(&Gpio, XPAR_AXI_GPIO_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		printf("GPIO initialization error\n\r\r");
	}
	/* Set the direction for all signals to be inputs except the LED
	 * outputs
	 */
	XGpio_SetDataDirection(&Gpio, 1, ~LED);

	/************************* Timer Setup ********************************/

	/* Initialize the timer counter so that it's ready to use,
	 * specify the device ID that is generated in xparameters.h
	 */
	Status = XTmrCtr_Initialize(&TimerCounter, XPAR_AXI_TIMER_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		printf("Timer counter initialization error\n\r\r");
	}

	/* Perform a self-test to ensure that the hardware was built
	 * correctly, use the 1st timer in the device (0)
	 */
	Status = XTmrCtr_SelfTest(&TimerCounter, TIMER_COUNTER_0);
	if (Status != XST_SUCCESS) {
		printf("Timer counter self-test error\n\r");
	}

	/* Setup the handler for the timer counter that will be called from the
	 * interrupt context when the timer expires, specify a pointer to the
	 * timer counter driver instance as the callback reference so the handler
	 * is able to access the instance data
	 */
	XTmrCtr_SetHandler(&TimerCounter, TimerCounterHandler, &TimerCounter);

	/* Enable the interrupt of the timer counter so interrupts will occur
	 * and use auto reload mode such that the timer counter will reload
	 * itself automatically and continue repeatedly, without this option
	 * it would expire once only
	 */
	XTmrCtr_SetOptions(&TimerCounter, TIMER_COUNTER_0,
			XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);

	/* Set a reset value for the timer counter such that it will expire
	 * earlier than letting it roll over from 0, the reset value is loaded
	 * into the timer counter when it is started
	 */
	XTmrCtr_SetResetValue(&TimerCounter, TIMER_COUNTER_0, resetTime /*RESET_VALUE*/);

	/* Start the timer counter such that it's incrementing
	 */
	XTmrCtr_Start(&TimerCounter, TIMER_COUNTER_0);

	/********************** Interrupt Controller Setup *********************/
	/*
	 * Initialize the interrupt controller driver so that it's ready to use,
	 * using the device ID that is generated in xparameters.h
	 */
	Status = XIntc_Initialize(&InterruptController, XPAR_AXI_INTC_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		printf("Interrupt controller initialization error\n\r");
	}

	/*
	 * Connect the device driver handler that will be called when an interrupt
	 * for the device occurs, the device driver handler performs the specific
	 * interrupt processing for the device
	 */
	Status = XIntc_Connect(&InterruptController,
			XPAR_AXI_INTC_0_AXI_TIMER_0_INTERRUPT_INTR, // we don't know what this is, but it's probably 0
			(XInterruptHandler) XTmrCtr_InterruptHandler, &TimerCounter);
	if (Status != XST_SUCCESS) {
		printf("Interrupt controller connect error\n\r");
	}

	/*
	 * Start the interrupt controller so interrupts are enabled for all
	 * devices that cause interrupts. Specify real mode so that the timer
	 * counter can cause interrupts through the interrupt controller.
	 */
	Status = XIntc_Start(&InterruptController, XIN_REAL_MODE);
	if (Status != XST_SUCCESS) {
		printf("Interrupt controller start error\n\r");
	}

	/* Enable the interrupt for the timer counter and enable interrupts in
	 * the microblaze processor
	 */
	XIntc_Enable(&InterruptController,
			XPAR_AXI_INTC_0_AXI_TIMER_0_INTERRUPT_INTR);

	microblaze_enable_interrupts();

	/********************** Application Processing *********************/

	/* Insert foreground processing here, interrupts will handle
	 * processing in the background
	 */
	while (1) {
		char get = (char)*(volatile int *)(XPAR_RS232_UART_1_BASEADDR);
		if (get >= ' ' && get <= '~')
			break;
	}
	// stop the timer
	microblaze_disable_interrupts();
	// break out of the while look

	/* The application should not ever execute the following code, but it is
	 * present to indicate if the application does exit because of an error
	 */printf("Exiting the Application\n\r");
}
Exemple #20
0
int main(void)
{
	XIntc intc;
	XTmrCtr tmrctr;
	int Status;

	Xil_ICacheEnable();
	Xil_DCacheEnable();

	// Initialize the timer counter so that it's ready to use,
	// specify the device ID that is generated in xparameters.h
	Status = XTmrCtr_Initialize(&tmrctr, XPAR_TMRCTR_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		return Status;
	}

	// Initialize the interrupt controller driver so that 
	// it's ready to use, specify the device ID that is generated in
	// xparameters.h
	Status = XIntc_Initialize(&intc, XPAR_INTC_0_DEVICE_ID);
	if (Status != XST_SUCCESS) {
		return Status;
	}

	// Connect a device driver handler that will be called when an interrupt
	// for the device occurs, the device driver handler performs the specific
	// interrupt processing for the device
	Status = XIntc_Connect(&intc, XPAR_INTC_0_TMRCTR_0_VEC_ID, 
			XTmrCtr_InterruptHandler, &tmrctr);
	if (Status != XST_SUCCESS) {
		return Status;
	}

	// Enable the interrupt for the timer counter
	XIntc_Enable(&intc, XPAR_INTC_0_TMRCTR_0_VEC_ID );

	// Start the interrupt controller such that interrupts are enabled for
	// all devices that cause interrupts, specific real mode so that
	// the timer counter can cause interrupts thru the interrupt controller.
	Status = XIntc_Start(&intc, XIN_REAL_MODE);
	if (Status != XST_SUCCESS) {
		return Status;
	}

	// Initialize the exception table.
	Xil_ExceptionInit();

	// Register the interrupt controller handler with the exception table.
	Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT,
    	(Xil_ExceptionHandler)XIntc_InterruptHandler, &intc);

	// Enable non-critical exceptions.
	Xil_ExceptionEnable();

	// Setup the handler for the timer counter that will be called from the
	// interrupt context when the timer expires, specify a pointer to the
	// timer counter driver instance as the callback reference so the handler
	// is able to access the instance data
	XTmrCtr_SetHandler(&tmrctr, TimerCounterHandler, &tmrctr);

	// Enable the interrupt of the timer counter so interrupts will occur
	// and use auto reload mode such that the timer counter will reload
	// itself automatically and continue repeatedly, without this option
	// it would expire once only
	XTmrCtr_SetOptions(&tmrctr, 0, XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION
	| XTC_DOWN_COUNT_OPTION);

	// Set a reset value for the timer counter such that it will expire
	// when it rolls under to 0, the reset value is loaded
	// into the timer counter when it is started
	XTmrCtr_SetResetValue(&tmrctr, 0, XPAR_AXI_TIMER_0_CLOCK_FREQ_HZ-1);

	// Start the timer counter 
	XTmrCtr_Start(&tmrctr, 0);

	while (1) {
	}
	
	Xil_DCacheDisable();
	Xil_ICacheDisable();

	return 0;
}
Exemple #21
0
int timer_method()
{

	XStatus Status;

	Status = XST_SUCCESS;

	Status = XIntc_Initialize(&intCtrl_Timer, TIMER_DEVICE_ID);
	if ( Status != XST_SUCCESS )
	{
		if( Status == XST_DEVICE_NOT_FOUND )
		{
			xil_printf("Interrupt Controller: XST_DEVICE_NOT_FOUND...\r\n");
		}
		else
		{
			xil_printf("Interrupt Controller: A different error from XST_DEVICE_NOT_FOUND...\r\n");
		}
		xil_printf("Interrupt controller: driver failed to be initialized...\r\n");
		return XST_FAILURE;
	}
	xil_printf("Interrupt controller: driver initialized!\r\n");

	Status = XIntc_Connect(&intCtrl_Timer,TIMER_IR_ID,(XInterruptHandler)timer_handler, &Timer_tmrctr);
	if ( Status != XST_SUCCESS )
	{
		xil_printf("Failed to connect the application handlers to the interrupt controller...\r\n");
		return XST_FAILURE;
	}
	xil_printf("Connected to Interrupt Controller!\r\n");


	Status = XIntc_Start(&intCtrl_Timer, XIN_REAL_MODE);
	if ( Status != XST_SUCCESS )
	{
		xil_printf("Failed to start Interrupt Controller: ...\r\n");
		return XST_FAILURE;
	}
	xil_printf("Interrupt Controller Started!\r\n");

	XIntc_Enable(&intCtrl_Timer, TIMER_IR_ID );

	Status = XTmrCtr_Initialize(&Timer_tmrctr, INTC_DEVICE_ID);
	if ( Status != XST_SUCCESS )
	{
		xil_printf("Timer initialization failed...\r\n");
		return XST_FAILURE;
	}
	xil_printf("Timer Initialized !\r\n");
	/*
	 * Enable the interrupt of the timer counter so interrupts will occur
	 * and use auto reload mode such that the timer counter will reload
	 * itself automatically and continue repeatedly, without this option
	 * it would expire once only
	 */
	XTmrCtr_SetOptions(&Timer_tmrctr, 0, XTC_INT_MODE_OPTION | XTC_AUTO_RELOAD_OPTION);
	/*
	 * Set a reset value for the timer counter such that it will expire
	 * eariler than letting it roll over from 0, the reset value is loaded
	 * into the timer counter when it is started
	 */
	XTmrCtr_SetResetValue(&Timer_tmrctr, 0, 0xFFFFFFFF-RESET_VALUE);		// 0x17D7840 = 25*10^6 clk cycles @ 50MHz = 500ms
	/*
	 * Register the intc device driver’s handler with the Standalone
	 * software platform’s interrupt table
	 */
	microblaze_register_handler((XInterruptHandler)XIntc_DeviceInterruptHandler,(void*)TIMER_DEVICE_ID);
	microblaze_enable_interrupts();
	/*
	 * Start the timer counter such that it's incrementing by default,
	 * then wait for it to timeout a number of times
	 */
	XTmrCtr_Start(&Timer_tmrctr, 0);
	xil_printf("Timer Started!\r\n");
	return XST_SUCCESS;
}
Exemple #22
0
/*
 * Initialize Timer Interrupt
 * In: interrupt frequency in Hz
 */
int initTmrInt(u32 int_freq) {
	//Variables
	int status;
	u32 reset_val;
	XScuGic_Config* IntcConfig;

	//Timer
	//Initialize Timer Controller
	status = XTmrCtr_Initialize(&tmrCtr, TMR_DEVICE_ID);
	if (status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	//Set Interrupt Handler for Timer Controller
	XTmrCtr_SetHandler(&tmrCtr, (XTmrCtr_Handler) tmrIntrHandler, &tmrCtr);

	//Reset Timer Value
	int_freq = (u32) (FPGA_FREQ / int_freq);
	reset_val = ~int_freq;

	//Reset Timer Value
	XTmrCtr_SetResetValue(&tmrCtr, 0, reset_val);

	//Set Options
	XTmrCtr_SetOptions(&tmrCtr, 0, TMR_OPTIONS);

	//GIC
	//Initialize Xil Exceptions
	Xil_ExceptionInit();

	//Initialize GIC
	IntcConfig = XScuGic_LookupConfig(INTC_DEVICE_ID);
	status = XScuGic_CfgInitialize(&Intc, IntcConfig,
			IntcConfig->CpuBaseAddress);
	if (status != XST_SUCCESS) {
		myprintf("mpu_utils.c: Error initializing SCU GIC Config.\r\n");
		return XST_FAILURE;
	}

	//Connect interrupt controller interrupt handler to HW interrupt handling logic in PS
	Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT,
			(Xil_ExceptionHandler) XScuGic_InterruptHandler, &Intc);

	//Connect driver handler (GIC) called when interrupt occurs to HW defined above
	XScuGic_Connect(&Intc, INTC_TMR_INT_ID,
			(Xil_ExceptionHandler) XTmrCtr_InterruptHandler, (void*) &tmrCtr);

	//Set Callback Handler for Timer Interrupts
	XTmrCtr_SetHandler(&tmrCtr, (XTmrCtr_Handler) tmrIntrHandler, &tmrCtr);

	//Enable Timer Interrupts
	XTmrCtr_EnableIntr(tmrCtr.BaseAddress, 0);

	//Enable Interrupts for Timer
	XScuGic_Enable(&Intc, INTC_TMR_INT_ID);

	//Enable Interrupts in Processor
	Xil_ExceptionEnableMask(XIL_EXCEPTION_IRQ);

	//Start Timer
	XTmrCtr_Start(&tmrCtr, 0);

	//Return
	return XST_SUCCESS;

}
int main(int argc, char *argv[]) 
{
   
  

   xil_printf("\r\n-----Begin Program-----\r\n"); 
   
  
//===============================================================================
   //Initilizing Data
//===============================================================================   
   data package;
   package.vector_size = SIZE;
   package.dataA = (int *) malloc(sizeof(int) * package.vector_size);
   package.dataB = (int *) malloc(sizeof(int) * package.vector_size);
   package.dataC = (int *) malloc(sizeof(int) * package.vector_size);  
   
  // xil_printf (" %08x  ,  %08x  , %08x  , \r\n", package.dataA,package.dataB,package.dataC);

   assert(package.dataA != NULL);
   assert(package.dataB != NULL);
   assert(package.dataC != NULL);
 
   int e;
 
   Hint * dataA = package.dataA;
   Hint * dataB = package.dataB;
   Hint * dataC = package.dataC; 
   
 // for (e = 0; e < package.vector_size; e++)       xil_printf("%d %d %d\r\n", dataA[e], dataB[e], dataC[e]);
   
   
//===============================================================================
	//Peripherals instantiation
//===============================================================================
   XTmrCtr mytimer;
   int Status= XTmrCtr_Initialize(&mytimer, XPAR_PERIPHERALS_AXI_TIMER_0_DEVICE_ID);
   if (Status != XST_SUCCESS) {
      xil_printf("Timer initialization failed \r\n");
		return XST_FAILURE;
		}
   XTmrCtr_SetResetValue(&mytimer, 0, 0);
   XTmrCtr_Start(&mytimer,0);
   XTmrCtr_SetResetValue(&mytimer, 1, 0);
   XTmrCtr_Start(&mytimer,1);
   package.timer= &mytimer;
   
   
   
//===============================================================================
	//Creating and joining on thread
//===============================================================================
   hthread_t tid;
   hthread_attr_t attr;
   hthread_attr_init(&attr);   

int i;   
for ( i=0; i <NUM_AVAILABLE_HETERO_CPUS ; i++)
{   
   for (e = 0; e < package.vector_size; e++)
   {
      dataA[e] = rand() %1000;
      dataB[e] = rand()%1000;
      dataC[e] = 10;
   }
   
   XTmrCtr_Reset(&mytimer,0);   

   thread_create ( &tid, &attr , foo_thread_FUNC_ID , (void * )&package, i+2, 0);
   
  
   int ret;
   if( hthread_join(tid, (void *) &ret))
   {
      xil_printf("Error joining child thread\r\n");
      while(1);
   }
   if (ret !=XST_SUCCESS){
      xil_printf("Thread returned XST_FAILURE\r\n");
      while(1);
   }



       int time= XTmrCtr_GetValue(&mytimer,0);
   xil_printf("Total exe_time  on Slave %d : %d us\r\n", i, (time)/100 );
   xil_printf("Net exe_time of the body of the thread: %d us\r\n",  (package.time)/100 );
   

//===============================================================================
	//Check to see if the result were right?
//=============================================================================== 
   for (e = 0; e < 5; e++)        xil_printf("%d %d %d\r\n", dataA[e], dataB[e], dataC[e]);
 
      for (e = 0; e < package.vector_size; e++)
    {
            if (dataC[e]!= dataA[e]+ dataB[e])
            {
                 xil_printf("Error at location %d \r\n", e);
                 while (1);
            }
    
    }
 }  
   
   
   xil_printf("FINISH\r\n");
   return 0;
}