Exemple #1
0
/**
* @brief Put a Message to a Queue.
* @param  queue_id  message queue ID obtained with \ref osMessageCreate.
* @param  info      message information.
* @param  millisec  timeout value or 0 in case of no time-out.
* @retval status code that indicates the execution status of the function.
* @note   MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS.
*/
osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec)
{
  portBASE_TYPE taskWoken = pdFALSE;
  TickType_t ticks;
  
  ticks = millisec / portTICK_PERIOD_MS;
  if (ticks == 0) {
    ticks = 1;
  }
  
  if (inHandlerMode()) {
    if (xQueueSendFromISR(queue_id, &info, &taskWoken) != pdTRUE) {
      return osErrorOS;
    }
    portEND_SWITCHING_ISR(taskWoken);
  }
  else {
    if (xQueueSend(queue_id, &info, ticks) != pdTRUE) {
      return osErrorOS;
    }
  }
  
  return osOK;
}
Exemple #2
0
/* The ISR executed when the user button is pushed. */
void EXTI0_IRQHandler( void )
{
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;

	/* The button was pushed, so ensure the LED is on before resetting the
	LED timer.  The LED timer will turn the LED off if the button is not
	pushed within 5000ms. */
	STM32vldiscovery_LEDOn( LED4 );

	/* This interrupt safe FreeRTOS function can be called from this interrupt
	because the interrupt priority is below the
	configMAX_SYSCALL_INTERRUPT_PRIORITY setting in FreeRTOSConfig.h. */
	xTimerResetFromISR( xLEDTimer, &xHigherPriorityTaskWoken );

	/* Clear the interrupt before leaving. */
	EXTI_ClearITPendingBit( EXTI_Line0 );

	/* If calling xTimerResetFromISR() caused a task (in this case the timer
	service/daemon task) to unblock, and the unblocked task has a priority
	higher than or equal to the task that was interrupted, then
	xHigherPriorityTaskWoken will now be set to pdTRUE, and calling
	portEND_SWITCHING_ISR() will ensure the unblocked task runs next. */
	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
Exemple #3
0
/* The ISR executed when the user button is pushed. */
void vPort_E_ISRHandler( void )
{
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;

	/* The button was pushed, so ensure the LED is on before resetting the
	LED timer.  The LED timer will turn the LED off if the button is not
	pushed within 5000ms. */
	vParTestSetLED( mainTIMER_CONTROLLED_LED, pdTRUE );

	/* This interrupt safe FreeRTOS function can be called from this interrupt
	because the interrupt priority is equal to or below the
	configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY setting in FreeRTOSConfig.h. */
	xTimerResetFromISR( xLEDButtonTimer, &xHigherPriorityTaskWoken );

	/* Clear the interrupt before leaving.  */
	PORTE_ISFR = 0xFFFFFFFFUL;

	/* If calling xTimerResetFromISR() caused a task (in this case the timer
	service/daemon task) to unblock, and the unblocked task has a priority
	higher than or equal to the task that was interrupted, then
	xHigherPriorityTaskWoken will now be set to pdTRUE, and calling
	portEND_SWITCHING_ISR() will ensure the unblocked task runs next. */
	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
/**
 * @brief	EMAC interrupt handler
 * @return	Nothing
 * @note	This function handles the transmit, receive, and error interrupt of
 * the LPC17xx/40xx. This is meant to be used when NO_SYS=0.
 */
void ETH_IRQHandler(void)
{
#if NO_SYS == 1
    /* Interrupts are not used without an RTOS */
    NVIC_DisableIRQ(ETHERNET_IRQn);
#else
    signed portBASE_TYPE xRecTaskWoken = pdFALSE, XTXTaskWoken = pdFALSE;
    uint32_t ints;

    /* Interrupts are of 2 groups - transmit or receive. Based on the
       interrupt, kick off the receive or transmit (cleanup) task */

    /* Get pending interrupts */
    ints = Chip_ENET_GetIntStatus(LPC_ETHERNET);

    if (ints & RXINTGROUP) {
        /* RX group interrupt(s) */
        /* Give semaphore to wakeup RX receive task. Note the FreeRTOS
           method is used instead of the LWIP arch method. */
        xSemaphoreGiveFromISR(lpc_enetdata.rx_sem, &xRecTaskWoken);
    }

    if (ints & TXINTGROUP) {
        /* TX group interrupt(s) */
        /* Give semaphore to wakeup TX cleanup task. Note the FreeRTOS
           method is used instead of the LWIP arch method. */
        xSemaphoreGiveFromISR(lpc_enetdata.tx_clean_sem, &XTXTaskWoken);
    }

    /* Clear pending interrupts */
    Chip_ENET_ClearIntStatus(LPC_ETHERNET, ints);

    /* Context switch needed? */
    portEND_SWITCHING_ISR(xRecTaskWoken || XTXTaskWoken);
#endif
}
static void vUARTReceiveHandler( alt_u32 status )
{
signed char cChar;
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;

	/* If there was an error, discard the data */
	if ( status & ( ALTERA_AVALON_UART_STATUS_PE_MSK | ALTERA_AVALON_UART_STATUS_FE_MSK ) )
	{
        asm("break");
		return;
	}

	/* Transfer data from the device to the circular buffer */
	cChar = IORD_ALTERA_AVALON_UART_RXDATA( UART_BASE );
	if ( pdTRUE != xQueueSendFromISR( xRxedChars, &cChar, &xHigherPriorityTaskWoken ) )
	{
		/* If the circular buffer was full, disable interrupts. Interrupts will 
        be re-enabled when data is removed from the buffer. */
		uartControl &= ~ALTERA_AVALON_UART_CONTROL_RRDY_MSK;
		IOWR_ALTERA_AVALON_UART_CONTROL( UART_BASE, uartControl );
	}
    
	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
void vT5InterruptHandler( void )
{
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;

	/* This function is the handler for the peripheral timer interrupt.
	The interrupt is initially signalled in a separate assembly file
	which switches to the system stack and then calls this function.
	It gives a semaphore which signals the prvISRBlockTask */

	/* Give the semaphore.  If giving the semaphore causes the task to leave the
	Blocked state, and the priority of the task is higher than the priority of
	the interrupted task, then xHigherPriorityTaskWoken will be set to pdTRUE
	inside the xSemaphoreGiveFromISR() function.  xHigherPriorityTaskWoken is
	later passed into portEND_SWITCHING_ISR(), where a context switch is
	requested if it is pdTRUE.  The context switch ensures the interrupt returns
	directly to the unblocked task. */
	xSemaphoreGiveFromISR( xBlockSemaphore, &xHigherPriorityTaskWoken );

	/* Clear the interrupt */
	IFS0CLR = _IFS0_T5IF_MASK;

	/* See comment above the call to xSemaphoreGiveFromISR(). */
	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
Exemple #7
0
void vUARTInterruptHandler( void )
{
    portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
    char cChar;

    if( USART_GetITStatus( USART1, USART_IT_TXE ) == SET ) {
        /* The interrupt was caused by the THR becoming empty.  Are there any
        more characters to transmit? */
        if( xQueueReceiveFromISR( xCharsForTx, &cChar, &xHigherPriorityTaskWoken ) == pdTRUE ) {
            /* A character was retrieved from the queue so can be sent to the
            THR now. */
            USART_SendData( USART1, cChar );
        } else {
            USART_ITConfig( USART1, USART_IT_TXE, DISABLE );
        }
    }

    if( USART_GetITStatus( USART1, USART_IT_RXNE ) == SET ) {
        cChar = USART_ReceiveData( USART1 );
        xQueueSendFromISR( xRxedChars, &cChar, &xHigherPriorityTaskWoken );
    }

    portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
Exemple #8
0
void usart1_isr(void) {
	long xHigherPriorityTaskWoken = pdFALSE;
	char cChar;

	// ----- transmission complete:
	if (usart_get_flag(USART1, USART_SR_TC) == true) {
		gpio_clear(GPIOA, GPIO12); // clear RTS
		gpio_clear(GPIOA, GPIO_USART1_TX); // clear DI
		USART_SR(USART1) &= ~USART_SR_TC;	// reset flag TC
		usart_disable_tx_interrupt(USART1);
	}

	if (usart_get_flag(USART1, USART_SR_TXE) == true) {
		/* The interrupt was caused by the THR becoming empty.  Are there any
		 more characters to transmit? */
		if (xQueueReceiveFromISR(xCharsForTx[0], &cChar,
				&xHigherPriorityTaskWoken)) {
			/* A character was retrieved from the buffer so can be sent to the
			 THR now. */
			gpio_set(GPIOA, GPIO12); // set RTS
			usart_send(USART1, (uint8_t) cChar);
		} else {
//			gpio_clear(GPIOA, GPIO12); // clear RTS
//			usart_disable_tx_interrupt(USART1);
//			USART_SR(USART1) &= ~USART_SR_TXE;	// reset flag TXE
//			USART_CR1(USART1) |= USART_CR1_TCIE;
		}
	}

	if (usart_get_flag(USART1, USART_SR_RXNE) == true) {
		cChar = (char) usart_recv(USART1);
		xQueueSendFromISR(xRxedChars[0], &cChar, &xHigherPriorityTaskWoken);
	}

	portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
}
void EP3_OUT_Callback(void)
{
        portBASE_TYPE hpta = false;
        xQueueHandle queue = serial_get_rx_queue(usb_state.serial);
        uint8_t *buff = usb_state.USB_Rx_Buffer;

	/* Get the received data buffer and clear the counter */
	const size_t len = USB_SIL_Read(EP3_OUT, buff);

        for (size_t i = 0; i < len; ++i)
                xQueueSendFromISR(queue, buff + i, &hpta);

	/*
         * STIEG HACK
         * For now just assume that all the data made it into the queue.  This
         * is what we do in MK2.  Probably shouldn't go out the door like this.
	 */
        SetEPRxValid(ENDP3);

        if (usb_state.rx_isr_cb)
                usb_state.rx_isr_cb();

        portEND_SWITCHING_ISR(hpta);
}
Exemple #10
0
void vT3InterruptHandler( void )
{
	TimerIntClear( TIMER3_BASE, TIMER_TIMA_TIMEOUT );
	portEND_SWITCHING_ISR( xSecondTimerHandler() );
}
Exemple #11
0
/*
 * For internal use only.
 * A common SPI interrupt handler that is called for all SPI peripherals.
 */
static void local_spi_handler(const portBASE_TYPE spi_index)
{
	portBASE_TYPE higher_priority_task_woken = pdFALSE;
	uint32_t spi_status;
	Spi *spi_port;

	spi_port = all_spi_definitions[spi_index].peripheral_base_address;

	spi_status = spi_read_status(spi_port);
	spi_status &= spi_read_interrupt_mask(spi_port);

	/* Has the PDC completed a transmission? */
	if ((spi_status & SPI_SR_ENDTX) != 0UL) {
		spi_disable_interrupt(spi_port, SPI_IDR_ENDTX);

		/* If the driver is supporting multi-threading, then return the access
		mutex. */
		if (tx_dma_control[spi_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[spi_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}

		/* if the sending task supplied a notification semaphore, then
		 * notify the task that the transmission has completed. */
		if (tx_dma_control[spi_index].transaction_complete_notification_semaphore != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[spi_index].transaction_complete_notification_semaphore,
					&higher_priority_task_woken);
		}
	}

	/* Has the PDC completed a reception? */
	if ((spi_status & SPI_SR_ENDRX) != 0UL) {
		spi_disable_interrupt(spi_port, SPI_IDR_ENDRX);

		/* If the driver is supporting multi-threading, then return the access
		mutex.  NOTE: As a reception is performed by first performing a
		transmission, the SPI receive function uses the tx access semaphore. */
		if (tx_dma_control[spi_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[spi_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}

		/* If the receiving task supplied a notification semaphore, then
		notify the task that the transmission has completed. */
		if (rx_dma_control[spi_index].transaction_complete_notification_semaphore != NULL) {
			xSemaphoreGiveFromISR(
					rx_dma_control[spi_index].transaction_complete_notification_semaphore,
					&higher_priority_task_woken);
		}
	}

	if ((spi_status & SR_ERROR_INTERRUPTS) != 0) {
		/* An mode error occurred in either a transmission or reception.  Abort.
		Stop the transmission, disable interrupts used by the peripheral, and
		ensure the peripheral access mutex is made available to tasks.  As this
		peripheral is half duplex, only the Tx peripheral access mutex exits. */
		spi_disable_interrupt(spi_port, SPI_IDR_ENDTX);
		spi_disable_interrupt(spi_port, SPI_IDR_ENDRX);

		if (tx_dma_control[spi_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[spi_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}

		/* The SPI port will have been disabled, re-enable it. */
		spi_enable(spi_port);
	}

	/* If giving a semaphore caused a task to unblock, and the unblocked task
	has a priority equal to or higher than the currently running task (the task
	this ISR interrupted), then higher_priority_task_woken will have
	automatically been set to pdTRUE within the semaphore function.
	portEND_SWITCHING_ISR() will then ensure that this ISR returns directly to
	the higher priority unblocked task. */
	portEND_SWITCHING_ISR(higher_priority_task_woken);
}
Exemple #12
0
void __attribute__ ((interrupt)) __cs3_isr_interrupt_120( void )
{
	MCF_PIT1_PCSR |= MCF_PIT_PCSR_PIF;
	portEND_SWITCHING_ISR( xFirstTimerHandler() );
}
void UART3_IRQHandler( void )
{
uint32_t ulInterruptSource, ulReceived;
const uint32_t ulRxInterrupts = ( UART_IIR_INTID_RDA | UART_IIR_INTID_CTI );
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
const unsigned portBASE_TYPE uxUARTNumber = 3UL;
Transfer_Control_t *pxTransferStruct;

	/* Determine the interrupt source. */
	ulInterruptSource = UART_GetIntId( LPC_UART3 );

	if( ( ulInterruptSource & ulRxInterrupts ) != 0UL )
	{
		pxTransferStruct = pxRxTransferControlStructs[ uxUARTNumber ];
		if( pxTransferStruct != NULL )
		{
			switch( diGET_TRANSFER_TYPE_FROM_CONTROL_STRUCT( pxTransferStruct ) )
			{
				case ioctlUSE_CIRCULAR_BUFFER_RX :

					#if ioconfigUSE_UART_CIRCULAR_BUFFER_RX == 1
					{
						ioutilsRX_CHARS_INTO_CIRCULAR_BUFFER_FROM_ISR(
																	pxTransferStruct, 	/* The structure that contains the reference to the circular buffer. */
																	( ( LPC_UART3->LSR & UART_LSR_RDR ) != 0 ), 	/* While loop condition. */
																	LPC_UART3->RBR,			/* Register holding the received character. */
																	ulReceived,
																	xHigherPriorityTaskWoken
																);
					}
					#endif /* ioconfigUSE_UART_CIRCULAR_BUFFER_RX */
					break;


				case ioctlUSE_CHARACTER_QUEUE_RX :

					#if ioconfigUSE_UART_RX_CHAR_QUEUE == 1
					{
						ioutilsRX_CHARS_INTO_QUEUE_FROM_ISR( pxTransferStruct, ( ( LPC_UART3->LSR & UART_LSR_RDR ) != 0 ), LPC_UART3->RBR, ulReceived, xHigherPriorityTaskWoken );
					}
					#endif /* ioconfigUSE_UART_RX_CHAR_QUEUE */
					break;


				default :

					/* This must be an error.  Force an assert. */
					configASSERT( xHigherPriorityTaskWoken );
					break;
			}
		}
	}

	if( ( ulInterruptSource & UART_IIR_INTID_THRE ) != 0UL )
	{
		/* The transmit holding register is empty.  Is there any more data
		to send? */
		pxTransferStruct = pxTxTransferControlStructs[ uxUARTNumber ];
		if( pxTransferStruct != NULL )
		{
			switch( diGET_TRANSFER_TYPE_FROM_CONTROL_STRUCT( pxTransferStruct ) )
			{
				case ioctlUSE_ZERO_COPY_TX:

					#if ioconfigUSE_UART_ZERO_COPY_TX == 1
					{
						iouitlsTX_CHARS_FROM_ZERO_COPY_BUFFER_FROM_ISR( pxTransferStruct, ( ( LPC_UART3->FIFOLVL & uartTX_FIFO_LEVEL_MASK ) != uartTX_FIFO_LEVEL_MASK ), ( LPC_UART3->THR = ucChar ), xHigherPriorityTaskWoken );
					}
					#endif /* ioconfigUSE_UART_ZERO_COPY_TX */
					break;


				case ioctlUSE_CHARACTER_QUEUE_TX:

					#if ioconfigUSE_UART_TX_CHAR_QUEUE == 1
					{
						ioutilsTX_CHARS_FROM_QUEUE_FROM_ISR( pxTransferStruct, ( UART_FIFOLVL_TXFIFOLVL( LPC_UART3->FIFOLVL ) != ( UART_TX_FIFO_SIZE - 1 ) ), ( LPC_UART3->THR = ucChar ), xHigherPriorityTaskWoken );
					}
					#endif /* ioconfigUSE_UART_TX_CHAR_QUEUE */
					break;


				default :

					/* This must be an error.  Force an assert. */
					configASSERT( xHigherPriorityTaskWoken );
					break;
			}
		}
	}

	/* The ulReceived parameter is not used by the UART ISR. */
	( void ) ulReceived;

	/* If lHigherPriorityTaskWoken is now equal to pdTRUE, then a context
	switch should be performed before the interrupt exists.  That ensures the
	unblocked (higher priority) task is returned to immediately. */
	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
void USART1_IRQHandler (void)//следует разработать систему распознавания старого протокола или заменить на выбор вручную
{
 	static portBASE_TYPE xHigherPriorityTaskWoken;
 	  xHigherPriorityTaskWoken = pdFALSE;

//

 	if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
   	{

 		USART_ClearITPendingBit(USART1, USART_IT_RXNE);


   		symbol=USART_ReceiveData (USART1);
   //----------------------обрабатываем возможные ошибки длины кадра-------------
   		if(recieve_count>MAX_LENGTH_REC_BUF)	//если посылка слишком длинная
   		{
   			recieve_count=0x0;
   			return;
   		}

		if(recieve_count==0x0)
		{
			if(symbol==':')//признак старого протокола
			{
				proto_type=PROTO_TYPE_OLD;
			}
			else
			{
				if((symbol==0x0) || (symbol==0xD7))//новый протокол
				{
					proto_type=PROTO_TYPE_NEW;
				}
				else//ошибка кадра или не с начала
				{
					return;
				}
			}
		}
switch(proto_type)
{
	case PROTO_TYPE_OLD:
	{
		if(symbol==':')
		{
			recieve_count=0x0;
		}

		tab.tablo_proto_buf[recieve_count]=symbol;
		recieve_count++;

		if(recieve_count>1)
		{
			if(tab.tablo_proto_buf[1]==(recieve_count-2))//кадр принят
			{
				 USART_ITConfig(USART1, USART_IT_RXNE , DISABLE);
				xSemaphoreGiveFromISR( xProtoSemaphore, &xHigherPriorityTaskWoken );

  				 if( xHigherPriorityTaskWoken != pdFALSE )
  				 {
  					portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
  				 }
			}
		}



	}
	break;

	case PROTO_TYPE_NEW:
	{
	//--------------------------начало кадра...проверка до длины кадра--------
   	    if(recieve_count<6)
   		{
   	    		switch(recieve_count)
   				{
   					case  0:   //первый символ 0
   					{
   	 				 	 if(symbol!=0x00)
   						 {
   	 				 		recieve_count=0;

   	 				 	fr_err++;
   							//return;
   						 }
   					}
   					break;

   					case 1:	 //второй символ 0xD7
   					{
   						 if(symbol!=0xD7)
   						 {
   							recieve_count=0;

   							//return;
   						 }
   					}
   					break;

   					case 2:	 //	третий символ 0x29
   					{
   					 	 if(symbol!=0x29)
   						 {
   					 		recieve_count=0;

   							//return;
   						 }
   					}
   					break;

   					case 3:	//если адрес не совпал, то сбросим//NEW
   					{
   						if(symbol!=ADRESS_DEV)//если адрес совпал
   						{
   							recieve_count=0;

   							//return;
   						}
   					}
   					break;

   					default:  //
   					{
   					}
   					break;
   				}

   			RecieveBuf[recieve_count]=symbol;//сохраняем принятый символ в буфер
   			recieve_count++;//счетчик буфера

   			if(recieve_count==6)
   			{
   				frame_len=RecieveBuf[recieve_count-1]; //получим оставшуюся длину
   			}
   		}
   //---------------------------------------------------------
   		else  //отсюда знаем длину кадра и удаляем нули после 0xD7
   		{
   			switch(symbol)//проверим, это 0x0 ,0xD7 или другое
   			{
   				case 0xD7:
   				{
   					CUT_OUT_NULL=1;	//
   					RecieveBuf[recieve_count]=symbol;
   					recieve_count++;

   				}
   				break;

   				case 0x0:
   				{
   					if(!CUT_OUT_NULL)  //если вырезать 0x0 не надо, то не вырезаем
   					{
   						RecieveBuf[recieve_count]=symbol;
   						recieve_count++;
   					}
   					else //иначе в буфер не кладем, сбросим флаг
   					{
   						CUT_OUT_NULL=0;
   					}
   				}
   				break;

   				default:  //другие кладем в буфер
   				{
   					CUT_OUT_NULL=0;
   					RecieveBuf[recieve_count]=symbol;
   					recieve_count++;
   				}
   				break;
   			}

   			if(recieve_count>=frame_len+6)//если приняты  все байты
   			{
   				 USART_ITConfig(USART1, USART_IT_RXNE , DISABLE);
   				  /* 'Дать' семафор для разблокировки задачи. */

   				 xSemaphoreGiveFromISR( xProtoSemaphore, &xHigherPriorityTaskWoken );

   				 if( xHigherPriorityTaskWoken != pdFALSE )
   				 {
   					portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
   				 }
   			}
   		}
	}
}

   	}
   //----------------------------передача----------------------------------------------------------------
   	if(USART_GetITStatus(USART1, USART_IT_TC) != RESET)
   	{

   		USART_ClearITPendingBit(USART1, USART_IT_TC);//очищаем признак прерывания

   		if(transf_count<buf_len)
   		{
   			if(transf_count<3)//передаем заголовок
   			{
   				USART_SendData(USART1,TransferBuf[transf_count]);
   				transf_count++;
   			}
   			else   //тело...   подставляем 0 после 0xD7
   			{
   					if(CUT_OUT_NULL==0)
   					{
   						if(TransferBuf[transf_count]==(uint8_t)0xD7)//проверим, это  ,0xD7 или другое
   						{
   							CUT_OUT_NULL=0x1;
   						}
   						USART_SendData(USART1,TransferBuf[transf_count]);
   						transf_count++;
   					}
   					else
   					{
   						USART_SendData(USART1,(uint8_t)0x0);
   						CUT_OUT_NULL=0;
   					}
   			}
   		}
   		else
   		{
   			transf_count=0;		//обнуляем счетчик
   			recieve_count=0;

   			CUT_OUT_NULL=0;
   			 USART_ITConfig(USART1, USART_IT_RXNE , ENABLE);
   		}

   	}
   	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );

}
Exemple #15
0
void vT4InterruptHandler( void )
{
    IFS0CLR = _IFS0_T4IF_MASK;
    portEND_SWITCHING_ISR( xSecondTimerHandler() );
}
/*
 * For internal use only.
 * A common TWI interrupt handler that is called for all TWI peripherals.
 */
static void local_twi_handler(const portBASE_TYPE twi_index)
{
	portBASE_TYPE higher_priority_task_woken = pdFALSE;
	uint32_t twi_status;
	Twi *twi_port;
	bool transfer_timeout = false;

	twi_port = all_twi_definitions[twi_index].peripheral_base_address;

	twi_status = twi_get_interrupt_status(twi_port);
	twi_status &= twi_get_interrupt_mask(twi_port);

	/* Has the PDC completed a transmission? */
	if ((twi_status & TWI_SR_ENDTX) != 0UL) {
		/* Disable PDC */
		pdc_disable_transfer(all_twi_definitions[twi_index].pdc_base_address, PERIPH_PTCR_TXTDIS);
		twi_disable_interrupt(twi_port, TWI_IDR_ENDTX);

		uint8_t status;
		uint32_t timeout_counter = 0;

		/* Wait for TX ready flag */
		while (1) {
			status = twi_port->TWI_SR;
			if (status & TWI_SR_TXRDY) {
				break;
			}
			/* Check timeout condition. */
			if (++timeout_counter >= TWI_TIMEOUT_COUNTER) {
				transfer_timeout = true;
				break;
			}
		}
		/* Complete the transfer - stop and last byte */
		twi_port->TWI_CR = TWI_CR_STOP;
		twi_port->TWI_THR = twis[twi_index].buffer[twis[twi_index].length-1];

		/* Wait for TX complete flag */
		while (1) {
			status = twi_port->TWI_SR;
			if (status & TWI_SR_TXCOMP) {
				break;
			}
			/* Check timeout condition. */
			if (++timeout_counter >= TWI_TIMEOUT_COUNTER) {
				transfer_timeout = true;
				break;
			}
		}
		/* If the driver is supporting multi-threading, then return the access
		mutex. */
		if (tx_dma_control[twi_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[twi_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}

		/* if the sending task supplied a notification semaphore, then
		notify the task that the transmission has completed. */
		if (!(timeout_counter >= TWI_TIMEOUT_COUNTER)) {
			if (tx_dma_control[twi_index]. transaction_complete_notification_semaphore != NULL) {
				xSemaphoreGiveFromISR(
						tx_dma_control[twi_index].transaction_complete_notification_semaphore,
						&higher_priority_task_woken);
			}
		}
	}

	/* Has the PDC completed a reception? */
	if ((twi_status & TWI_SR_ENDRX) != 0UL) {
		uint32_t timeout_counter = 0;
		uint32_t status;
		/* Must handle the two last bytes */
		/* Disable PDC */
		pdc_disable_transfer(all_twi_definitions[twi_index].pdc_base_address, PERIPH_PTCR_RXTDIS);

		twi_disable_interrupt(twi_port, TWI_IDR_ENDRX);

		/* Wait for RX ready flag */
		while (1) {
			status = twi_port->TWI_SR;
			if (status & TWI_SR_RXRDY) {
				break;
			}
			/* Check timeout condition. */
			if (++timeout_counter >= TWI_TIMEOUT_COUNTER) {
				break;
			}
		}
		/* Complete the transfer. */
		twi_port->TWI_CR = TWI_CR_STOP;
		/* Read second last data */
		twis[twi_index].buffer[(twis[twi_index].length)-2] = twi_port->TWI_RHR;

		/* Wait for RX ready flag */
		while (1) {
			status = twi_port->TWI_SR;
			if (status & TWI_SR_RXRDY) {
				break;
			}
			/* Check timeout condition. */
			if (++timeout_counter >= TWI_TIMEOUT_COUNTER) {
				break;
			}
		}

		if (!(timeout_counter >= TWI_TIMEOUT_COUNTER)) {
			/* Read last data */
			twis[twi_index].buffer[(twis[twi_index].length)-1] = twi_port->TWI_RHR;
			timeout_counter = 0;
			/* Wait for TX complete flag before releasing semaphore */
			while (1) {
				status = twi_port->TWI_SR;
				if (status & TWI_SR_TXCOMP) {
					break;
				}
				/* Check timeout condition. */
				if (++timeout_counter >= TWI_TIMEOUT_COUNTER) {
					transfer_timeout = true;
					break;
				}
			}
		}

		/* If the driver is supporting multi-threading, then return the access
		mutex.  NOTE: As the peripheral is half duplex there is only one
		access mutex, and the reception uses the tx access muted. */
		if (tx_dma_control[twi_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[twi_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}

		/* if the receiving task supplied a notification semaphore, then
		notify the task that the transmission has completed. */
		if  (!(timeout_counter >= TWI_TIMEOUT_COUNTER)) {
			if (rx_dma_control[twi_index].transaction_complete_notification_semaphore != NULL) {
				xSemaphoreGiveFromISR(
						rx_dma_control[twi_index].transaction_complete_notification_semaphore,
						&higher_priority_task_woken);
			}
		}
	}

	if (((twi_status & SR_ERROR_INTERRUPTS) != 0) || (transfer_timeout == true)) {
		/* An error occurred in either a transmission or reception.  Abort.
		Stop the transmission, disable interrupts used by the peripheral, and
		ensure the peripheral access mutex is made available to tasks.  As this
		peripheral is half duplex, only the Tx peripheral access mutex exits.*/

		/* Stop the PDC */
		pdc_disable_transfer(all_twi_definitions[twi_index].pdc_base_address, PERIPH_PTCR_TXTDIS | PERIPH_PTCR_RXTDIS);

		if (!(twi_status & TWI_SR_NACK)) {
			/* Do not send stop if NACK received. Handled by hardware */
			twi_port->TWI_CR = TWI_CR_STOP;
		}
		twi_disable_interrupt(twi_port, TWI_IDR_ENDTX);
		twi_disable_interrupt(twi_port, TWI_IDR_ENDRX);

		if (tx_dma_control[twi_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[twi_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}
	}

	/* If giving a semaphore caused a task to unblock, and the unblocked task
	has a priority equal to or higher than the currently running task (the task
	this ISR interrupted), then higher_priority_task_woken will have
	automatically been set to pdTRUE within the semaphore function.
	portEND_SWITCHING_ISR() will then ensure that this ISR returns directly to
	the higher priority unblocked task. */
	portEND_SWITCHING_ISR(higher_priority_task_woken);
}
Exemple #17
0
void vT3InterruptHandler( void )
{
    IFS0CLR = _IFS0_T3IF_MASK;
    portEND_SWITCHING_ISR( xFirstTimerHandler() );
}
Exemple #18
0
void SSP1_IRQHandler( void )
{
uint32_t ulInterruptSource;
volatile uint32_t usJunk, ulReceived = 0UL;
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
const unsigned portBASE_TYPE uxSSPNumber = 1UL;
Transfer_Control_t *pxTxTransferStruct, *pxRxTransferStruct;

	/* Determine the interrupt source. */
	ulInterruptSource = LPC_SSP1->MIS;

	/* Clear receive overruns, and optionally assert. */
	if( ( ulInterruptSource & SSP_INTSTAT_ROR ) != 0 )
	{
		configASSERT( ( ulInterruptSource & SSP_INTSTAT_ROR ) == 0 );
		LPC_SSP1->ICR = SSP_INTCLR_ROR;
	}

	/* Clear timeouts. */
	if( ( ulInterruptSource & SSP_INTSTAT_RT ) != 0 )
	{
		LPC_SSP1->ICR = SSP_INTCLR_RT;
	}

	/* Is this a receive FIFO half full or receive timeout? */
	if( ( ulInterruptSource & sspRX_DATA_AVAILABLE_INTERRUPTS ) != 0 )
	{
		pxTxTransferStruct = pxTxTransferControlStructs[ uxSSPNumber ];
		pxRxTransferStruct = pxRxTransferControlStructs[ uxSSPNumber ];
		configASSERT( pxRxTransferStruct );
		configASSERT( pxTxTransferStruct );

		if( pxRxTransferStruct != NULL )
		{
			if( ulReceiveActive[ uxSSPNumber ] == pdFALSE )
			{
				/* The data being received is just in response to data
				being sent,	not in response to data being read, just
				just junk it. */
				while( ( LPC_SSP1->SR & SSP_SR_RNE ) != 0 )
				{
					usJunk = LPC_SSP1->DR;
					ulReceived++;
				}
			}
			else
			{
				/* Data is being received because a read is being
				performed.  Store the data using whichever
				transfer mechanism is currently configured. */
				switch( diGET_TRANSFER_TYPE_FROM_CONTROL_STRUCT( pxRxTransferStruct ) )
				{
					case ioctlUSE_CIRCULAR_BUFFER_RX :

						#if ioconfigUSE_SSP_CIRCULAR_BUFFER_RX == 1
						{
							/* This call will empty the FIFO, and give the New
							Data semaphore so a task blocked on an SSP read
							will unblock.  Note that this does not mean that
							more data will not arrive after this interrupt,
							even if there is no more data to send. */
							ioutilsRX_CHARS_INTO_CIRCULAR_BUFFER_FROM_ISR(
																		pxRxTransferStruct, 	/* The structure that contains the reference to the circular buffer. */
																		( ( LPC_SSP1->SR & SSP_SR_RNE ) != 0 ), 		/* While loop condition. */
																		( LPC_SSP1->DR ),						/* The function that returns the chars. */
																		ulReceived,
																		xHigherPriorityTaskWoken
																	);
						}
						#endif /* ioconfigUSE_SSP_CIRCULAR_BUFFER_RX */
						break;


					case ioctlUSE_CHARACTER_QUEUE_RX :

						#if ioconfigUSE_SSP_RX_CHAR_QUEUE == 1
						{
							ioutilsRX_CHARS_INTO_QUEUE_FROM_ISR( pxRxTransferStruct, ( ( LPC_SSP1->SR & SSP_SR_RNE ) != 0 ), ( LPC_SSP1->DR ), ulReceived, xHigherPriorityTaskWoken );
						}
						#endif /* ioconfigUSE_SSP_RX_CHAR_QUEUE */
						break;


					default :

						/* This must be an error.  Force an assert. */
						configASSERT( xHigherPriorityTaskWoken );
						break;
				}
			}

			/* Space has been created in the Rx FIFO, see if there is any data
			to send to the Tx FIFO. */
			switch( diGET_TRANSFER_TYPE_FROM_CONTROL_STRUCT( pxTxTransferStruct ) )
			{
				case ioctlUSE_ZERO_COPY_TX:

					#if ioconfigUSE_SSP_ZERO_COPY_TX == 1
					{
						iouitlsTX_CHARS_FROM_ZERO_COPY_BUFFER_FROM_ISR( pxTxTransferStruct, ( ( ulReceived-- ) > 0 ), ( LPC_SSP1->DR = ucChar), xHigherPriorityTaskWoken );
					}
					#endif /* ioconfigUSE_SSP_ZERO_COPY_TX */
					break;


				case ioctlUSE_CHARACTER_QUEUE_TX:

					#if ioconfigUSE_SSP_TX_CHAR_QUEUE == 1
					{
						ioutilsTX_CHARS_FROM_QUEUE_FROM_ISR( pxTxTransferStruct, ( ( ulReceived-- ) > 0 ), ( LPC_SSP1->DR = SSP_DR_BITMASK( ( uint16_t ) ucChar ) ), xHigherPriorityTaskWoken );
					}
					#endif /* ioconfigUSE_SSP_TX_CHAR_QUEUE */
					break;


				default :

					/* Should not get here.  Set the saved transfer control
					structure to NULL so the Tx interrupt will get disabled
					before this ISR is exited. */
					pxTxTransferControlStructs[ uxSSPNumber ] = NULL;

					/* This must be an error.  Force an assert. */
					configASSERT( xHigherPriorityTaskWoken );
					break;
			}
		}
	}

	/* If lHigherPriorityTaskWoken is now equal to pdTRUE, then a context
	switch should be performed before the interrupt exists.  That ensures the
	unblocked (higher priority) task is returned to immediately. */
	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
/*
 * For internal use only.
 * A common UART interrupt handler that is called for all UART peripherals.
 */
static void local_uart_handler(const portBASE_TYPE uart_index)
{
	portBASE_TYPE higher_priority_task_woken = pdFALSE;
	uint32_t uart_status;
	freertos_pdc_rx_control_t *rx_buffer_definition;

	uart_status = uart_get_status(
			all_uart_definitions[uart_index].peripheral_base_address);
	uart_status &= uart_get_interrupt_mask(
			all_uart_definitions[uart_index].peripheral_base_address);

	rx_buffer_definition = &(rx_buffer_definitions[uart_index]);

	/* Has the PDC completed a transmission? */
	if ((uart_status & UART_SR_ENDTX) != 0UL) {
		uart_disable_interrupt(
				all_uart_definitions[uart_index].peripheral_base_address,
				UART_IDR_ENDTX);

		/* If the driver is supporting multi-threading, then return the access
		mutex. */
		if (tx_dma_control[uart_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[uart_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}

		/* if the sending task supplied a notification semaphore, then
		notify the task that the transmission has completed. */
		if (tx_dma_control[uart_index].transaction_complete_notification_semaphore != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[uart_index].transaction_complete_notification_semaphore,
					&higher_priority_task_woken);
		}
	}

	if ((uart_status & UART_SR_ENDRX) != 0UL) {
		/* It is possible to initialise the peripheral to only use Tx and not Rx.
		Check that Rx has been initialised. */
		configASSERT(rx_buffer_definition->next_byte_to_read);
		configASSERT(rx_buffer_definition->next_byte_to_read !=
				RX_NOT_USED);

		/* Out of DMA buffer, configure the next buffer.  Start by moving
		the DMA buffer start address up to the end of the previously defined
		buffer. */
		rx_buffer_definition->rx_pdc_parameters.ul_addr +=
				rx_buffer_definition->rx_pdc_parameters.ul_size;

		/* If the end of the buffer has been reached, wrap back to the start. */
		if (rx_buffer_definition->rx_pdc_parameters.ul_addr >=
				rx_buffer_definition->past_rx_buffer_end_address)
		{
			rx_buffer_definition->rx_pdc_parameters.ul_addr =
					rx_buffer_definition->rx_buffer_start_address;
		}

		/* Reset the Rx DMA to receive data into whatever free space remains in
		the Rx buffer. */
		configure_rx_dma(uart_index, data_added);

		if (rx_buffer_definition->rx_event_semaphore != NULL) {
			/* Notify that new data is available. */
			xSemaphoreGiveFromISR(
					rx_buffer_definition->rx_event_semaphore,
					&higher_priority_task_woken);
		}
	}

	/**
	 * Normally the uart_status can't be "0" when the interrupt happened.
	 * It happened only when in PDC mode with TXRDY and RXRDY interrupts since
	 * the flags has been cleared by PDC.
	 * As the TXRDY is never enabled in this service, here we
	 * check the RXRDY interrupt case.
	 */
	if (uart_status == 0UL) {
		/* Character has been placed into the Rx buffer. */
		if (rx_buffer_definition->rx_event_semaphore != NULL) {
			/* Notify that new data is available. */
			xSemaphoreGiveFromISR(
					rx_buffer_definition->rx_event_semaphore,
					&higher_priority_task_woken);
		}
	}

	if ((uart_status & SR_ERROR_INTERRUPTS) != 0) {
		/* An error occurred in either a transmission or reception.  Abort, and
		ensure the peripheral access mutex is made available to tasks. */
		uart_reset_status(
				all_uart_definitions[uart_index].peripheral_base_address);
		if (tx_dma_control[uart_index].peripheral_access_mutex != NULL) {
			xSemaphoreGiveFromISR(
					tx_dma_control[uart_index].peripheral_access_mutex,
					&higher_priority_task_woken);
		}
	}

	/* If giving a semaphore caused a task to unblock, and the unblocked task
	has a priority equal to or higher than the currently running task (the task
	this ISR interrupted), then higher_priority_task_woken will have
	automatically been set to pdTRUE within the semaphore function.
	portEND_SWITCHING_ISR() will then ensure that this ISR returns directly to
	the higher priority unblocked task. */
	portEND_SWITCHING_ISR(higher_priority_task_woken);
}
Exemple #20
0
/**
* @brief  Start or restart a timer.
* @param  timer_id      timer ID obtained by \ref osTimerCreate.
* @param  millisec      time delay value of the timer.
* @retval  status code that indicates the execution status of the function
* @note   MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS.
*/
osStatus osTimerStart (osTimerId timer_id, uint32_t millisec)
{
  osStatus result = osOK;
#if (configUSE_TIMERS == 1)  
	portBASE_TYPE taskWoken = pdFALSE;
  TickType_t ticks = millisec / portTICK_PERIOD_MS;
  
  if (xTimerIsTimerActive(timer_id) != pdFALSE)
  {
    if (inHandlerMode()) 
    {
      if(xTimerResetFromISR(timer_id, &taskWoken) != pdPASS)
      {
        result = osErrorOS;
      }
      else
      {
        portEND_SWITCHING_ISR(taskWoken);
        result = osOK;
      }
    }
    else
    {
      if (xTimerReset(timer_id, 0) != pdPASS)
        result = osErrorOS;
      else   
        result = osOK;
    }
  }
  else
  {
    if (ticks == 0)
      ticks = 1;
    
    if (inHandlerMode()) 
    {
      if (xTimerChangePeriodFromISR(timer_id, ticks, &taskWoken) != pdPASS) 
        result = osErrorOS;
      else
      {
        xTimerStartFromISR(timer_id, &taskWoken);
        portEND_SWITCHING_ISR(taskWoken);
        result = osOK; 
      }
    }
    else 
    {
      if (xTimerChangePeriod(timer_id, ticks, 0) != pdPASS)
        result = osErrorOS;
      else
      {
        if (xTimerStart(timer_id, 0) != pdPASS)
          result = osErrorOS;
      }
    }
  }
#else 
  result = osErrorOS;
#endif
  return result;
}
void uart1_irq_handler(void)
{
    uint32_t ulReceived = 0;
    portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
    const unsigned portBASE_TYPE uxUARTNumber = 1UL;
    Transfer_Control_t *pxTransferStruct;

    if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
        pxTransferStruct = pxRxTransferControlStructs[uxUARTNumber];
        if (pxTransferStruct != NULL) {
            switch(diGET_TRANSFER_TYPE_FROM_CONTROL_STRUCT(pxTransferStruct)) {
            case ioctlUSE_CIRCULAR_BUFFER_RX:
            #if ioconfigUSE_UART_CIRCULAR_BUFFER_RX == 1
            {
                ioutilsRX_CHARS_INTO_CIRCULAR_BUFFER_FROM_ISR(
                        pxTransferStruct,   /* The structure that contains the reference to the circular buffer. */
                        (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET),    /* While loop condition. */
                        USART_ReceiveData(USART1),         /* Register holding the received character. */
                        ulReceived,
                        xHigherPriorityTaskWoken);
            }
            #endif /* ioconfigUSE_UART_CIRCULAR_BUFFER_RX */
                break;

            case ioctlUSE_CHARACTER_QUEUE_RX:
            #if ioconfigUSE_UART_RX_CHAR_QUEUE == 1
            {
                size_t i = 1;
                ioutilsRX_CHARS_INTO_QUEUE_FROM_ISR(
                        pxTransferStruct,
                        i--,
                        USART_ReceiveData(USART1),
                        ulReceived,
                        xHigherPriorityTaskWoken);
            }
            #endif /* ioconfigUSE_UART_RX_CHAR_QUEUE */
                break;

            default:
                break;
            }
        }
        USART_ClearITPendingBit(USART1, USART_IT_RXNE);
    }

    if (USART_GetITStatus(USART1, USART_IT_TXE) != RESET) {
        pxTransferStruct = pxTxTransferControlStructs[uxUARTNumber];
        if (pxTransferStruct != NULL) {
            switch (diGET_TRANSFER_TYPE_FROM_CONTROL_STRUCT(pxTransferStruct)) {
            case ioctlUSE_ZERO_COPY_TX:
            #if ioconfigUSE_UART_ZERO_COPY_TX == 1
            {
                iouitlsTX_SINGLE_CHAR_FROM_ZERO_COPY_BUFFER_FROM_ISR(
                        pxTransferStruct,
                        USART_SendData(USART1, ucChar),
                        xHigherPriorityTaskWoken);
            }
            #endif /* ioconfigUSE_UART_ZERO_COPY_TX */
                if (xHigherPriorityTaskWoken != pdTRUE)
                    USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
                break;

            case ioctlUSE_CHARACTER_QUEUE_TX:
            #if ioconfigUSE_UART_TX_CHAR_QUEUE == 1
            {
                size_t i = 1;
                ioutilsTX_CHARS_FROM_QUEUE_FROM_ISR(
                        pxTransferStruct,
                        i--,
                        USART_SendData(USART1, ucChar),
                        xHigherPriorityTaskWoken);
            }
            #endif /* ioconfigUSE_UART_TX_CHAR_QUEUE */
            if (xHigherPriorityTaskWoken != pdTRUE)
                USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
                break;

            default:
                /* This must be an error.  Force an assert. */
                configASSERT( xHigherPriorityTaskWoken );
                break;
            }
        }
        USART_ClearITPendingBit(USART1, USART_IT_TXE);
    }
    /* The ulReceived parameter is not used by the UART ISR. */
    (void) ulReceived;

    /* If xHigherPriorityTaskWoken is now equal to pdTRUE, then a context
    switch should be performed before the interrupt exists.  That ensures the
    unblocked (higher priority) task is returned to immediately. */
    portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
}
Exemple #22
0
/**
 * \brief GMAC Interrupt handler.
 *
 * \param p_gmac_dev   Pointer to GMAC device instance.
 */
void gmac_handler(gmac_device_t* p_gmac_dev, gmac_quelist_t queue_idx)
{
	Gmac *p_hw = p_gmac_dev->p_hw;

	gmac_tx_descriptor_t *p_tx_td;
	gmac_dev_tx_cb_t *p_tx_cb;
	volatile uint32_t ul_isr;
	volatile uint32_t ul_rsr;
	volatile uint32_t ul_tsr;
	uint32_t ul_rx_status_flag;
	uint32_t ul_tx_status_flag;
#ifdef FREERTOS_USED
	portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
#endif

	gmac_queue_t* p_gmac_queue = &p_gmac_dev->gmac_queue_list[queue_idx];

	if(queue_idx == GMAC_QUE_0) {
		ul_isr = gmac_get_interrupt_status(p_hw);
	} else {
		ul_isr = gmac_get_priority_interrupt_status(p_hw, queue_idx);
	}
	ul_rsr = gmac_get_rx_status(p_hw);
	ul_tsr = gmac_get_tx_status(p_hw);

	ul_isr &= ~(gmac_get_interrupt_mask(p_hw) | 0xF8030300);

	/* RX packet */
	if ((ul_isr & GMAC_ISR_RCOMP) || (ul_rsr & GMAC_RSR_REC)) {
		ul_rx_status_flag = GMAC_RSR_REC;

		/* Check OVR */
		if (ul_rsr & GMAC_RSR_RXOVR) {
			ul_rx_status_flag |= GMAC_RSR_RXOVR;
		}
		/* Check BNA */
		if (ul_rsr & GMAC_RSR_BNA) {
			ul_rx_status_flag |= GMAC_RSR_BNA;
		}
		/* Clear status */
		gmac_clear_rx_status(p_hw, ul_rx_status_flag);

		/* Invoke callbacks */
		if (p_gmac_queue->func_rx_cb) {
			p_gmac_queue->func_rx_cb(ul_rx_status_flag);
		}
	}

	/* TX packet */
	if ((ul_isr & GMAC_ISR_TCOMP) || (ul_tsr & GMAC_TSR_TXCOMP)) {
		ul_tx_status_flag = GMAC_TSR_TXCOMP;

		/* Check RLE */
		if (ul_tsr & GMAC_TSR_RLE) {
			/* Status RLE */
			ul_tx_status_flag = GMAC_TSR_RLE;
			p_tx_cb = &p_gmac_queue->func_tx_cb_list[p_gmac_queue->us_tx_tail];
			gmac_reset_tx_mem(p_gmac_dev, queue_idx);
			gmac_enable_transmit(p_hw, 1);
		}
		/* Check COL */
		if (ul_tsr & GMAC_TSR_COL) {
			ul_tx_status_flag |= GMAC_TSR_COL;
		}

		/* Clear status */
		gmac_clear_tx_status(p_hw, ul_tx_status_flag);

		if (!CIRC_EMPTY(p_gmac_queue->us_tx_head, p_gmac_queue->us_tx_tail)) {
			/* Check the buffers */
			do {
				p_tx_td = &p_gmac_queue->p_tx_dscr[p_gmac_queue->us_tx_tail];
				p_tx_cb = &p_gmac_queue->func_tx_cb_list[p_gmac_queue->us_tx_tail];
				/* Any error? Exit if buffer has not been sent yet */
				if ((p_tx_td->status.val & GMAC_TXD_USED) == 0) {
					break;
				}

				/* Notify upper layer that a packet has been sent */
				if (*p_tx_cb) {
					(*p_tx_cb) (ul_tx_status_flag);
				}

				circ_inc(&p_gmac_queue->us_tx_tail, p_gmac_queue->us_tx_list_size);
			} while (CIRC_CNT(p_gmac_queue->us_tx_head, p_gmac_queue->us_tx_tail,
							p_gmac_queue->us_tx_list_size));
		}

		/* If a wakeup has been scheduled, notify upper layer that it can
		   send other packets, and the sending will be successful. */
		if ((CIRC_SPACE(p_gmac_queue->us_tx_head, p_gmac_queue->us_tx_tail,
				p_gmac_queue->us_tx_list_size) >= p_gmac_queue->uc_wakeup_threshold)
				&& p_gmac_queue->func_wakeup_cb) {
			p_gmac_queue->func_wakeup_cb();
		}
	}

#ifdef FREERTOS_USED
		/* Notify TCP/IP task to start data processing. */
		/* LwIP works on top of GMAC driver, hence this semaphore locks */
		/* the complete IP stack. */
		xSemaphoreGiveFromISR(netif_notification_semaphore,
				&xHigherPriorityTaskWoken);
		portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
#endif
}
Exemple #23
0
void __attribute__ ((interrupt)) __cs3_isr_interrupt_121( void )
{
	MCF_PIT2_PCSR |= MCF_PIT_PCSR_PIF;
	portEND_SWITCHING_ISR( xSecondTimerHandler() );
}
Exemple #24
0
void UartDev::handleInterrupt()
{
    /**
     * Bit Masks of IIR register Bits 3:1 that contain interrupt reason.
     * Bits are shifted left because reasonForInterrupt contains Bits 3:0
     */
    const uint16_t transmitterEmpty = (1 << 1);
    const uint16_t dataAvailable    = (2 << 1);
    const uint16_t dataTimeout      = (6 << 1);

    long higherPriorityTaskWoken = 0;
    long switchRequired = 0;
    char c = 0;
    unsigned charsSent = 0;

    uint16_t reasonForInterrupt = (mpUARTRegBase->IIR & 0xE);
    {
        /**
         * If multiple sources of interrupt arise, let this interrupt exit, and re-enter
         * for the new source of interrupt.
         */
        switch (reasonForInterrupt)
        {
            case transmitterEmpty:
            {
                if(uxQueueMessagesWaitingFromISR(mTxQueue) > mTxQWatermark) {
                    mTxQWatermark = uxQueueMessagesWaitingFromISR(mTxQueue);
                }

                /**
                 * When THRE (Transmit Holding Register Empty) interrupt occurs,
                 * we can send as many bytes as the hardware FIFO supports (16)
                 */
                const unsigned char hwTxFifoSize = 16;
                for(charsSent=0;
                        charsSent < hwTxFifoSize && xQueueReceiveFromISR(mTxQueue, &c, &higherPriorityTaskWoken);
                        charsSent++)
                {
                    mpUARTRegBase->THR = c;
                    if(higherPriorityTaskWoken) {
                        switchRequired = 1;
                    }
                }
            }
            break;

            case dataAvailable:
            case dataTimeout:
            {
                mLastActivityTime = xTaskGetTickCountFromISR();
                /**
                 * While receive Hardware FIFO not empty, keep queuing the data.
                 * Even if xQueueSendFromISR() Fails (Queue is full), we still need to
                 * read RBR register otherwise interrupt will not clear
                 */
                while (0 != (mpUARTRegBase->LSR & (1 << 0)))
                {
                    c = mpUARTRegBase->RBR;
                    xQueueSendFromISR(mRxQueue, &c, &higherPriorityTaskWoken);
                    if(higherPriorityTaskWoken) {
                        switchRequired = 1;
                    }
                }

                if(uxQueueMessagesWaitingFromISR(mRxQueue) > mRxQWatermark) {
                    mRxQWatermark = uxQueueMessagesWaitingFromISR(mRxQueue);
                }
            }
            break;

            default:
                /* Read LSR register to clear Line Status Interrupt */
                reasonForInterrupt = mpUARTRegBase->LSR;
                break;
        }
    }

    portEND_SWITCHING_ISR(switchRequired);
}
Exemple #25
0
void adc_init(adc_t* adc)
{
  static int already_initialized = 0;

  gpio_clock_init(adc->GPIOx);

  GPIO_InitTypeDef GPIO_InitStructure =
    {
      .GPIO_Pin = adc->GPIO_Pin_x,
      .GPIO_Speed = GPIO_Speed_2MHz,
      .GPIO_Mode = GPIO_Mode_IN_FLOATING,
    };

  GPIO_Init(adc->GPIOx, &GPIO_InitStructure);

  // avoid configuring ADC2 again:
  if (already_initialized)
    return;

  already_initialized = 1;

  adc_clock_init(ADC2);
  xADCMutex = xSemaphoreCreateMutex();
  xADCQueue = xQueueCreate(10, sizeof(unsigned short));

  ADC_Cmd(ADC2, ENABLE);
  // Wait until it stabilizes
  wait_us(1000);
  ADC_InitTypeDef ADC_InitStructure;
  ADC_StructInit(&ADC_InitStructure);
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
  ADC_InitStructure.ADC_NbrOfChannel = 1;
  ADC_Init(ADC2, &ADC_InitStructure);
  ADC_StartCalibration(ADC2);
  while (ADC_GetCalibrationStatus(ADC2));
  ADC_Cmd(ADC2, DISABLE);
  ADC_ITConfig(ADC2, ADC_IT_EOC, ENABLE);

  // Enable interrupt UART:
  NVIC_InitTypeDef NVIC_InitStructure =
  {
    .NVIC_IRQChannel = ADC1_2_IRQn,
    .NVIC_IRQChannelPreemptionPriority = 7,
    .NVIC_IRQChannelSubPriority = 0,
    .NVIC_IRQChannelCmd = ENABLE,
  };
  NVIC_Init(&NVIC_InitStructure);
  ADC_Cmd(ADC2, ENABLE);
}

void ADC1_2_IRQHandler(void)
{
  signed portBASE_TYPE xHigherPriorityTaskWoken;
  unsigned short in_buffer = ADC2->DR & 0xfff;
  xQueueSendToBackFromISR(xADCQueue, &in_buffer,
                          &xHigherPriorityTaskWoken);
  portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
}

unsigned short adc_read(adc_t* adc)
{
  unsigned short in_buffer;
  xSemaphoreTake(xADCMutex, portMAX_DELAY);
  // we use the same ADC for all peripherals
  ADC_RegularChannelConfig(ADC2, adc->ADC_Channel, 1,
                           ADC_SampleTime_239Cycles5);
  ADC_Cmd(ADC2, ENABLE);
  xQueueReceive(xADCQueue, &in_buffer, portMAX_DELAY);
  xSemaphoreGive(xADCMutex);
  return in_buffer;
}
Exemple #26
0
void sharps_init(sharps_t* sharps)
{
  ADC_TypeDef* ADCx = ADC1;
  sharp_t* ADCs = sharps->ADCs;
  DMA_Channel_TypeDef* DMA = DMA1_Channel1;

  dma_clock_init(DMA1);
  adc_clock_init(sharps->ADCx);

  GPIO_InitTypeDef GPIO_InitStructure =
    {
      .GPIO_Pin = 0,
      .GPIO_Speed = GPIO_Mode_IN_FLOATING,
      .GPIO_Mode = GPIO_Speed_2MHz,
    };

  for (int i = 0; i < sharps->number; i++)
  {
    gpio_clock_init(ADCs[i].GPIOx);
    GPIO_InitStructure.GPIO_Pin = ADCs[i].GPIO_Pin_x;
    GPIO_Init(ADCs[i].GPIOx, &GPIO_InitStructure);
  }

  ADC_DeInit(ADCx);
  ADC_Cmd(ADCx, ENABLE);
  // Wait until it stabilizes
  wait_us(1000);
  ADC_InitTypeDef ADC_InitStructure;
  ADC_StructInit(&ADC_InitStructure);
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
  ADC_InitStructure.ADC_NbrOfChannel = sharps->number;
  ADC_Init(ADCx, &ADC_InitStructure);
  ADC_ResetCalibration(ADCx);
  while (ADC_GetResetCalibrationStatus(ADCx));
  ADC_StartCalibration(ADCx);
  while (ADC_GetCalibrationStatus(ADCx));

  for (int i = 0; i < sharps->number; i++)
    ADC_RegularChannelConfig(ADCx, ADCs[i].ADC_Channel,
                             i + 1, ADC_SampleTime_239Cycles5);

  ADC_Cmd(ADCx, ENABLE);

  DMA_DeInit(DMA);
  DMA_InitTypeDef DMA_InitStructure;
  DMA_StructInit(&DMA_InitStructure);
  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)ADCx->DR;
  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)ADC_DMA_Buffer;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = sharps->number;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; // 16 ?
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA, &DMA_InitStructure);

  DMA_ITConfig(DMA, DMA_IT_TC, ENABLE);

  NVIC_InitTypeDef NVIC_InitStructure =
    {
      .NVIC_IRQChannel = DMA1_Channel1_IRQn,
      .NVIC_IRQChannelPreemptionPriority = 3, // ?
      .NVIC_IRQChannelSubPriority = 3,        // ?
      .NVIC_IRQChannelCmd = ENABLE,
    };

  NVIC_Init(&NVIC_InitStructure);

  DMA_Cmd(DMA, ENABLE);

  vSemaphoreCreateBinary(xSharpsSemaphore);
}

void DMA1_Channel1_IRQHandler()
{
  portBASE_TYPE resched = pdFALSE;
  if (DMA_GetFlagStatus(DMA1_FLAG_TC1))
  {
    xSemaphoreGiveFromISR(xSharpsSemaphore, &resched);
    DMA_ClearITPendingBit(DMA1_IT_TC1);
  }
  portEND_SWITCHING_ISR(resched);
}

void sharps_smooth_task(void* pvParameters)
{
  static int i = 0;
  static uint32_t average[SHARPS_MAX_NUMBER] = {0};

  for (;;)
  {
    xSemaphoreTake(xSharpsSemaphore, portMAX_DELAY);

    for (int j = 0; j < SHARPS_MAX_NUMBER; j++)
      average[j] += ADC_DMA_Buffer[j];

    i++;

    if (i == AVERAGE_NUMBER)
    {
      for (int j = 0; j < SHARPS_MAX_NUMBER; j++)
      {
        ADC_Smoothed[j] = average[j] / AVERAGE_NUMBER;
        average[j] = 0;
      }
      i = 0;
    }
  }
}

uint16_t sharps_get_value(int i)
{
  return ADC_Smoothed[i];
}
Exemple #27
0
void vT2InterruptHandler( void )
{
    TimerIntClear( TIMER2_BASE, TIMER_TIMA_TIMEOUT );	
	portEND_SWITCHING_ISR( xFirstTimerHandler() );
}
Exemple #28
0
/*------------------------------------------------------------------------------
 * MSS I2C interrupt service routine.
 *------------------------------------------------------------------------------
 * Parameters:
 *
 * 	mss_i2c_instance_t * this_i2c:
 * 		Pointer to the mss_i2c_instance_t data structure holding all data related to
 * 		the	MSS I2C instance that generated the interrupt.
 */
static void mss_i2c_isr
(
    mss_i2c_instance_t * this_i2c
)
{
    volatile uint8_t status;
    uint8_t data;
    uint8_t hold_bus;
    uint8_t clear_irq = 1;
    long lHigherPriorityTaskWoken = pdFALSE;
    configASSERT( ( this_i2c->xI2CCompleteSemaphore ) );

    ASSERT( (this_i2c == &g_mss_i2c0) || (this_i2c == &g_mss_i2c1) );

    status = this_i2c->hw_reg->STATUS;

    switch( status ) {
        /************** MASTER TRANSMITTER / RECEIVER *******************/

        case ST_START: /* start has been xmt'd */
        case ST_RESTART: /* repeated start has been xmt'd */
            this_i2c->hw_reg_bit->CTRL_STA = 0x0;
            this_i2c->hw_reg->DATA = this_i2c->target_addr;
            this_i2c->hw_reg_bit->DATA_DIR = this_i2c->dir;

            this_i2c->tx_idx = 0;
            this_i2c->rx_idx = 0;
            break;

        case ST_LOST_ARB:
            /* Set start bit.  Let's keep trying!  Don't give up! */
            this_i2c->hw_reg_bit->CTRL_STA = 0x01;
            break;

        /******************* MASTER TRANSMITTER *************************/
        case ST_SLAW_ACK:
            /* call address has been xmt'd with ACK, time to send data byte and increment index. */
            if ( this_i2c->tx_idx < this_i2c->tx_size ) {
                /* load data byte */
                this_i2c->hw_reg->DATA = this_i2c->tx_buffer[this_i2c->tx_idx++];
            } else {
                NVIC_DisableIRQ( this_i2c->irqn );
            }
            break;

        case ST_SLAW_NACK:
#if 0
            /* SLA+W has been transmitted; not ACK has been received - let's stop. */
            this_i2c->hw_reg_bit->CTRL_STO = 0x01;
            this_i2c->status = MSS_I2C_FAILED;
#endif
            /* call address has been xmt'd with ACK, time to send data byte and increment index. */
            if ( this_i2c->tx_idx < this_i2c->tx_size ) {
                /* load data byte */
                this_i2c->hw_reg->DATA = this_i2c->tx_buffer[this_i2c->tx_idx++];
            } else {
                NVIC_DisableIRQ( this_i2c->irqn );
            }
            break;

        case ST_TX_DATA_ACK:
            /* data byte has been xmt'd with ACK, time to send stop bit or repeated start. */
            if (this_i2c->tx_idx < this_i2c->tx_size) {
                this_i2c->hw_reg->DATA = this_i2c->tx_buffer[this_i2c->tx_idx++];
            } else if ( this_i2c->transaction == MASTER_RANDOM_READ_TRANSACTION ) {
                /* We are finished sending the address offset part of a random read transaction.
                 * It is is time to send a restart in order to change direction. */
                this_i2c->dir = READ_DIR;
                this_i2c->hw_reg_bit->CTRL_STA = 0x01;
            } else { /* done sending. let's stop */
                hold_bus = this_i2c->options & MSS_I2C_HOLD_BUS;
                if ( hold_bus == 0 ) {
                    this_i2c->hw_reg_bit->CTRL_STO = 0x01; /*xmt stop condition */
                } else {
                    NVIC_DisableIRQ( this_i2c->irqn );
                    clear_irq = 0;
                }
                this_i2c->status = MSS_I2C_SUCCESS;
                xSemaphoreGiveFromISR( this_i2c->xI2CCompleteSemaphore, &lHigherPriorityTaskWoken );
            }
            break;

        case ST_TX_DATA_NACK:
#if 0
            /* data byte SENT, ACK to be received
            * In fact, this means we've received a NACK (This may not be
            * obvious, but if we've rec'd an ACK then we would be in state
            * 0x28!) hence, let's send a stop bit
            */
            this_i2c->hw_reg_bit->CTRL_STO = 0x01;
            this_i2c->status = MSS_I2C_FAILED;
#endif
            /* data byte has been xmt'd with ACK, time to send stop bit or repeated start. */
            if (this_i2c->tx_idx < this_i2c->tx_size) {
                this_i2c->hw_reg->DATA = this_i2c->tx_buffer[this_i2c->tx_idx++];
            } else if ( this_i2c->transaction == MASTER_RANDOM_READ_TRANSACTION ) {
                /* We are finished sending the address offset part of a random read transaction.
                 * It is is time to send a restart in order to change direction. */
                this_i2c->dir = READ_DIR;
                this_i2c->hw_reg_bit->CTRL_STA = 0x01;
            } else { /* done sending. let's stop */
                hold_bus = this_i2c->options & MSS_I2C_HOLD_BUS;
                if ( hold_bus == 0 ) {
                    this_i2c->hw_reg_bit->CTRL_STO = 0x01; /*xmt stop condition */
                } else {
                    NVIC_DisableIRQ( this_i2c->irqn );
                    clear_irq = 0;
                }
                this_i2c->status = MSS_I2C_SUCCESS;
                xSemaphoreGiveFromISR( this_i2c->xI2CCompleteSemaphore, &lHigherPriorityTaskWoken );
            }
            break;

        /********************* MASTER (or slave?) RECEIVER *************************/

        /* STATUS codes 08H, 10H, 38H are all covered in MTX mode */
        case ST_SLAR_ACK: /* SLA+R tx'ed. */
            /* Let's make sure we ACK the first data byte received (set AA bit in CTRL) unless
             * the next byte is the last byte of the read transaction.
             */
            if( this_i2c->rx_size > 1 ) {
                this_i2c->hw_reg_bit->CTRL_AA = 0x01;
            } else {
                this_i2c->hw_reg_bit->CTRL_AA = 0x00;
            }
            break;

        case ST_SLAR_NACK: /* SLA+R tx'ed; let's release the bus (send a stop condition) */
            this_i2c->hw_reg_bit->CTRL_STO = 0x01;
            this_i2c->status = MSS_I2C_FAILED;
            xSemaphoreGiveFromISR( this_i2c->xI2CCompleteSemaphore, &lHigherPriorityTaskWoken );
            break;

        case ST_RX_DATA_ACK: /* Data byte received, ACK returned */
            /* First, get the data */
            this_i2c->rx_buffer[this_i2c->rx_idx++] = this_i2c->hw_reg->DATA;

            if( this_i2c->rx_idx >= this_i2c->rx_size - 1) {
                /* If we're at the second last byte, let's set AA to 0 so
                 * we return a NACK at the last byte. */
                this_i2c->hw_reg_bit->CTRL_AA = 0x00;
            }
            break;

        case ST_RX_DATA_NACK: /* Data byte received, NACK returned */
            /* Get the data, then send a stop condition */
            this_i2c->rx_buffer[this_i2c->rx_idx++] = this_i2c->hw_reg->DATA;

            hold_bus = this_i2c->options &  MSS_I2C_HOLD_BUS;
            if ( hold_bus == 0 ) {
                this_i2c->hw_reg_bit->CTRL_STO = 0x01;  /*xmt stop condition */
            } else {
                NVIC_DisableIRQ( this_i2c->irqn );
                clear_irq = 0;
            }

            this_i2c->status = MSS_I2C_SUCCESS;
//			xSemaphoreGiveFromISR( this_i2c->xI2CCompleteSemaphore, &lHigherPriorityTaskWoken );
            break;

        /******************** SLAVE RECEIVER **************************/
        case ST_GCA_NACK: /* NACK after, GCA addressing */
        case ST_SLA_NACK: /* Get Data, but also re-enable AA (assert ack) bit for future transmissions */
            if ( this_i2c->rx_buffer != 0 ) {
                this_i2c->rx_buffer[this_i2c->rx_idx] = this_i2c->hw_reg->DATA;
            }
            this_i2c->hw_reg_bit->CTRL_AA = 0x01;
            break;

        case ST_SLAVE_SLAW: /* SLA+W received, ACK returned */
            this_i2c->transaction = WRITE_SLAVE_TRANSACTION;
            this_i2c->rx_idx = 0;
            this_i2c->random_read_addr = 0;
#ifndef INCLUDE_SLA_IN_RX_PAYLOAD
            /* Only break from this case if the slave address must NOT be included at the
             * beginning of the received write data. */
            break;
#endif
        case ST_GCA_ACK: /* DATA received; ACK sent after GCA */
        case ST_RDATA: /* DATA received; must clear DATA register */
            if (this_i2c->rx_idx >= this_i2c->rx_size - 2) {
                this_i2c->hw_reg_bit->CTRL_AA = 0x00;   /* send a NACK when done (next reception) */
            }
            data = this_i2c->hw_reg->DATA;
            this_i2c->rx_buffer[this_i2c->rx_idx++] = data;
            this_i2c->random_read_addr = (this_i2c->random_read_addr << 8) + data;

            break;

        case ST_RSTOP:
            /* STOP or repeated START occured. */
            /* We cannot be sure if the transaction has actually completed as
             * this hardware state reports that either a STOP or repeated START
             * condition has occured. We assume that this is a repeated START
             * if the transaction was a write from the master to this point.*/
            if ( this_i2c->transaction == WRITE_SLAVE_TRANSACTION ) {
                if ( this_i2c->rx_idx == this_i2c->slave_mem_offset_length ) {
                    this_i2c->transaction = RANDOM_READ_SLAVE_TRANSACTION;
                    this_i2c->tx_idx = this_i2c->random_read_addr;
                } else {
                    /* Call the slave's write transaction handler if it exists. */
                    if ( this_i2c->slave_write_handler != 0 ) {
                        mss_i2c_slave_handler_ret_t h_ret;
                        h_ret = this_i2c->slave_write_handler( this_i2c->rx_buffer, (uint16_t)this_i2c->rx_idx );
                        if ( MSS_I2C_REENABLE_SLAVE_RX == h_ret ) {
                            this_i2c->hw_reg_bit->CTRL_AA = 0x01;
                        } else {
                            this_i2c->hw_reg_bit->CTRL_AA = 0x00;
                        }
                    }
                }
            }
            /* Mark any previous master write transaction as complete. */
            this_i2c->status = MSS_I2C_SUCCESS;
//			xSemaphoreGiveFromISR( this_i2c->xI2CCompleteSemaphore, &lHigherPriorityTaskWoken );
            break;

        case ST_SLV_RST: /* SMBUS ONLY: timeout state. must clear interrupt */
        case ST_SLV_LA: /* Arbitr. lost (SLA rec'd) */
        case ST_GCA: /* General call address received, ACK returned */
        case ST_GCA_LA: /* Arbitr. lost (GCA rec'd) */
            /* do nothing */
            break;

        /****************** SLAVE TRANSMITTER **************************/
        case ST_SLAVE_SLAR_ACK: /* SLA+R received, ACK returned */
        case ST_SLARW_LA: /* Arbitration lost, and: */
        case ST_RACK: /* Data tx'ed, ACK received */
            if ( status == ST_SLAVE_SLAR_ACK ) {
                this_i2c->transaction = READ_SLAVE_TRANSACTION;
                this_i2c->random_read_addr = 0;
            }
            /* Load the data, and determine if it is the last one */
            this_i2c->hw_reg->DATA = this_i2c->tx_buffer[this_i2c->tx_idx++];
            if (this_i2c->tx_idx >= this_i2c->tx_size - 1) { /* last byte? */
                this_i2c->hw_reg_bit->CTRL_AA = 0x00;
                /* Next read transaction will result in slave's transmit buffer
                 * being sent from the first byte. */
                this_i2c->tx_idx = 0;
            }
            break;

        case ST_SLAVE_RNACK:	/* Data byte has been transmitted; not-ACK has been received. */
            /* We assume that the transaction will be stopped by the master.
             * Reset tx_idx so that a subsequent read will result in the slave's
             * transmit buffer being sent from the first byte. */
            this_i2c->tx_idx = 0;
            break;

        case ST_FINAL: /* Last Data byte tx'ed, ACK recieved */
        default:
            /* do nothing */
            break;
    }

    if ( clear_irq ) {
        /* clear interrupt. */
        this_i2c->hw_reg_bit->CTRL_SI = 0x00;
    }

    /* Read the status register to ensure the last I2C registers write took place
     * in a system built around a bus making use of posted writes. */
    status = this_i2c->hw_reg->STATUS;

    portEND_SWITCHING_ISR( lHigherPriorityTaskWoken );
}
Exemple #29
0
static void enable_usart1(void)
{
	/* RCC Initialization */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

	//RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1, ENABLE);

	/* GPIO Initialization */
	GPIO_InitTypeDef GPIO_InitStruct = {
		.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10,
		.GPIO_Mode = GPIO_Mode_AF,
		.GPIO_OType = GPIO_OType_PP,
		.GPIO_PuPd = GPIO_PuPd_UP,
		.GPIO_Speed = GPIO_Speed_50MHz
	};

	GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
	GPIO_Init(GPIOA, &GPIO_InitStruct);

	/* USART3 Initialization */
	USART_InitTypeDef USART_InitStruct = {
		.USART_BaudRate = 57600,
		.USART_WordLength = USART_WordLength_8b,
		.USART_StopBits = USART_StopBits_1,
		.USART_Parity = USART_Parity_No,
		.USART_HardwareFlowControl = USART_HardwareFlowControl_None,
		.USART_Mode = USART_Mode_Rx | USART_Mode_Tx
	};

	USART_Init(USART1, &USART_InitStruct);
	USART_Cmd(USART1, ENABLE);
}

static void enable_usart2(void)
{
	/* RCC Initialization */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1, ENABLE);

	/* GPIO Initialization */
	GPIO_InitTypeDef GPIO_InitStruct = {
		.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6,
		.GPIO_Mode = GPIO_Mode_AF,
		.GPIO_OType = GPIO_OType_PP,
		.GPIO_PuPd = GPIO_PuPd_UP,
		.GPIO_Speed = GPIO_Speed_50MHz
	};

	GPIO_PinAFConfig(GPIOD, GPIO_PinSource5, GPIO_AF_USART2);
	GPIO_PinAFConfig(GPIOD, GPIO_PinSource6, GPIO_AF_USART2);
	GPIO_Init(GPIOD, &GPIO_InitStruct);

	/* USART2 Initialization */
	USART_InitTypeDef USART_InitStruct = {
		.USART_BaudRate = 9600,
		.USART_WordLength = USART_WordLength_8b,
		.USART_StopBits = USART_StopBits_1,
		.USART_Parity = USART_Parity_No,
		.USART_HardwareFlowControl = USART_HardwareFlowControl_None,
		.USART_Mode = USART_Mode_Rx | USART_Mode_Tx
	};

	USART_Init(USART2, &USART_InitStruct);
	USART_Cmd(USART2, ENABLE);

	/* DMA Initialization */
	DMA_DeInit(DMA1_Stream6);
	while (DMA_GetCmdStatus(DMA1_Stream6) != DISABLE);
}

static void enable_usart3(void)
{
	/* RCC Initialization */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

	/* GPIO Initialization */
	GPIO_InitTypeDef GPIO_InitStruct = {
		.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9,
		.GPIO_Mode = GPIO_Mode_AF,
		.GPIO_OType = GPIO_OType_PP,
		.GPIO_PuPd = GPIO_PuPd_UP,
		.GPIO_Speed = GPIO_Speed_50MHz
	};

	GPIO_PinAFConfig(GPIOD, GPIO_PinSource8, GPIO_AF_USART3);
	GPIO_PinAFConfig(GPIOD, GPIO_PinSource9, GPIO_AF_USART3);
	GPIO_Init(GPIOD, &GPIO_InitStruct);

	/* USART3 Initialization */
	USART_InitTypeDef USART_InitStruct = {
		.USART_BaudRate = 57600,
		.USART_WordLength = USART_WordLength_8b,
		.USART_StopBits = USART_StopBits_1,
		.USART_Parity = USART_Parity_No,
		.USART_HardwareFlowControl = USART_HardwareFlowControl_None,
		.USART_Mode = USART_Mode_Rx | USART_Mode_Tx
	};

	USART_Init(USART3, &USART_InitStruct);
	USART_Cmd(USART3, ENABLE);
	USART_ClearFlag(USART3, USART_FLAG_TC);

	USART_ITConfig(USART3, USART_IT_TXE, DISABLE);
	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);

	/* NVIC Initialization */
	NVIC_InitTypeDef NVIC_InitStruct = {
		.NVIC_IRQChannel = USART3_IRQn,
		.NVIC_IRQChannelPreemptionPriority = configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1,
		.NVIC_IRQChannelSubPriority = 0,
		.NVIC_IRQChannelCmd = ENABLE
	};
	NVIC_Init(&NVIC_InitStruct);
}

static void enable_usart4(void)
{
	/* RCC Initialization */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4, ENABLE);

	/* GPIO Initialization */
	GPIO_InitTypeDef GPIO_InitStruct = {
		.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11,
		.GPIO_Mode = GPIO_Mode_AF,
		.GPIO_OType = GPIO_OType_PP,
		.GPIO_PuPd = GPIO_PuPd_UP,
		.GPIO_Speed = GPIO_Speed_50MHz
	};

	GPIO_PinAFConfig(GPIOC, GPIO_PinSource10, GPIO_AF_UART4);
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource11, GPIO_AF_UART4);
	GPIO_Init(GPIOC, &GPIO_InitStruct);

	/* USART4 Initialization */
	USART_InitTypeDef USART_InitStruct = {
		.USART_BaudRate = 57600,
		.USART_WordLength = USART_WordLength_8b,
		.USART_StopBits = USART_StopBits_1,
		.USART_Parity = USART_Parity_No,
		.USART_HardwareFlowControl = USART_HardwareFlowControl_None,
		.USART_Mode = USART_Mode_Rx | USART_Mode_Tx
	};

	USART_Init(UART4, &USART_InitStruct);
	USART_Cmd(UART4, ENABLE);
}

static void enable_usart5(void)
{
	/* RCC Initialization */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5, ENABLE);

	/* GPIO Initialization */
	GPIO_InitTypeDef GPIO_InitStruct = {
		.GPIO_Pin = GPIO_Pin_2,
		.GPIO_Mode = GPIO_Mode_AF,
		.GPIO_OType = GPIO_OType_PP,
		.GPIO_PuPd = GPIO_PuPd_UP,
		.GPIO_Speed = GPIO_Speed_50MHz
	};

	GPIO_Init(GPIOD, &GPIO_InitStruct);

	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_12;

	GPIO_Init(GPIOC, &GPIO_InitStruct);

	GPIO_PinAFConfig(GPIOD, GPIO_PinSource2, GPIO_AF_UART5);
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource12, GPIO_AF_UART5);

	/* USART5 Initialization */
	USART_InitTypeDef USART_InitStruct = {
		.USART_BaudRate = 57600,
		.USART_WordLength = USART_WordLength_8b,
		.USART_StopBits = USART_StopBits_1,
		.USART_Parity = USART_Parity_No,
		.USART_HardwareFlowControl = USART_HardwareFlowControl_None,
		.USART_Mode = USART_Mode_Rx | USART_Mode_Tx
	};

	USART_Init(UART5, &USART_InitStruct);
	USART_Cmd(UART5, ENABLE);
}

static void enable_usart8(void)
{
	/* RCC Initialization */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART8, ENABLE);

	/* GPIO Initialization */
	GPIO_InitTypeDef GPIO_InitStruct = {
		.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1,
		.GPIO_Mode = GPIO_Mode_AF,
		.GPIO_OType = GPIO_OType_PP,
		.GPIO_PuPd = GPIO_PuPd_UP,
		.GPIO_Speed = GPIO_Speed_50MHz
	};

	GPIO_PinAFConfig(GPIOE, GPIO_PinSource0, GPIO_AF_UART8);
	GPIO_PinAFConfig(GPIOE, GPIO_PinSource1, GPIO_AF_UART8);
	GPIO_Init(GPIOE, &GPIO_InitStruct);

	/* USART8 Initialization */
	USART_InitTypeDef USART_InitStruct = {
		.USART_BaudRate = 57600,
		.USART_WordLength = USART_WordLength_8b,
		.USART_StopBits = USART_StopBits_1,
		.USART_Parity = USART_Parity_No,
		.USART_HardwareFlowControl = USART_HardwareFlowControl_None,
		.USART_Mode = USART_Mode_Rx | USART_Mode_Tx
	};

	USART_Init(UART8, &USART_InitStruct);
	USART_Cmd(UART8, ENABLE);
	
	/* DMA Initialization */
	DMA_DeInit(DMA1_Stream6);

	while (DMA_GetCmdStatus(DMA1_Stream6) != DISABLE);
}

void usart_init()
{
	enable_usart1();
	enable_usart2();
	enable_usart3();
	enable_usart4();
	enable_usart5();
	enable_usart8();
}

void usart2_dma_init()
{

	uint8_t dummy = 0;
	DMA_InitTypeDef DMA_InitStructure = {
	/* Configure DMA Initialization Structure */
		.DMA_BufferSize = (uint32_t)1,
		.DMA_FIFOMode = DMA_FIFOMode_Disable,
		.DMA_FIFOThreshold = DMA_FIFOThreshold_Full,
		.DMA_MemoryBurst = DMA_MemoryBurst_Single,
		.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte,
		.DMA_MemoryInc = DMA_MemoryInc_Enable,
		.DMA_Mode = DMA_Mode_Normal,
		.DMA_PeripheralBaseAddr = (uint32_t)(&(USART2->DR)),
		.DMA_PeripheralBurst = DMA_PeripheralBurst_Single,
		.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte,
		.DMA_PeripheralInc = DMA_PeripheralInc_Disable,
		.DMA_Priority = DMA_Priority_Medium,
		/* Configure TX DMA */
		.DMA_Channel = DMA_Channel_4,
		.DMA_DIR = DMA_DIR_MemoryToPeripheral,
		.DMA_Memory0BaseAddr = (uint32_t)&dummy
	};

	DMA_Init(DMA1_Stream6, &DMA_InitStructure);
	DMA_Cmd(DMA1_Stream6, ENABLE);

	USART_DMACmd(USART2, USART_DMAReq_Tx, ENABLE);

}
void usart2_dma_send(uint8_t *s)
{
	while (DMA_GetFlagStatus(DMA1_Stream6, DMA_FLAG_TCIF6) == RESET);

	DMA_ClearFlag(DMA1_Stream6, DMA_FLAG_TCIF6);

	DMA_InitTypeDef  DMA_InitStructure = {
		/* Configure DMA Initialization Structure */
		.DMA_BufferSize = (uint32_t)strlen((const char *) s),
		.DMA_FIFOMode = DMA_FIFOMode_Disable,
		.DMA_FIFOThreshold = DMA_FIFOThreshold_Full,
		.DMA_MemoryBurst = DMA_MemoryBurst_Single,
		.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte,
		.DMA_MemoryInc = DMA_MemoryInc_Enable,
		.DMA_Mode = DMA_Mode_Normal,
		.DMA_PeripheralBaseAddr = (uint32_t)(&(USART2->DR)),
		.DMA_PeripheralBurst = DMA_PeripheralBurst_Single,
		.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte,
		.DMA_PeripheralInc = DMA_PeripheralInc_Disable,
		.DMA_Priority = DMA_Priority_Medium,
		/* Configure TX DMA */
		.DMA_Channel = DMA_Channel_4,
		.DMA_DIR = DMA_DIR_MemoryToPeripheral,
		.DMA_Memory0BaseAddr = (uint32_t)s
	};
	DMA_Init(DMA1_Stream6, &DMA_InitStructure);

	DMA_Cmd(DMA1_Stream6, ENABLE);

	USART_DMACmd(USART2, USART_DMAReq_Tx, ENABLE);


}

int _write(int fd, char *ptr, int len)
{
	/* Write "len" of char from "ptr" to file id "fd"
	 * Return number of char written.
	 * Need implementing with UART here. */
	int i = 0;
	fd=fd;
	for (i = 0; i < len ; i++) {
		USART_SendData(PRINTF_USART, (uint8_t) *ptr);

		/* Loop until USART2 DR register is empty */
		while (USART_GetFlagStatus(PRINTF_USART, USART_FLAG_TXE) == RESET);

		ptr++;
	}

	return len;
}


xSemaphoreHandle serial_tx_wait_sem = NULL;
xQueueHandle serial_rx_queue = NULL;
xQueueHandle gps_serial_queue = NULL;
void USART3_IRQHandler(void)
{
	long lHigherPriorityTaskWoken = pdFALSE;

	serial_msg rx_msg;

	if (USART_GetITStatus(USART3, USART_IT_TXE) != RESET) {
		xSemaphoreGiveFromISR(serial_tx_wait_sem, &lHigherPriorityTaskWoken);

		USART_ITConfig(USART3, USART_IT_TXE, DISABLE);

	}
	
	if (USART_GetITStatus(USART3, USART_IT_RXNE) != RESET) {
		rx_msg.ch = USART_ReceiveData(USART3);

		if (!xQueueSendToBackFromISR(serial_rx_queue, &rx_msg, &lHigherPriorityTaskWoken))
			portEND_SWITCHING_ISR(lHigherPriorityTaskWoken);

	}

	portEND_SWITCHING_ISR(lHigherPriorityTaskWoken);
}

char usart3_read(void)
{
	serial_msg msg;

	while (!xQueueReceive(serial_rx_queue, &msg, portMAX_DELAY));

	return msg.ch;
}

void usart3_send(char str)
{
	while (!xSemaphoreTake(serial_tx_wait_sem, portMAX_DELAY));

	USART_SendData(USART3, (uint16_t)str);
	USART_ITConfig(USART3, USART_IT_TXE, ENABLE);
}

void uart8_puts(uint8_t *ptr)
{
	while(*ptr!='\0'){

		USART_SendData(PRINTF_USART, (uint8_t) *ptr);

		/* Loop until USART8 DR register is empty */
		while (USART_GetFlagStatus(PRINTF_USART, USART_FLAG_TXE) == RESET);
		ptr++;
	}

}
Exemple #30
0
//Vsync interrupt service routine
void EXTI1_IRQHandler()
{
	portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
	
	static uint16_t Vsync_update = 0;
	
//	vPortEnterCritical();
//	taskENTER_CRITICAL();
	
	if(EXTI_GetITStatus(EXTI_Line1) != RESET) 
	{
		EXTI_ClearITPendingBit(EXTI_Line1);
		
		// Stop the line counter
		TIM_Cmd(LINE_COUNTER_TIMER, DISABLE);

		// Update the number of video lines
		num_video_lines = LINE_COUNTER_TIMER->CNT;

		// check video type
		if (num_video_lines > VIDEO_TYPE_PAL_ROWS) 
		{
			video_type_tmp = VIDEO_TYPE_PAL;
		}

		// if video type has changed set new active values
		if (video_type_act != video_type_tmp) 
		{
			video_type_act = video_type_tmp;
			if (video_type_act == VIDEO_TYPE_NTSC) 
			{
				pios_video_type_boundary_act = &pios_video_type_boundary_ntsc;
				pios_video_type_cfg_act = &pios_video_type_cfg_ntsc;
				//set_bw_levels(black_ntsc, white_ntsc);
			} 
			else 
			{
				pios_video_type_boundary_act = &pios_video_type_boundary_pal;
				pios_video_type_cfg_act = &pios_video_type_cfg_pal;
				//set_bw_levels(black_pal, white_pal);
			}
			PIXEL_TIMER->CCR1 = pios_video_type_cfg_act->dc;
			PIXEL_TIMER->ARR  = pios_video_type_cfg_act->period;
			HSYNC_CAPTURE_TIMER->ARR = pios_video_type_cfg_act->dc * (pios_video_type_cfg_act->graphics_column_start + x_offset);
		}
		if (x_offset != x_offset_new)
		{
			x_offset = x_offset_new;
			HSYNC_CAPTURE_TIMER->ARR = pios_video_type_cfg_act->dc * (pios_video_type_cfg_act->graphics_column_start + x_offset);
		}

		video_type_tmp = VIDEO_TYPE_NTSC;


		// Every VSYNC_REDRAW_CNT field: swap buffers and trigger redraw
		if (++Vsync_update >= VSYNC_REDRAW_CNT) {
			if((LINE_COUNTER_TIMER->DIER & TIM_IT_Update) == (uint16_t)RESET)
			{
				TIM_ITConfig(LINE_COUNTER_TIMER, TIM_IT_Update, ENABLE);
			}
			Vsync_update = 0;
			swap_buffers();
			xSemaphoreGiveFromISR(onScreenDisplaySemaphore, &xHigherPriorityTaskWoken);
		}
		
		// Get ready for the first line
		active_line = 0;

		// Set the number of lines to wait until we start clocking out pixels
		LINE_COUNTER_TIMER->CNT = 0xffff - (pios_video_type_cfg_act->graphics_line_start + y_offset);
		TIM_Cmd(LINE_COUNTER_TIMER, ENABLE);
		

	}
	
	portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
//	vPortExitCritical();
//	taskEXIT_CRITICAL();
}