Upload original 计算机组成原理课程实践 学分×2 陈媛媛 course files (part 22)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/demo_v8.pdsprj
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/flash.ld+154-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/croutine.c+386-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/FreeRTOS.h+621-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/StackMacros.h+180-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/croutine.h+758-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/list.h+379-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/mpu_wrappers.h+153-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/portable.h+402-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/projdefs.h+89-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/queue.h+1685-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/semphr.h+840-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/task.h+1520-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/timers.h+960-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/list.c+204-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_1.c+170-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_2.c+299-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_3.c+131-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_4.c+391-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/portable/debug.h+32-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/portable/port.c+737-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/portable/portmacro.h+187-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/queue.c+2105-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/tasks.c
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/timers.c+707-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/make.bat+62-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/include/FreeRTOSConfig.h+96-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/include/serial.h+136-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/main.c+234-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/serial.c+317-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/DLib_Config_Normal.h+13-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/adc.c+979-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/adc.h+149-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/can.c+2203-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/can.h+459-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/comp.c+439-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/comp.h+133-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/cpu.c+189-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/cpu.h+60-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/debug.h+56-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/driverlib.ewp+867-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/epi.c+1039-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/epi.h+229-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/ethernet.c+1280-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/ethernet.h+172-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/flash.c+915-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/flash.h+89-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/gpio.c+1512-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/gpio.h+768-3
- Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/hibernate.c+965-3
123version https://git-lfs.github.com/spec/v1oid sha256:6d5fcb39989f0a2ba731239ee0f0e82fbaf66f9f0f4c4eff89a087140e5df9dbsize 4679123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154/*** \file** \brief Flash Linker script for SAM.** Copyright (c) 2011-2012 Atmel Corporation. All rights reserved.** \asf_license_start** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,* this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright notice,* this list of conditions and the following disclaimer in the documentation* and/or other materials provided with the distribution.** 3. The name of Atmel may not be used to endorse or promote products derived* from this software without specific prior written permission.** 4. This software may only be redistributed and used in connection with an* Atmel microcontroller product.** THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE* POSSIBILITY OF SUCH DAMAGE.** \asf_license_stop**/OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm")OUTPUT_ARCH(arm)SEARCH_DIR(.)/* Memory Spaces Definitions */MEMORY{rom (rx) : ORIGIN = 0x00400000, LENGTH = 0x00040000 /* flash, 256K */ram (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00006000 /* sram, 24K */}/* The stack size used by the application. NOTE: you need to adjust */__stack_size__ = DEFINED(__stack_size__) ? __stack_size__ : 0x800;/* Section Definitions */SECTIONS{.text :{. = ALIGN(4);_sfixed = .;KEEP(*(.vectors .vectors.*))*(.text .text.* .gnu.linkonce.t.*)*(.glue_7t) *(.glue_7)*(.rodata .rodata* .gnu.linkonce.r.*)*(.ARM.extab* .gnu.linkonce.armextab.*)/* Support C constructors, and C destructors in both user codeand the C library. This also provides support for C++ code. */. = ALIGN(4);KEEP(*(.init)). = ALIGN(4);__preinit_array_start = .;KEEP (*(.preinit_array))__preinit_array_end = .;. = ALIGN(4);__init_array_start = .;KEEP (*(SORT(.init_array.*)))KEEP (*(.init_array))__init_array_end = .;. = ALIGN(0x4);KEEP (*crtbegin.o(.ctors))KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))KEEP (*(SORT(.ctors.*)))KEEP (*crtend.o(.ctors)). = ALIGN(4);KEEP(*(.fini)). = ALIGN(4);__fini_array_start = .;KEEP (*(.fini_array))KEEP (*(SORT(.fini_array.*)))__fini_array_end = .;KEEP (*crtbegin.o(.dtors))KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))KEEP (*(SORT(.dtors.*)))KEEP (*crtend.o(.dtors)). = ALIGN(4);_efixed = .; /* End of text section */} > rom/* .ARM.exidx is sorted, so has to go in its own output section. */PROVIDE_HIDDEN (__exidx_start = .);.ARM.exidx :{*(.ARM.exidx* .gnu.linkonce.armexidx.*)} > romPROVIDE_HIDDEN (__exidx_end = .);. = ALIGN(4);_etext = .;.relocate : AT (_etext){. = ALIGN(4);_srelocate = .;*(.ramfunc .ramfunc.*);*(.data .data.*);. = ALIGN(4);_erelocate = .;} > ram/* .bss section which is used for uninitialized data */.bss (NOLOAD) :{. = ALIGN(4);_sbss = . ;_szero = .;*(.bss .bss.*)*(COMMON). = ALIGN(4);_ebss = . ;_ezero = .;} > ram/* stack section */.stack (NOLOAD):{. = ALIGN(8);_sstack = .;. = . + __stack_size__;. = ALIGN(8);_estack = .;} > ram. = ALIGN(4);_end = . ;}
123version https://git-lfs.github.com/spec/v1oid sha256:638308fcf2600c90029ba55ae12e713715e496fef9dd6f04cc40ac6569fc52fasize 15364123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#include "FreeRTOS.h"#include "task.h"#include "croutine.h"/** Some kernel aware debuggers require data to be viewed to be global, rather* than file scope.*/#ifdef portREMOVE_STATIC_QUALIFIER#define static#endif/* Lists for ready and blocked co-routines. --------------------*/static xList pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */static xList xDelayedCoRoutineList1; /*< Delayed co-routines. */static xList xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */static xList * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */static xList * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */static xList xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. *//* Other file private variables. --------------------------------*/corCRCB * pxCurrentCoRoutine = NULL;static unsigned portBASE_TYPE uxTopCoRoutineReadyPriority = 0;static portTickType xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0;/* The initial state of the co-routine when it is created. */#define corINITIAL_STATE ( 0 )/** Place the co-routine represented by pxCRCB into the appropriate ready queue* for the priority. It is inserted at the end of the list.** This macro accesses the co-routine ready lists and therefore must not be* used from within an ISR.*/#define prvAddCoRoutineToReadyQueue( pxCRCB ) \{ \if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \{ \uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \} \vListInsertEnd( ( xList * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \}/** Utility to ready all the lists used by the scheduler. This is called* automatically upon the creation of the first co-routine.*/static void prvInitialiseCoRoutineLists( void );/** Co-routines that are readied by an interrupt cannot be placed directly into* the ready lists (there is no mutual exclusion). Instead they are placed in* in the pending ready list in order that they can later be moved to the ready* list by the co-routine scheduler.*/static void prvCheckPendingReadyList( void );/** Macro that looks at the list of co-routines that are currently delayed to* see if any require waking.** Co-routines are stored in the queue in the order of their wake time -* meaning once one co-routine has been found whose timer has not expired* we need not look any further down the list.*/static void prvCheckDelayedList( void );/*-----------------------------------------------------------*/signed portBASE_TYPE xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, unsigned portBASE_TYPE uxPriority, unsigned portBASE_TYPE uxIndex ){signed portBASE_TYPE xReturn;corCRCB *pxCoRoutine;/* Allocate the memory that will store the co-routine control block. */pxCoRoutine = ( corCRCB * ) pvPortMalloc( sizeof( corCRCB ) );if( pxCoRoutine ){/* If pxCurrentCoRoutine is NULL then this is the first co-routine tobe created and the co-routine data structures need initialising. */if( pxCurrentCoRoutine == NULL ){pxCurrentCoRoutine = pxCoRoutine;prvInitialiseCoRoutineLists();}/* Check the priority is within limits. */if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ){uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1;}/* Fill out the co-routine control block from the function parameters. */pxCoRoutine->uxState = corINITIAL_STATE;pxCoRoutine->uxPriority = uxPriority;pxCoRoutine->uxIndex = uxIndex;pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode;/* Initialise all the other co-routine control block parameters. */vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) );vListInitialiseItem( &( pxCoRoutine->xEventListItem ) );/* Set the co-routine control block as a link back from the xListItem.This is so we can get back to the containing CRCB from a generic itemin a list. */listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine );listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine );/* Event lists are always in priority order. */listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) uxPriority );/* Now the co-routine has been initialised it can be added to the readylist at the correct priority. */prvAddCoRoutineToReadyQueue( pxCoRoutine );xReturn = pdPASS;}else{xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;}return xReturn;}/*-----------------------------------------------------------*/void vCoRoutineAddToDelayedList( portTickType xTicksToDelay, xList *pxEventList ){portTickType xTimeToWake;/* Calculate the time to wake - this may overflow but this isnot a problem. */xTimeToWake = xCoRoutineTickCount + xTicksToDelay;/* We must remove ourselves from the ready list before addingourselves to the blocked list as the same list item is used forboth lists. */( void ) uxListRemove( ( xListItem * ) &( pxCurrentCoRoutine->xGenericListItem ) );/* The list item will be inserted in wake time order. */listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake );if( xTimeToWake < xCoRoutineTickCount ){/* Wake time has overflowed. Place this item in theoverflow list. */vListInsert( ( xList * ) pxOverflowDelayedCoRoutineList, ( xListItem * ) &( pxCurrentCoRoutine->xGenericListItem ) );}else{/* The wake time has not overflowed, so we can use thecurrent block list. */vListInsert( ( xList * ) pxDelayedCoRoutineList, ( xListItem * ) &( pxCurrentCoRoutine->xGenericListItem ) );}if( pxEventList ){/* Also add the co-routine to an event list. If this is done then thefunction must be called with interrupts disabled. */vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) );}}/*-----------------------------------------------------------*/static void prvCheckPendingReadyList( void ){/* Are there any co-routines waiting to get moved to the ready list? Theseare co-routines that have been readied by an ISR. The ISR cannot accessthe ready lists itself. */while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ){corCRCB *pxUnblockedCRCB;/* The pending ready list can be accessed by an ISR. */portDISABLE_INTERRUPTS();{pxUnblockedCRCB = ( corCRCB * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) );( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );}portENABLE_INTERRUPTS();( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) );prvAddCoRoutineToReadyQueue( pxUnblockedCRCB );}}/*-----------------------------------------------------------*/static void prvCheckDelayedList( void ){corCRCB *pxCRCB;xPassedTicks = xTaskGetTickCount() - xLastTickCount;while( xPassedTicks ){xCoRoutineTickCount++;xPassedTicks--;/* If the tick count has overflowed we need to swap the ready lists. */if( xCoRoutineTickCount == 0 ){xList * pxTemp;/* Tick count has overflowed so we need to swap the delay lists. If there areany items in pxDelayedCoRoutineList here then there is an error! */pxTemp = pxDelayedCoRoutineList;pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList;pxOverflowDelayedCoRoutineList = pxTemp;}/* See if this tick has made a timeout expire. */while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ){pxCRCB = ( corCRCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList );if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ){/* Timeout not yet expired. */break;}portDISABLE_INTERRUPTS();{/* The event could have occurred just before this criticalsection. If this is the case then the generic list item willhave been moved to the pending ready list and the followingline is still valid. Also the pvContainer parameter will havebeen set to NULL so the following lines are also valid. */uxListRemove( &( pxCRCB->xGenericListItem ) );/* Is the co-routine waiting on an event also? */if( pxCRCB->xEventListItem.pvContainer ){( void ) uxListRemove( &( pxCRCB->xEventListItem ) );}}portENABLE_INTERRUPTS();prvAddCoRoutineToReadyQueue( pxCRCB );}}xLastTickCount = xCoRoutineTickCount;}/*-----------------------------------------------------------*/void vCoRoutineSchedule( void ){/* See if any co-routines readied by events need moving to the ready lists. */prvCheckPendingReadyList();/* See if any delayed co-routines have timed out. */prvCheckDelayedList();/* Find the highest priority queue that contains ready co-routines. */while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ){if( uxTopCoRoutineReadyPriority == 0 ){/* No more co-routines to check. */return;}--uxTopCoRoutineReadyPriority;}/* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routinesof the same priority get an equal share of the processor time. */listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) );/* Call the co-routine. */( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex );return;}/*-----------------------------------------------------------*/static void prvInitialiseCoRoutineLists( void ){unsigned portBASE_TYPE uxPriority;for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ){vListInitialise( ( xList * ) &( pxReadyCoRoutineLists[ uxPriority ] ) );}vListInitialise( ( xList * ) &xDelayedCoRoutineList1 );vListInitialise( ( xList * ) &xDelayedCoRoutineList2 );vListInitialise( ( xList * ) &xPendingReadyCoRoutineList );/* Start with pxDelayedCoRoutineList using list1 and thepxOverflowDelayedCoRoutineList using list2. */pxDelayedCoRoutineList = &xDelayedCoRoutineList1;pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2;}/*-----------------------------------------------------------*/signed portBASE_TYPE xCoRoutineRemoveFromEventList( const xList *pxEventList ){corCRCB *pxUnblockedCRCB;signed portBASE_TYPE xReturn;/* This function is called from within an interrupt. It can only accessevent lists and the pending ready list. This function assumes that acheck has already been made to ensure pxEventList is not empty. */pxUnblockedCRCB = ( corCRCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );vListInsertEnd( ( xList * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) );if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ){xReturn = pdTRUE;}else{xReturn = pdFALSE;}return xReturn;}
123version https://git-lfs.github.com/spec/v1oid sha256:765248d347bb4b824e95992f60c2177df51925dcd0ade90b9093678912371b4esize 19948123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef INC_FREERTOS_H#define INC_FREERTOS_H/** Include the generic headers required for the FreeRTOS port being used.*/#include <stddef.h>/* Basic FreeRTOS definitions. */#include "projdefs.h"/* Application specific configuration options. */#include "FreeRTOSConfig.h"/* configUSE_PORT_OPTIMISED_TASK_SELECTION must be defined before portable.his included as it is used by the port layer. */#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0#endif/* Definitions specific to the port being used. */#include "portable.h"/* Defines the prototype to which the application task hook function mustconform. */typedef portBASE_TYPE (*pdTASK_HOOK_CODE)( void * );/** Check all the required application specific macros have been defined.* These macros are application specific and (as downloaded) are defined* within FreeRTOSConfig.h.*/#ifndef configUSE_PREEMPTION#error Missing definition: configUSE_PREEMPTION should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef configUSE_IDLE_HOOK#error Missing definition: configUSE_IDLE_HOOK should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef configUSE_TICK_HOOK#error Missing definition: configUSE_TICK_HOOK should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef configUSE_CO_ROUTINES#error Missing definition: configUSE_CO_ROUTINES should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_vTaskPrioritySet#error Missing definition: INCLUDE_vTaskPrioritySet should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_uxTaskPriorityGet#error Missing definition: INCLUDE_uxTaskPriorityGet should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_vTaskDelete#error Missing definition: INCLUDE_vTaskDelete should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_vTaskSuspend#error Missing definition: INCLUDE_vTaskSuspend should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_vTaskDelayUntil#error Missing definition: INCLUDE_vTaskDelayUntil should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_vTaskDelay#error Missing definition: INCLUDE_vTaskDelay should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef configUSE_16_BIT_TICKS#error Missing definition: configUSE_16_BIT_TICKS should be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details.#endif#ifndef INCLUDE_xTaskGetIdleTaskHandle#define INCLUDE_xTaskGetIdleTaskHandle 0#endif#ifndef INCLUDE_xTimerGetTimerDaemonTaskHandle#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0#endif#ifndef INCLUDE_xQueueGetMutexHolder#define INCLUDE_xQueueGetMutexHolder 0#endif#ifndef INCLUDE_xSemaphoreGetMutexHolder#define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder#endif#ifndef INCLUDE_pcTaskGetTaskName#define INCLUDE_pcTaskGetTaskName 0#endif#ifndef configUSE_APPLICATION_TASK_TAG#define configUSE_APPLICATION_TASK_TAG 0#endif#ifndef INCLUDE_uxTaskGetStackHighWaterMark#define INCLUDE_uxTaskGetStackHighWaterMark 0#endif#ifndef INCLUDE_eTaskGetState#define INCLUDE_eTaskGetState 0#endif#ifndef configUSE_RECURSIVE_MUTEXES#define configUSE_RECURSIVE_MUTEXES 0#endif#ifndef configUSE_MUTEXES#define configUSE_MUTEXES 0#endif#ifndef configUSE_TIMERS#define configUSE_TIMERS 0#endif#ifndef configUSE_COUNTING_SEMAPHORES#define configUSE_COUNTING_SEMAPHORES 0#endif#ifndef configUSE_ALTERNATIVE_API#define configUSE_ALTERNATIVE_API 0#endif#ifndef portCRITICAL_NESTING_IN_TCB#define portCRITICAL_NESTING_IN_TCB 0#endif#ifndef configMAX_TASK_NAME_LEN#define configMAX_TASK_NAME_LEN 16#endif#ifndef configIDLE_SHOULD_YIELD#define configIDLE_SHOULD_YIELD 1#endif#if configMAX_TASK_NAME_LEN < 1#error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h#endif#ifndef INCLUDE_xTaskResumeFromISR#define INCLUDE_xTaskResumeFromISR 1#endif#ifndef configASSERT#define configASSERT( x )#define configASSERT_DEFINED 0#else#define configASSERT_DEFINED 1#endif/* The timers module relies on xTaskGetSchedulerState(). */#if configUSE_TIMERS == 1#ifndef configTIMER_TASK_PRIORITY#error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined.#endif /* configTIMER_TASK_PRIORITY */#ifndef configTIMER_QUEUE_LENGTH#error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined.#endif /* configTIMER_QUEUE_LENGTH */#ifndef configTIMER_TASK_STACK_DEPTH#error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined.#endif /* configTIMER_TASK_STACK_DEPTH */#endif /* configUSE_TIMERS */#ifndef INCLUDE_xTaskGetSchedulerState#define INCLUDE_xTaskGetSchedulerState 0#endif#ifndef INCLUDE_xTaskGetCurrentTaskHandle#define INCLUDE_xTaskGetCurrentTaskHandle 0#endif#ifndef portSET_INTERRUPT_MASK_FROM_ISR#define portSET_INTERRUPT_MASK_FROM_ISR() 0#endif#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue#endif#ifndef portCLEAN_UP_TCB#define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB#endif#ifndef portSETUP_TCB#define portSETUP_TCB( pxTCB ) ( void ) pxTCB#endif#ifndef configQUEUE_REGISTRY_SIZE#define configQUEUE_REGISTRY_SIZE 0U#endif#if ( configQUEUE_REGISTRY_SIZE < 1 )#define vQueueAddToRegistry( xQueue, pcName )#define vQueueUnregisterQueue( xQueue )#endif#ifndef portPOINTER_SIZE_TYPE#define portPOINTER_SIZE_TYPE unsigned long#endif/* Remove any unused trace macros. */#ifndef traceSTART/* Used to perform any necessary initialisation - for example, open a fileinto which trace is to be written. */#define traceSTART()#endif#ifndef traceEND/* Use to close a trace, for example close a file into which trace has beenwritten. */#define traceEND()#endif#ifndef traceTASK_SWITCHED_IN/* Called after a task has been selected to run. pxCurrentTCB holds a pointerto the task control block of the selected task. */#define traceTASK_SWITCHED_IN()#endif#ifndef traceINCREASE_TICK_COUNT/* Called before stepping the tick count after waking from tickless idlesleep. */#define traceINCREASE_TICK_COUNT( x )#endif#ifndef traceLOW_POWER_IDLE_BEGIN/* Called immediately before entering tickless idle. */#define traceLOW_POWER_IDLE_BEGIN()#endif#ifndef traceLOW_POWER_IDLE_END/* Called when returning to the Idle task after a tickless idle. */#define traceLOW_POWER_IDLE_END()#endif#ifndef traceTASK_SWITCHED_OUT/* Called before a task has been selected to run. pxCurrentTCB holds a pointerto the task control block of the task being switched out. */#define traceTASK_SWITCHED_OUT()#endif#ifndef traceTASK_PRIORITY_INHERIT/* Called when a task attempts to take a mutex that is already held by alower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the taskthat holds the mutex. uxInheritedPriority is the priority the mutex holderwill inherit (the priority of the task that is attempting to obtain themuted. */#define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority )#endif#ifndef traceTASK_PRIORITY_DISINHERIT/* Called when a task releases a mutex, the holding of which had resulted inthe task inheriting the priority of a higher priority task.pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing themutex. uxOriginalPriority is the task's configured (base) priority. */#define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority )#endif#ifndef traceBLOCKING_ON_QUEUE_RECEIVE/* Task is about to block because it cannot read from aqueue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphoreupon which the read was attempted. pxCurrentTCB points to the TCB of thetask that attempted the read. */#define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue )#endif#ifndef traceBLOCKING_ON_QUEUE_SEND/* Task is about to block because it cannot write to aqueue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphoreupon which the write was attempted. pxCurrentTCB points to the TCB of thetask that attempted the write. */#define traceBLOCKING_ON_QUEUE_SEND( pxQueue )#endif#ifndef configCHECK_FOR_STACK_OVERFLOW#define configCHECK_FOR_STACK_OVERFLOW 0#endif/* The following event macros are embedded in the kernel API calls. */#ifndef traceMOVED_TASK_TO_READY_STATE#define traceMOVED_TASK_TO_READY_STATE( pxTCB )#endif#ifndef traceQUEUE_CREATE#define traceQUEUE_CREATE( pxNewQueue )#endif#ifndef traceQUEUE_CREATE_FAILED#define traceQUEUE_CREATE_FAILED( ucQueueType )#endif#ifndef traceCREATE_MUTEX#define traceCREATE_MUTEX( pxNewQueue )#endif#ifndef traceCREATE_MUTEX_FAILED#define traceCREATE_MUTEX_FAILED()#endif#ifndef traceGIVE_MUTEX_RECURSIVE#define traceGIVE_MUTEX_RECURSIVE( pxMutex )#endif#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED#define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex )#endif#ifndef traceTAKE_MUTEX_RECURSIVE#define traceTAKE_MUTEX_RECURSIVE( pxMutex )#endif#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED#define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex )#endif#ifndef traceCREATE_COUNTING_SEMAPHORE#define traceCREATE_COUNTING_SEMAPHORE()#endif#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED#define traceCREATE_COUNTING_SEMAPHORE_FAILED()#endif#ifndef traceQUEUE_SEND#define traceQUEUE_SEND( pxQueue )#endif#ifndef traceQUEUE_SEND_FAILED#define traceQUEUE_SEND_FAILED( pxQueue )#endif#ifndef traceQUEUE_RECEIVE#define traceQUEUE_RECEIVE( pxQueue )#endif#ifndef traceQUEUE_PEEK#define traceQUEUE_PEEK( pxQueue )#endif#ifndef traceQUEUE_PEEK_FROM_ISR#define traceQUEUE_PEEK_FROM_ISR( pxQueue )#endif#ifndef traceQUEUE_RECEIVE_FAILED#define traceQUEUE_RECEIVE_FAILED( pxQueue )#endif#ifndef traceQUEUE_SEND_FROM_ISR#define traceQUEUE_SEND_FROM_ISR( pxQueue )#endif#ifndef traceQUEUE_SEND_FROM_ISR_FAILED#define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue )#endif#ifndef traceQUEUE_RECEIVE_FROM_ISR#define traceQUEUE_RECEIVE_FROM_ISR( pxQueue )#endif#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED#define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue )#endif#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED#define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue )#endif#ifndef traceQUEUE_DELETE#define traceQUEUE_DELETE( pxQueue )#endif#ifndef traceTASK_CREATE#define traceTASK_CREATE( pxNewTCB )#endif#ifndef traceTASK_CREATE_FAILED#define traceTASK_CREATE_FAILED()#endif#ifndef traceTASK_DELETE#define traceTASK_DELETE( pxTaskToDelete )#endif#ifndef traceTASK_DELAY_UNTIL#define traceTASK_DELAY_UNTIL()#endif#ifndef traceTASK_DELAY#define traceTASK_DELAY()#endif#ifndef traceTASK_PRIORITY_SET#define traceTASK_PRIORITY_SET( pxTask, uxNewPriority )#endif#ifndef traceTASK_SUSPEND#define traceTASK_SUSPEND( pxTaskToSuspend )#endif#ifndef traceTASK_RESUME#define traceTASK_RESUME( pxTaskToResume )#endif#ifndef traceTASK_RESUME_FROM_ISR#define traceTASK_RESUME_FROM_ISR( pxTaskToResume )#endif#ifndef traceTASK_INCREMENT_TICK#define traceTASK_INCREMENT_TICK( xTickCount )#endif#ifndef traceTIMER_CREATE#define traceTIMER_CREATE( pxNewTimer )#endif#ifndef traceTIMER_CREATE_FAILED#define traceTIMER_CREATE_FAILED()#endif#ifndef traceTIMER_COMMAND_SEND#define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn )#endif#ifndef traceTIMER_EXPIRED#define traceTIMER_EXPIRED( pxTimer )#endif#ifndef traceTIMER_COMMAND_RECEIVED#define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue )#endif#ifndef traceMALLOC#define traceMALLOC( pvAddress, uiSize )#endif#ifndef traceFREE#define traceFREE( pvAddress, uiSize )#endif#ifndef configGENERATE_RUN_TIME_STATS#define configGENERATE_RUN_TIME_STATS 0#endif#if ( configGENERATE_RUN_TIME_STATS == 1 )#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS#error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base.#endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */#ifndef portGET_RUN_TIME_COUNTER_VALUE#ifndef portALT_GET_RUN_TIME_COUNTER_VALUE#error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information.#endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */#endif /* portGET_RUN_TIME_COUNTER_VALUE */#endif /* configGENERATE_RUN_TIME_STATS */#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS()#endif#ifndef configUSE_MALLOC_FAILED_HOOK#define configUSE_MALLOC_FAILED_HOOK 0#endif#ifndef portPRIVILEGE_BIT#define portPRIVILEGE_BIT ( ( unsigned portBASE_TYPE ) 0x00 )#endif#ifndef portYIELD_WITHIN_API#define portYIELD_WITHIN_API portYIELD#endif#ifndef pvPortMallocAligned#define pvPortMallocAligned( x, puxStackBuffer ) ( ( ( puxStackBuffer ) == NULL ) ? ( pvPortMalloc( ( x ) ) ) : ( puxStackBuffer ) )#endif#ifndef vPortFreeAligned#define vPortFreeAligned( pvBlockToFree ) vPortFree( pvBlockToFree )#endif#ifndef portSUPPRESS_TICKS_AND_SLEEP#define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime )#endif#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2#endif#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2#error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2#endif#ifndef configUSE_TICKLESS_IDLE#define configUSE_TICKLESS_IDLE 0#endif#ifndef configPRE_SLEEP_PROCESSING#define configPRE_SLEEP_PROCESSING( x )#endif#ifndef configPOST_SLEEP_PROCESSING#define configPOST_SLEEP_PROCESSING( x )#endif#ifndef configUSE_QUEUE_SETS#define configUSE_QUEUE_SETS 0#endif#ifndef portTASK_USES_FLOATING_POINT#define portTASK_USES_FLOATING_POINT()#endif#ifndef configUSE_TIME_SLICING#define configUSE_TIME_SLICING 1#endif#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0#endif#ifndef configUSE_NEWLIB_REENTRANT#define configUSE_NEWLIB_REENTRANT 0#endif#ifndef configUSE_STATS_FORMATTING_FUNCTIONS#define configUSE_STATS_FORMATTING_FUNCTIONS 0#endif#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID#define portASSERT_IF_INTERRUPT_PRIORITY_INVALID()#endif/* For backward compatability. */#define eTaskStateGet eTaskGetState#endif /* INC_FREERTOS_H */
123version https://git-lfs.github.com/spec/v1oid sha256:a586d5c4ffa19f6ef3d9f3e00582e72e4d184b7d246d08a32c1966b3405447dasize 9207123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef STACK_MACROS_H#define STACK_MACROS_H/** Call the stack overflow hook function if the stack of the task being swapped* out is currently overflowed, or looks like it might have overflowed in the* past.** Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check* the current stack state only - comparing the current top of stack value to* the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1* will also cause the last few stack bytes to be checked to ensure the value* to which the bytes were set when the task was created have not been* overwritten. Note this second test does not guarantee that an overflowed* stack will always be recognised.*//*-----------------------------------------------------------*/#if( configCHECK_FOR_STACK_OVERFLOW == 0 )/* FreeRTOSConfig.h is not set to check for stack overflows. */#define taskFIRST_CHECK_FOR_STACK_OVERFLOW()#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()#endif /* configCHECK_FOR_STACK_OVERFLOW == 0 *//*-----------------------------------------------------------*/#if( configCHECK_FOR_STACK_OVERFLOW == 1 )/* FreeRTOSConfig.h is only set to use the first method ofoverflow checking. */#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()#endif/*-----------------------------------------------------------*/#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH < 0 ) )/* Only the current stack state is to be checked. */#define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \{ \/* Is the currently saved stack pointer within the stack limit? */ \if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \{ \vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \} \}#endif /* configCHECK_FOR_STACK_OVERFLOW > 0 *//*-----------------------------------------------------------*/#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH > 0 ) )/* Only the current stack state is to be checked. */#define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \{ \\/* Is the currently saved stack pointer within the stack limit? */ \if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \{ \vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \} \}#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 *//*-----------------------------------------------------------*/#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )#define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \{ \static const unsigned char ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \\\/* Has the extremity of the task stack ever been written over? */ \if( memcmp( ( void * ) pxCurrentTCB->pxStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \{ \vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \} \}#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) *//*-----------------------------------------------------------*/#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )#define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \{ \char *pcEndOfStack = ( char * ) pxCurrentTCB->pxEndOfStack; \static const unsigned char ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \\\pcEndOfStack -= sizeof( ucExpectedStackBytes ); \\/* Has the extremity of the task stack ever been written over? */ \if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \{ \vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \} \}#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) *//*-----------------------------------------------------------*/#endif /* STACK_MACROS_H */
123version https://git-lfs.github.com/spec/v1oid sha256:3c3fa3f6f3953c3f0634aa0235d7add3331c76c8985a9c3cabeb4916c4091909size 29050123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef CO_ROUTINE_H#define CO_ROUTINE_H#ifndef INC_FREERTOS_H#error "include FreeRTOS.h must appear in source files before include croutine.h"#endif#include "list.h"#ifdef __cplusplusextern "C" {#endif/* Used to hide the implementation of the co-routine control block. Thecontrol block structure however has to be included in the header due tothe macro implementation of the co-routine functionality. */typedef void * xCoRoutineHandle;/* Defines the prototype to which co-routine functions must conform. */typedef void (*crCOROUTINE_CODE)( xCoRoutineHandle, unsigned portBASE_TYPE );typedef struct corCoRoutineControlBlock{crCOROUTINE_CODE pxCoRoutineFunction;xListItem xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */xListItem xEventListItem; /*< List item used to place the CRCB in event lists. */unsigned portBASE_TYPE uxPriority; /*< The priority of the co-routine in relation to other co-routines. */unsigned portBASE_TYPE uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */unsigned short uxState; /*< Used internally by the co-routine implementation. */} corCRCB; /* Co-routine control block. Note must be identical in size down to uxPriority with tskTCB. *//*** croutine. h*<pre>portBASE_TYPE xCoRoutineCreate(crCOROUTINE_CODE pxCoRoutineCode,unsigned portBASE_TYPE uxPriority,unsigned portBASE_TYPE uxIndex);</pre>** Create a new co-routine and add it to the list of co-routines that are* ready to run.** @param pxCoRoutineCode Pointer to the co-routine function. Co-routine* functions require special syntax - see the co-routine section of the WEB* documentation for more information.** @param uxPriority The priority with respect to other co-routines at which* the co-routine will run.** @param uxIndex Used to distinguish between different co-routines that* execute the same function. See the example below and the co-routine section* of the WEB documentation for further information.** @return pdPASS if the co-routine was successfully created and added to a ready* list, otherwise an error code defined with ProjDefs.h.** Example usage:<pre>// Co-routine to be created.void vFlashCoRoutine( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// Variables in co-routines must be declared static if they must maintain value across a blocking call.// This may not be necessary for const variables.static const char cLedToFlash[ 2 ] = { 5, 6 };static const portTickType uxFlashRates[ 2 ] = { 200, 400 };// Must start every co-routine with a call to crSTART();crSTART( xHandle );for( ;; ){// This co-routine just delays for a fixed period, then toggles// an LED. Two co-routines are created using this function, so// the uxIndex parameter is used to tell the co-routine which// LED to flash and how long to delay. This assumes xQueue has// already been created.vParTestToggleLED( cLedToFlash[ uxIndex ] );crDELAY( xHandle, uxFlashRates[ uxIndex ] );}// Must end every co-routine with a call to crEND();crEND();}// Function that creates two co-routines.void vOtherFunction( void ){unsigned char ucParameterToPass;xTaskHandle xHandle;// Create two co-routines at priority 0. The first is given index 0// so (from the code above) toggles LED 5 every 200 ticks. The second// is given index 1 so toggles LED 6 every 400 ticks.for( uxIndex = 0; uxIndex < 2; uxIndex++ ){xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );}}</pre>* \defgroup xCoRoutineCreate xCoRoutineCreate* \ingroup Tasks*/signed portBASE_TYPE xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, unsigned portBASE_TYPE uxPriority, unsigned portBASE_TYPE uxIndex );/*** croutine. h*<pre>void vCoRoutineSchedule( void );</pre>** Run a co-routine.** vCoRoutineSchedule() executes the highest priority co-routine that is able* to run. The co-routine will execute until it either blocks, yields or is* preempted by a task. Co-routines execute cooperatively so one* co-routine cannot be preempted by another, but can be preempted by a task.** If an application comprises of both tasks and co-routines then* vCoRoutineSchedule should be called from the idle task (in an idle task* hook).** Example usage:<pre>// This idle task hook will schedule a co-routine each time it is called.// The rest of the idle task will execute between co-routine calls.void vApplicationIdleHook( void ){vCoRoutineSchedule();}// Alternatively, if you do not require any other part of the idle task to// execute, the idle task hook can call vCoRoutineScheduler() within an// infinite loop.void vApplicationIdleHook( void ){for( ;; ){vCoRoutineSchedule();}}</pre>* \defgroup vCoRoutineSchedule vCoRoutineSchedule* \ingroup Tasks*/void vCoRoutineSchedule( void );/*** croutine. h* <pre>crSTART( xCoRoutineHandle xHandle );</pre>** This macro MUST always be called at the start of a co-routine function.** Example usage:<pre>// Co-routine to be created.void vACoRoutine( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// Variables in co-routines must be declared static if they must maintain value across a blocking call.static long ulAVariable;// Must start every co-routine with a call to crSTART();crSTART( xHandle );for( ;; ){// Co-routine functionality goes here.}// Must end every co-routine with a call to crEND();crEND();}</pre>* \defgroup crSTART crSTART* \ingroup Tasks*/#define crSTART( pxCRCB ) switch( ( ( corCRCB * )( pxCRCB ) )->uxState ) { case 0:/*** croutine. h* <pre>crEND();</pre>** This macro MUST always be called at the end of a co-routine function.** Example usage:<pre>// Co-routine to be created.void vACoRoutine( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// Variables in co-routines must be declared static if they must maintain value across a blocking call.static long ulAVariable;// Must start every co-routine with a call to crSTART();crSTART( xHandle );for( ;; ){// Co-routine functionality goes here.}// Must end every co-routine with a call to crEND();crEND();}</pre>* \defgroup crSTART crSTART* \ingroup Tasks*/#define crEND() }/** These macros are intended for internal use by the co-routine implementation* only. The macros should not be used directly by application writers.*/#define crSET_STATE0( xHandle ) ( ( corCRCB * )( xHandle ) )->uxState = (__LINE__ * 2); return; case (__LINE__ * 2):#define crSET_STATE1( xHandle ) ( ( corCRCB * )( xHandle ) )->uxState = ((__LINE__ * 2)+1); return; case ((__LINE__ * 2)+1):/*** croutine. h*<pre>crDELAY( xCoRoutineHandle xHandle, portTickType xTicksToDelay );</pre>** Delay a co-routine for a fixed period of time.** crDELAY can only be called from the co-routine function itself - not* from within a function called by the co-routine function. This is because* co-routines do not maintain their own stack.** @param xHandle The handle of the co-routine to delay. This is the xHandle* parameter of the co-routine function.** @param xTickToDelay The number of ticks that the co-routine should delay* for. The actual amount of time this equates to is defined by* configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_RATE_MS* can be used to convert ticks to milliseconds.** Example usage:<pre>// Co-routine to be created.void vACoRoutine( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// Variables in co-routines must be declared static if they must maintain value across a blocking call.// This may not be necessary for const variables.// We are to delay for 200ms.static const xTickType xDelayTime = 200 / portTICK_RATE_MS;// Must start every co-routine with a call to crSTART();crSTART( xHandle );for( ;; ){// Delay for 200ms.crDELAY( xHandle, xDelayTime );// Do something here.}// Must end every co-routine with a call to crEND();crEND();}</pre>* \defgroup crDELAY crDELAY* \ingroup Tasks*/#define crDELAY( xHandle, xTicksToDelay ) \if( ( xTicksToDelay ) > 0 ) \{ \vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \} \crSET_STATE0( ( xHandle ) );/*** <pre>crQUEUE_SEND(xCoRoutineHandle xHandle,xQueueHandle pxQueue,void *pvItemToQueue,portTickType xTicksToWait,portBASE_TYPE *pxResult)</pre>** The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine* equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.** crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas* xQueueSend() and xQueueReceive() can only be used from tasks.** crQUEUE_SEND can only be called from the co-routine function itself - not* from within a function called by the co-routine function. This is because* co-routines do not maintain their own stack.** See the co-routine section of the WEB documentation for information on* passing data between tasks and co-routines and between ISR's and* co-routines.** @param xHandle The handle of the calling co-routine. This is the xHandle* parameter of the co-routine function.** @param pxQueue The handle of the queue on which the data will be posted.* The handle is obtained as the return value when the queue is created using* the xQueueCreate() API function.** @param pvItemToQueue A pointer to the data being posted onto the queue.* The number of bytes of each queued item is specified when the queue is* created. This number of bytes is copied from pvItemToQueue into the queue* itself.** @param xTickToDelay The number of ticks that the co-routine should block* to wait for space to become available on the queue, should space not be* available immediately. The actual amount of time this equates to is defined* by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant* portTICK_RATE_MS can be used to convert ticks to milliseconds (see example* below).** @param pxResult The variable pointed to by pxResult will be set to pdPASS if* data was successfully posted onto the queue, otherwise it will be set to an* error defined within ProjDefs.h.** Example usage:<pre>// Co-routine function that blocks for a fixed period then posts a number onto// a queue.static void prvCoRoutineFlashTask( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// Variables in co-routines must be declared static if they must maintain value across a blocking call.static portBASE_TYPE xNumberToPost = 0;static portBASE_TYPE xResult;// Co-routines must begin with a call to crSTART().crSTART( xHandle );for( ;; ){// This assumes the queue has already been created.crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );if( xResult != pdPASS ){// The message was not posted!}// Increment the number to be posted onto the queue.xNumberToPost++;// Delay for 100 ticks.crDELAY( xHandle, 100 );}// Co-routines must end with a call to crEND().crEND();}</pre>* \defgroup crQUEUE_SEND crQUEUE_SEND* \ingroup Tasks*/#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \{ \*( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) ); \if( *( pxResult ) == errQUEUE_BLOCKED ) \{ \crSET_STATE0( ( xHandle ) ); \*pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \} \if( *pxResult == errQUEUE_YIELD ) \{ \crSET_STATE1( ( xHandle ) ); \*pxResult = pdPASS; \} \}/*** croutine. h* <pre>crQUEUE_RECEIVE(xCoRoutineHandle xHandle,xQueueHandle pxQueue,void *pvBuffer,portTickType xTicksToWait,portBASE_TYPE *pxResult)</pre>** The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine* equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.** crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas* xQueueSend() and xQueueReceive() can only be used from tasks.** crQUEUE_RECEIVE can only be called from the co-routine function itself - not* from within a function called by the co-routine function. This is because* co-routines do not maintain their own stack.** See the co-routine section of the WEB documentation for information on* passing data between tasks and co-routines and between ISR's and* co-routines.** @param xHandle The handle of the calling co-routine. This is the xHandle* parameter of the co-routine function.** @param pxQueue The handle of the queue from which the data will be received.* The handle is obtained as the return value when the queue is created using* the xQueueCreate() API function.** @param pvBuffer The buffer into which the received item is to be copied.* The number of bytes of each queued item is specified when the queue is* created. This number of bytes is copied into pvBuffer.** @param xTickToDelay The number of ticks that the co-routine should block* to wait for data to become available from the queue, should data not be* available immediately. The actual amount of time this equates to is defined* by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant* portTICK_RATE_MS can be used to convert ticks to milliseconds (see the* crQUEUE_SEND example).** @param pxResult The variable pointed to by pxResult will be set to pdPASS if* data was successfully retrieved from the queue, otherwise it will be set to* an error code as defined within ProjDefs.h.** Example usage:<pre>// A co-routine receives the number of an LED to flash from a queue. It// blocks on the queue until the number is received.static void prvCoRoutineFlashWorkTask( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// Variables in co-routines must be declared static if they must maintain value across a blocking call.static portBASE_TYPE xResult;static unsigned portBASE_TYPE uxLEDToFlash;// All co-routines must start with a call to crSTART().crSTART( xHandle );for( ;; ){// Wait for data to become available on the queue.crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );if( xResult == pdPASS ){// We received the LED to flash - flash it!vParTestToggleLED( uxLEDToFlash );}}crEND();}</pre>* \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE* \ingroup Tasks*/#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \{ \*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) ); \if( *( pxResult ) == errQUEUE_BLOCKED ) \{ \crSET_STATE0( ( xHandle ) ); \*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 ); \} \if( *( pxResult ) == errQUEUE_YIELD ) \{ \crSET_STATE1( ( xHandle ) ); \*( pxResult ) = pdPASS; \} \}/*** croutine. h* <pre>crQUEUE_SEND_FROM_ISR(xQueueHandle pxQueue,void *pvItemToQueue,portBASE_TYPE xCoRoutinePreviouslyWoken)</pre>** The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the* co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()* functions used by tasks.** crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to* pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and* xQueueReceiveFromISR() can only be used to pass data between a task and and* ISR.** crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue* that is being used from within a co-routine.** See the co-routine section of the WEB documentation for information on* passing data between tasks and co-routines and between ISR's and* co-routines.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto* the same queue multiple times from a single interrupt. The first call* should always pass in pdFALSE. Subsequent calls should pass in* the value returned from the previous call.** @return pdTRUE if a co-routine was woken by posting onto the queue. This is* used by the ISR to determine if a context switch may be required following* the ISR.** Example usage:<pre>// A co-routine that blocks on a queue waiting for characters to be received.static void vReceivingCoRoutine( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){char cRxedChar;portBASE_TYPE xResult;// All co-routines must start with a call to crSTART().crSTART( xHandle );for( ;; ){// Wait for data to become available on the queue. This assumes the// queue xCommsRxQueue has already been created!crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );// Was a character received?if( xResult == pdPASS ){// Process the character here.}}// All co-routines must end with a call to crEND().crEND();}// An ISR that uses a queue to send characters received on a serial port to// a co-routine.void vUART_ISR( void ){char cRxedChar;portBASE_TYPE xCRWokenByPost = pdFALSE;// We loop around reading characters until there are none left in the UART.while( UART_RX_REG_NOT_EMPTY() ){// Obtain the character from the UART.cRxedChar = UART_RX_REG;// Post the character onto a queue. xCRWokenByPost will be pdFALSE// the first time around the loop. If the post causes a co-routine// to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.// In this manner we can ensure that if more than one co-routine is// blocked on the queue only one is woken by this ISR no matter how// many characters are posted to the queue.xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );}}</pre>* \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR* \ingroup Tasks*/#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) )/*** croutine. h* <pre>crQUEUE_SEND_FROM_ISR(xQueueHandle pxQueue,void *pvBuffer,portBASE_TYPE * pxCoRoutineWoken)</pre>** The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the* co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()* functions used by tasks.** crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to* pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and* xQueueReceiveFromISR() can only be used to pass data between a task and and* ISR.** crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data* from a queue that is being used from within a co-routine (a co-routine* posted to the queue).** See the co-routine section of the WEB documentation for information on* passing data between tasks and co-routines and between ISR's and* co-routines.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvBuffer A pointer to a buffer into which the received item will be* placed. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from the queue into* pvBuffer.** @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become* available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a* co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise* *pxCoRoutineWoken will remain unchanged.** @return pdTRUE an item was successfully received from the queue, otherwise* pdFALSE.** Example usage:<pre>// A co-routine that posts a character to a queue then blocks for a fixed// period. The character is incremented each time.static void vSendingCoRoutine( xCoRoutineHandle xHandle, unsigned portBASE_TYPE uxIndex ){// cChar holds its value while this co-routine is blocked and must therefore// be declared static.static char cCharToTx = 'a';portBASE_TYPE xResult;// All co-routines must start with a call to crSTART().crSTART( xHandle );for( ;; ){// Send the next character to the queue.crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );if( xResult == pdPASS ){// The character was successfully posted to the queue.}else{// Could not post the character to the queue.}// Enable the UART Tx interrupt to cause an interrupt in this// hypothetical UART. The interrupt will obtain the character// from the queue and send it.ENABLE_RX_INTERRUPT();// Increment to the next character then block for a fixed period.// cCharToTx will maintain its value across the delay as it is// declared static.cCharToTx++;if( cCharToTx > 'x' ){cCharToTx = 'a';}crDELAY( 100 );}// All co-routines must end with a call to crEND().crEND();}// An ISR that uses a queue to receive characters to send on a UART.void vUART_ISR( void ){char cCharToTx;portBASE_TYPE xCRWokenByPost = pdFALSE;while( UART_TX_REG_EMPTY() ){// Are there any characters in the queue waiting to be sent?// xCRWokenByPost will automatically be set to pdTRUE if a co-routine// is woken by the post - ensuring that only a single co-routine is// woken no matter how many times we go around this loop.if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) ){SEND_CHARACTER( cCharToTx );}}}</pre>* \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR* \ingroup Tasks*/#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) )/** This function is intended for internal use by the co-routine macros only.* The macro nature of the co-routine implementation requires that the* prototype appears here. The function should not be used by application* writers.** Removes the current co-routine from its ready list and places it in the* appropriate delayed list.*/void vCoRoutineAddToDelayedList( portTickType xTicksToDelay, xList *pxEventList );/** This function is intended for internal use by the queue implementation only.* The function should not be used by application writers.** Removes the highest priority co-routine from the event list and places it in* the pending ready list.*/signed portBASE_TYPE xCoRoutineRemoveFromEventList( const xList *pxEventList );#ifdef __cplusplus}#endif#endif /* CO_ROUTINE_H */
123version https://git-lfs.github.com/spec/v1oid sha256:131de852b2f2a6972ac44a50816391e445bf508481d27706dc1659312da60dcbsize 16818123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//** This is the list implementation used by the scheduler. While it is tailored* heavily for the schedulers needs, it is also available for use by* application code.** xLists can only store pointers to xListItems. Each xListItem contains a* numeric value (xItemValue). Most of the time the lists are sorted in* descending item value order.** Lists are created already containing one list item. The value of this* item is the maximum possible that can be stored, it is therefore always at* the end of the list and acts as a marker. The list member pxHead always* points to this marker - even though it is at the tail of the list. This* is because the tail contains a wrap back pointer to the true head of* the list.** In addition to it's value, each list item contains a pointer to the next* item in the list (pxNext), a pointer to the list it is in (pxContainer)* and a pointer to back to the object that contains it. These later two* pointers are included for efficiency of list manipulation. There is* effectively a two way link between the object containing the list item and* the list item itself.*** \page ListIntroduction List Implementation* \ingroup FreeRTOSIntro*/#ifndef LIST_H#define LIST_H/** The list structure members are modified from within interrupts, and therefore* by rights should be declared volatile. However, they are only modified in a* functionally atomic way (within critical sections of with the scheduler* suspended) and are either passed by reference into a function or indexed via* a volatile variable. Therefore, in all use cases tested so far, the volatile* qualifier can be omitted in order to provide a moderate performance* improvement without adversely affecting functional behaviour. The assembly* instructions generated by the IAR, ARM and GCC compilers when the respective* compiler's options were set for maximum optimisation has been inspected and* deemed to be as intended. That said, as compiler technology advances, and* especially if aggressive cross module optimisation is used (a use case that* has not been exercised to any great extend) then it is feasible that the* volatile qualifier will be needed for correct optimisation. It is expected* that a compiler removing essential code because, without the volatile* qualifier on the list structure members and with aggressive cross module* optimisation, the compiler deemed the code unnecessary will result in* complete and obvious failure of the scheduler. If this is ever experienced* then the volatile qualifier can be inserted in the relevant places within the* list structures by simply defining configLIST_VOLATILE to volatile in* FreeRTOSConfig.h (as per the example at the bottom of this comment block).* If configLIST_VOLATILE is not defined then the preprocessor directives below* will simply #define configLIST_VOLATILE away completely.** To use volatile list structure members then add the following line to* FreeRTOSConfig.h (without the quotes):* "#define configLIST_VOLATILE volatile"*/#ifndef configLIST_VOLATILE#define configLIST_VOLATILE#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */#ifdef __cplusplusextern "C" {#endif/** Definition of the only type of object that a list can contain.*/struct xLIST_ITEM{configLIST_VOLATILE portTickType xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next xListItem in the list. */struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;/*< Pointer to the previous xListItem in the list. */void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */void * configLIST_VOLATILE pvContainer; /*< Pointer to the list in which this list item is placed (if any). */};typedef struct xLIST_ITEM xListItem; /* For some reason lint wants this as two separate definitions. */struct xMINI_LIST_ITEM{configLIST_VOLATILE portTickType xItemValue;struct xLIST_ITEM * configLIST_VOLATILE pxNext;struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;};typedef struct xMINI_LIST_ITEM xMiniListItem;/** Definition of the type of queue used by the scheduler.*/typedef struct xLIST{configLIST_VOLATILE unsigned portBASE_TYPE uxNumberOfItems;xListItem * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to pvListGetOwnerOfNextEntry (). */xMiniListItem xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */} xList;/** Access macro to set the owner of a list item. The owner of a list item* is the object (usually a TCB) that contains the list item.** \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER* \ingroup LinkedList*/#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) )/** Access macro to get the owner of a list item. The owner of a list item* is the object (usually a TCB) that contains the list item.** \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER* \ingroup LinkedList*/#define listGET_LIST_ITEM_OWNER( pxListItem ) ( pxListItem )->pvOwner/** Access macro to set the value of the list item. In most cases the value is* used to sort the list in descending order.** \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE* \ingroup LinkedList*/#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) )/** Access macro to retrieve the value of the list item. The value can* represent anything - for example a the priority of a task, or the time at* which a task should be unblocked.** \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE* \ingroup LinkedList*/#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue )/** Access macro the retrieve the value of the list item at the head of a given* list.** \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE* \ingroup LinkedList*/#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( (&( ( pxList )->xListEnd ))->pxNext->xItemValue )/** Access macro to determine if a list contains any items. The macro will* only have the value true if the list is empty.** \page listLIST_IS_EMPTY listLIST_IS_EMPTY* \ingroup LinkedList*/#define listLIST_IS_EMPTY( pxList ) ( ( portBASE_TYPE ) ( ( pxList )->uxNumberOfItems == ( unsigned portBASE_TYPE ) 0 ) )/** Access macro to return the number of items in the list.*/#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems )/** Access function to obtain the owner of the next entry in a list.** The list member pxIndex is used to walk through a list. Calling* listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list* and returns that entries pxOwner parameter. Using multiple calls to this* function it is therefore possible to move through every item contained in* a list.** The pxOwner parameter of a list item is a pointer to the object that owns* the list item. In the scheduler this is normally a task control block.* The pxOwner parameter effectively creates a two way link between the list* item and its owner.** @param pxList The list from which the next item owner is to be returned.** \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY* \ingroup LinkedList*/#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \{ \xList * const pxConstList = ( pxList ); \/* Increment the index to the next item and return the item, ensuring */ \/* we don't return the marker used at the end of the list. */ \( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \{ \( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \} \( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \}/** Access function to obtain the owner of the first entry in a list. Lists* are normally sorted in ascending item value order.** This function returns the pxOwner member of the first item in the list.* The pxOwner parameter of a list item is a pointer to the object that owns* the list item. In the scheduler this is normally a task control block.* The pxOwner parameter effectively creates a two way link between the list* item and its owner.** @param pxList The list from which the owner of the head item is to be* returned.** \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY* \ingroup LinkedList*/#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner )/** Check to see if a list item is within a list. The list item maintains a* "container" pointer that points to the list it is in. All this macro does* is check to see if the container and the list match.** @param pxList The list we want to know if the list item is within.* @param pxListItem The list item we want to know if is in the list.* @return pdTRUE is the list item is in the list, otherwise pdFALSE.* pointer against*/#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( portBASE_TYPE ) ( ( pxListItem )->pvContainer == ( void * ) ( pxList ) ) )/** Return the list a list item is contained within (referenced from).** @param pxListItem The list item being queried.* @return A pointer to the xList object that references the pxListItem*/#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pvContainer )/** This provides a crude means of knowing if a list has been initialised, as* pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise()* function.*/#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY )/** Must be called before a list is used! This initialises all the members* of the list structure and inserts the xListEnd item into the list as a* marker to the back of the list.** @param pxList Pointer to the list being initialised.** \page vListInitialise vListInitialise* \ingroup LinkedList*/void vListInitialise( xList * const pxList );/** Must be called before a list item is used. This sets the list container to* null so the item does not think that it is already contained in a list.** @param pxItem Pointer to the list item being initialised.** \page vListInitialiseItem vListInitialiseItem* \ingroup LinkedList*/void vListInitialiseItem( xListItem * const pxItem );/** Insert a list item into a list. The item will be inserted into the list in* a position determined by its item value (descending item value order).** @param pxList The list into which the item is to be inserted.** @param pxNewListItem The item to that is to be placed in the list.** \page vListInsert vListInsert* \ingroup LinkedList*/void vListInsert( xList * const pxList, xListItem * const pxNewListItem );/** Insert a list item into a list. The item will be inserted in a position* such that it will be the last item within the list returned by multiple* calls to listGET_OWNER_OF_NEXT_ENTRY.** The list member pvIndex is used to walk through a list. Calling* listGET_OWNER_OF_NEXT_ENTRY increments pvIndex to the next item in the list.* Placing an item in a list using vListInsertEnd effectively places the item* in the list position pointed to by pvIndex. This means that every other* item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before* the pvIndex parameter again points to the item being inserted.** @param pxList The list into which the item is to be inserted.** @param pxNewListItem The list item to be inserted into the list.** \page vListInsertEnd vListInsertEnd* \ingroup LinkedList*/void vListInsertEnd( xList * const pxList, xListItem * const pxNewListItem );/** Remove an item from a list. The list item has a pointer to the list that* it is in, so only the list item need be passed into the function.** @param uxListRemove The item to be removed. The item will remove itself from* the list pointed to by it's pxContainer parameter.** @return The number of items that remain in the list after the list item has* been removed.** \page uxListRemove uxListRemove* \ingroup LinkedList*/unsigned portBASE_TYPE uxListRemove( xListItem * const pxItemToRemove );#ifdef __cplusplus}#endif#endif
123version https://git-lfs.github.com/spec/v1oid sha256:eba367cb0305a4e3ee56e9af569d98f0e2386a5f5f947000f382b6549c0d339asize 7412123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef MPU_WRAPPERS_H#define MPU_WRAPPERS_H/* This file redefines API functions to be called through a wrapper macro, butonly for ports that are using the MPU. */#ifdef portUSING_MPU_WRAPPERS/* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file isincluded from queue.c or task.c to prevent it from having an effect withinthose files. */#ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE#define xTaskGenericCreate MPU_xTaskGenericCreate#define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions#define vTaskDelete MPU_vTaskDelete#define vTaskDelayUntil MPU_vTaskDelayUntil#define vTaskDelay MPU_vTaskDelay#define uxTaskPriorityGet MPU_uxTaskPriorityGet#define vTaskPrioritySet MPU_vTaskPrioritySet#define eTaskGetState MPU_eTaskGetState#define vTaskSuspend MPU_vTaskSuspend#define xTaskIsTaskSuspended MPU_xTaskIsTaskSuspended#define vTaskResume MPU_vTaskResume#define vTaskSuspendAll MPU_vTaskSuspendAll#define xTaskResumeAll MPU_xTaskResumeAll#define xTaskGetTickCount MPU_xTaskGetTickCount#define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks#define vTaskList MPU_vTaskList#define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats#define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag#define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag#define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook#define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark#define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle#define xTaskGetSchedulerState MPU_xTaskGetSchedulerState#define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle#define uxTaskGetSystemState MPU_uxTaskGetSystemState#define xQueueGenericCreate MPU_xQueueGenericCreate#define xQueueCreateMutex MPU_xQueueCreateMutex#define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive#define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive#define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore#define xQueueGenericSend MPU_xQueueGenericSend#define xQueueAltGenericSend MPU_xQueueAltGenericSend#define xQueueAltGenericReceive MPU_xQueueAltGenericReceive#define xQueueGenericReceive MPU_xQueueGenericReceive#define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting#define vQueueDelete MPU_vQueueDelete#define xQueueGenericReset MPU_xQueueGenericReset#define xQueueCreateSet MPU_xQueueCreateSet#define xQueueSelectFromSet MPU_xQueueSelectFromSet#define xQueueAddToSet MPU_xQueueAddToSet#define xQueueRemoveFromSet MPU_xQueueRemoveFromSet#define xQueuePeekFromISR MPU_xQueuePeekFromISR#define pvPortMalloc MPU_pvPortMalloc#define vPortFree MPU_vPortFree#define xPortGetFreeHeapSize MPU_xPortGetFreeHeapSize#define vPortInitialiseBlocks MPU_vPortInitialiseBlocks#if configQUEUE_REGISTRY_SIZE > 0#define vQueueAddToRegistry MPU_vQueueAddToRegistry#define vQueueUnregisterQueue MPU_vQueueUnregisterQueue#endif/* Remove the privileged function macro. */#define PRIVILEGED_FUNCTION#else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE *//* Ensure API functions go in the privileged execution section. */#define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions")))#define PRIVILEGED_DATA __attribute__((section("privileged_data")))#endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */#else /* portUSING_MPU_WRAPPERS */#define PRIVILEGED_FUNCTION#define PRIVILEGED_DATA#define portUSING_MPU_WRAPPERS 0#endif /* portUSING_MPU_WRAPPERS */#endif /* MPU_WRAPPERS_H */
123version https://git-lfs.github.com/spec/v1oid sha256:1443c46676de6d54aa53372369e29e2caae64949f7e26e2f0f2f8309e8436937size 12416123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//*-----------------------------------------------------------* Portable layer API. Each function must be defined for each port.*----------------------------------------------------------*/#ifndef PORTABLE_H#define PORTABLE_H/* Include the macro file relevant to the port being used. */#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT#include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h"typedef void ( __interrupt __far *pxISR )();#endif#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT#include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h"typedef void ( __interrupt __far *pxISR )();#endif#ifdef GCC_MEGA_AVR#include "../portable/GCC/ATMega323/portmacro.h"#endif#ifdef IAR_MEGA_AVR#include "../portable/IAR/ATMega323/portmacro.h"#endif#ifdef MPLAB_PIC24_PORT#include "..\..\Source\portable\MPLAB\PIC24_dsPIC\portmacro.h"#endif#ifdef MPLAB_DSPIC_PORT#include "..\..\Source\portable\MPLAB\PIC24_dsPIC\portmacro.h"#endif#ifdef MPLAB_PIC18F_PORT#include "..\..\Source\portable\MPLAB\PIC18F\portmacro.h"#endif#ifdef MPLAB_PIC32MX_PORT#include "../../Source/portable/MPLAB/PIC32MX/portmacro.h"#endif#ifdef _FEDPICC#include "libFreeRTOS/Include/portmacro.h"#endif#ifdef SDCC_CYGNAL#include "../../Source/portable/SDCC/Cygnal/portmacro.h"#endif#ifdef GCC_ARM7#include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h"#endif#ifdef GCC_ARM7_ECLIPSE#include "portmacro.h"#endif#ifdef ROWLEY_LPC23xx#include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h"#endif#ifdef IAR_MSP430#include "..\..\Source\portable\IAR\MSP430\portmacro.h"#endif#ifdef GCC_MSP430#include "../../Source/portable/GCC/MSP430F449/portmacro.h"#endif#ifdef ROWLEY_MSP430#include "../../Source/portable/Rowley/MSP430F449/portmacro.h"#endif#ifdef ARM7_LPC21xx_KEIL_RVDS#include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h"#endif#ifdef SAM7_GCC#include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h"#endif#ifdef SAM7_IAR#include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h"#endif#ifdef SAM9XE_IAR#include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h"#endif#ifdef LPC2000_IAR#include "..\..\Source\portable\IAR\LPC2000\portmacro.h"#endif#ifdef STR71X_IAR#include "..\..\Source\portable\IAR\STR71x\portmacro.h"#endif#ifdef STR75X_IAR#include "..\..\Source\portable\IAR\STR75x\portmacro.h"#endif#ifdef STR75X_GCC#include "..\..\Source\portable\GCC\STR75x\portmacro.h"#endif#ifdef STR91X_IAR#include "..\..\Source\portable\IAR\STR91x\portmacro.h"#endif#ifdef GCC_H8S#include "../../Source/portable/GCC/H8S2329/portmacro.h"#endif#ifdef GCC_AT91FR40008#include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h"#endif#ifdef RVDS_ARMCM3_LM3S102#include "../../Source/portable/RVDS/ARM_CM3/portmacro.h"#endif#ifdef GCC_ARMCM3_LM3S102#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"#endif#ifdef GCC_ARMCM3#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"#endif#ifdef IAR_ARM_CM3#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"#endif#ifdef IAR_ARMCM3_LM#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"#endif#ifdef HCS12_CODE_WARRIOR#include "../../Source/portable/CodeWarrior/HCS12/portmacro.h"#endif#ifdef MICROBLAZE_GCC#include "../../Source/portable/GCC/MicroBlaze/portmacro.h"#endif#ifdef TERN_EE#include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h"#endif#ifdef GCC_HCS12#include "../../Source/portable/GCC/HCS12/portmacro.h"#endif#ifdef GCC_MCF5235#include "../../Source/portable/GCC/MCF5235/portmacro.h"#endif#ifdef COLDFIRE_V2_GCC#include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h"#endif#ifdef COLDFIRE_V2_CODEWARRIOR#include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h"#endif#ifdef GCC_PPC405#include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h"#endif#ifdef GCC_PPC440#include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h"#endif#ifdef _16FX_SOFTUNE#include "..\..\Source\portable\Softune\MB96340\portmacro.h"#endif#ifdef BCC_INDUSTRIAL_PC_PORT/* A short file name has to be used in place of the normalFreeRTOSConfig.h when using the Borland compiler. */#include "frconfig.h"#include "..\portable\BCC\16BitDOS\PC\prtmacro.h"typedef void ( __interrupt __far *pxISR )();#endif#ifdef BCC_FLASH_LITE_186_PORT/* A short file name has to be used in place of the normalFreeRTOSConfig.h when using the Borland compiler. */#include "frconfig.h"#include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h"typedef void ( __interrupt __far *pxISR )();#endif#ifdef __GNUC__#ifdef __AVR32_AVR32A__#include "portmacro.h"#endif#endif#ifdef __ICCAVR32__#ifdef __CORE__#if __CORE__ == __AVR32A__#include "portmacro.h"#endif#endif#endif#ifdef __91467D#include "portmacro.h"#endif#ifdef __96340#include "portmacro.h"#endif#ifdef __IAR_V850ES_Fx3__#include "../../Source/portable/IAR/V850ES/portmacro.h"#endif#ifdef __IAR_V850ES_Jx3__#include "../../Source/portable/IAR/V850ES/portmacro.h"#endif#ifdef __IAR_V850ES_Jx3_L__#include "../../Source/portable/IAR/V850ES/portmacro.h"#endif#ifdef __IAR_V850ES_Jx2__#include "../../Source/portable/IAR/V850ES/portmacro.h"#endif#ifdef __IAR_V850ES_Hx2__#include "../../Source/portable/IAR/V850ES/portmacro.h"#endif#ifdef __IAR_78K0R_Kx3__#include "../../Source/portable/IAR/78K0R/portmacro.h"#endif#ifdef __IAR_78K0R_Kx3L__#include "../../Source/portable/IAR/78K0R/portmacro.h"#endif/* Catch all to ensure portmacro.h is included in the build. Newer demoshave the path as part of the project options, rather than as relative fromthe project location. If portENTER_CRITICAL() has not been defined thenportmacro.h has not yet been included - as every portmacro.h provides aportENTER_CRITICAL() definition. Check the demo application for your demoto find the path to the correct portmacro.h file. */#ifndef portENTER_CRITICAL#include "portmacro.h"#endif#if portBYTE_ALIGNMENT == 8#define portBYTE_ALIGNMENT_MASK ( 0x0007 )#endif#if portBYTE_ALIGNMENT == 4#define portBYTE_ALIGNMENT_MASK ( 0x0003 )#endif#if portBYTE_ALIGNMENT == 2#define portBYTE_ALIGNMENT_MASK ( 0x0001 )#endif#if portBYTE_ALIGNMENT == 1#define portBYTE_ALIGNMENT_MASK ( 0x0000 )#endif#ifndef portBYTE_ALIGNMENT_MASK#error "Invalid portBYTE_ALIGNMENT definition"#endif#ifndef portNUM_CONFIGURABLE_REGIONS#define portNUM_CONFIGURABLE_REGIONS 1#endif#ifdef __cplusplusextern "C" {#endif#include "mpu_wrappers.h"/** Setup the stack of a new task so it is ready to be placed under the* scheduler control. The registers have to be placed on the stack in* the order that the port expects to find them.**/#if( portUSING_MPU_WRAPPERS == 1 )portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters, portBASE_TYPE xRunPrivileged ) PRIVILEGED_FUNCTION;#elseportSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters ) PRIVILEGED_FUNCTION;#endif/** Map to the memory management routines required for the port.*/void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION;void vPortFree( void *pv ) PRIVILEGED_FUNCTION;void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION;size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION;/** Setup the hardware ready for the scheduler to take control. This generally* sets up a tick interrupt and sets timers for the correct tick frequency.*/portBASE_TYPE xPortStartScheduler( void ) PRIVILEGED_FUNCTION;/** Undo any hardware/ISR setup that was performed by xPortStartScheduler() so* the hardware is left in its original condition after the scheduler stops* executing.*/void vPortEndScheduler( void ) PRIVILEGED_FUNCTION;/** The structures and methods of manipulating the MPU are contained within the* port layer.** Fills the xMPUSettings structure with the memory region information* contained in xRegions.*/#if( portUSING_MPU_WRAPPERS == 1 )struct xMEMORY_REGION;void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, portSTACK_TYPE *pxBottomOfStack, unsigned short usStackDepth ) PRIVILEGED_FUNCTION;#endif#ifdef __cplusplus}#endif#endif /* PORTABLE_H */
123version https://git-lfs.github.com/spec/v1oid sha256:07c014cac6b10388057b4719a8b5e94e30deea4c8f847cd49d86c66ae622ce92size 42361234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef PROJDEFS_H#define PROJDEFS_H/* Defines the prototype to which task functions must conform. */typedef void (*pdTASK_CODE)( void * );#define pdFALSE ( ( portBASE_TYPE ) 0 )#define pdTRUE ( ( portBASE_TYPE ) 1 )#define pdPASS ( pdTRUE )#define pdFAIL ( pdFALSE )#define errQUEUE_EMPTY ( ( portBASE_TYPE ) 0 )#define errQUEUE_FULL ( ( portBASE_TYPE ) 0 )/* Error definitions. */#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 )#define errNO_TASK_TO_RUN ( -2 )#define errQUEUE_BLOCKED ( -4 )#define errQUEUE_YIELD ( -5 )#endif /* PROJDEFS_H */
123version https://git-lfs.github.com/spec/v1oid sha256:c41c69e0c9f4b9b771f8f982c860b1aad2d689011941b8dbe3bddc80f4c8fe63size 6290612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef QUEUE_H#define QUEUE_H#ifndef INC_FREERTOS_H#error "include FreeRTOS.h" must appear in source files before "include queue.h"#endif#ifdef __cplusplusextern "C" {#endif/*** Type by which queues are referenced. For example, a call to xQueueCreate()* returns an xQueueHandle variable that can then be used as a parameter to* xQueueSend(), xQueueReceive(), etc.*/typedef void * xQueueHandle;/*** Type by which queue sets are referenced. For example, a call to* xQueueCreateSet() returns an xQueueSet variable that can then be used as a* parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc.*/typedef void * xQueueSetHandle;/*** Queue sets can contain both queues and semaphores, so the* xQueueSetMemberHandle is defined as a type to be used where a parameter or* return value can be either an xQueueHandle or an xSemaphoreHandle.*/typedef void * xQueueSetMemberHandle;/* For internal use only. */#define queueSEND_TO_BACK ( ( portBASE_TYPE ) 0 )#define queueSEND_TO_FRONT ( ( portBASE_TYPE ) 1 )#define queueOVERWRITE ( ( portBASE_TYPE ) 2 )/* For internal use only. These definitions *must* match those in queue.c. */#define queueQUEUE_TYPE_BASE ( ( unsigned char ) 0U )#define queueQUEUE_TYPE_SET ( ( unsigned char ) 0U )#define queueQUEUE_TYPE_MUTEX ( ( unsigned char ) 1U )#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( unsigned char ) 2U )#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( unsigned char ) 3U )#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( unsigned char ) 4U )/*** queue. h* <pre>xQueueHandle xQueueCreate(unsigned portBASE_TYPE uxQueueLength,unsigned portBASE_TYPE uxItemSize);* </pre>** Creates a new queue instance. This allocates the storage required by the* new queue and returns a handle for the queue.** @param uxQueueLength The maximum number of items that the queue can contain.** @param uxItemSize The number of bytes each item in the queue will require.* Items are queued by copy, not by reference, so this is the number of bytes* that will be copied for each posted item. Each item on the queue must be* the same size.** @return If the queue is successfully create then a handle to the newly* created queue is returned. If the queue cannot be created then 0 is* returned.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];};void vATask( void *pvParameters ){xQueueHandle xQueue1, xQueue2;// Create a queue capable of containing 10 unsigned long values.xQueue1 = xQueueCreate( 10, sizeof( unsigned long ) );if( xQueue1 == 0 ){// Queue was not created and must not be used.}// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );if( xQueue2 == 0 ){// Queue was not created and must not be used.}// ... Rest of task code.}</pre>* \defgroup xQueueCreate xQueueCreate* \ingroup QueueManagement*/#define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( uxQueueLength, uxItemSize, queueQUEUE_TYPE_BASE )/*** queue. h* <pre>portBASE_TYPE xQueueSendToToFront(xQueueHandle xQueue,const void * pvItemToQueue,portTickType xTicksToWait);* </pre>** This is a macro that calls xQueueGenericSend().** Post an item to the front of a queue. The item is queued by copy, not by* reference. This function must not be called from an interrupt service* routine. See xQueueSendFromISR () for an alternative which may be used* in an ISR.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param xTicksToWait The maximum amount of time the task should block* waiting for space to become available on the queue, should it already* be full. The call will return immediately if this is set to 0 and the* queue is full. The time is defined in tick periods so the constant* portTICK_RATE_MS should be used to convert to real time if this is required.** @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;unsigned long ulVar = 10UL;void vATask( void *pvParameters ){xQueueHandle xQueue1, xQueue2;struct AMessage *pxMessage;// Create a queue capable of containing 10 unsigned long values.xQueue1 = xQueueCreate( 10, sizeof( unsigned long ) );// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );// ...if( xQueue1 != 0 ){// Send an unsigned long. Wait for 10 ticks for space to become// available if necessary.if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( portTickType ) 10 ) != pdPASS ){// Failed to post the message, even after 10 ticks.}}if( xQueue2 != 0 ){// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( portTickType ) 0 );}// ... Rest of task code.}</pre>* \defgroup xQueueSend xQueueSend* \ingroup QueueManagement*/#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )/*** queue. h* <pre>portBASE_TYPE xQueueSendToBack(xQueueHandle xQueue,const void * pvItemToQueue,portTickType xTicksToWait);* </pre>** This is a macro that calls xQueueGenericSend().** Post an item to the back of a queue. The item is queued by copy, not by* reference. This function must not be called from an interrupt service* routine. See xQueueSendFromISR () for an alternative which may be used* in an ISR.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param xTicksToWait The maximum amount of time the task should block* waiting for space to become available on the queue, should it already* be full. The call will return immediately if this is set to 0 and the queue* is full. The time is defined in tick periods so the constant* portTICK_RATE_MS should be used to convert to real time if this is required.** @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;unsigned long ulVar = 10UL;void vATask( void *pvParameters ){xQueueHandle xQueue1, xQueue2;struct AMessage *pxMessage;// Create a queue capable of containing 10 unsigned long values.xQueue1 = xQueueCreate( 10, sizeof( unsigned long ) );// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );// ...if( xQueue1 != 0 ){// Send an unsigned long. Wait for 10 ticks for space to become// available if necessary.if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( portTickType ) 10 ) != pdPASS ){// Failed to post the message, even after 10 ticks.}}if( xQueue2 != 0 ){// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( portTickType ) 0 );}// ... Rest of task code.}</pre>* \defgroup xQueueSend xQueueSend* \ingroup QueueManagement*/#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )/*** queue. h* <pre>portBASE_TYPE xQueueSend(xQueueHandle xQueue,const void * pvItemToQueue,portTickType xTicksToWait);* </pre>** This is a macro that calls xQueueGenericSend(). It is included for* backward compatibility with versions of FreeRTOS.org that did not* include the xQueueSendToFront() and xQueueSendToBack() macros. It is* equivalent to xQueueSendToBack().** Post an item on a queue. The item is queued by copy, not by reference.* This function must not be called from an interrupt service routine.* See xQueueSendFromISR () for an alternative which may be used in an ISR.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param xTicksToWait The maximum amount of time the task should block* waiting for space to become available on the queue, should it already* be full. The call will return immediately if this is set to 0 and the* queue is full. The time is defined in tick periods so the constant* portTICK_RATE_MS should be used to convert to real time if this is required.** @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;unsigned long ulVar = 10UL;void vATask( void *pvParameters ){xQueueHandle xQueue1, xQueue2;struct AMessage *pxMessage;// Create a queue capable of containing 10 unsigned long values.xQueue1 = xQueueCreate( 10, sizeof( unsigned long ) );// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );// ...if( xQueue1 != 0 ){// Send an unsigned long. Wait for 10 ticks for space to become// available if necessary.if( xQueueSend( xQueue1, ( void * ) &ulVar, ( portTickType ) 10 ) != pdPASS ){// Failed to post the message, even after 10 ticks.}}if( xQueue2 != 0 ){// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueSend( xQueue2, ( void * ) &pxMessage, ( portTickType ) 0 );}// ... Rest of task code.}</pre>* \defgroup xQueueSend xQueueSend* \ingroup QueueManagement*/#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )/*** queue. h* <pre>portBASE_TYPE xQueueOverwrite(xQueueHandle xQueue,const void * pvItemToQueue);* </pre>** Only for use with queues that have a length of one - so the queue is either* empty or full.** Post an item on a queue. If the queue is already full then overwrite the* value held in the queue. The item is queued by copy, not by reference.** This function must not be called from an interrupt service routine.* See xQueueOverwriteFromISR () for an alternative which may be used in an ISR.** @param xQueue The handle of the queue to which the data is being sent.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and* therefore has the same return values as xQueueSendToFront(). However, pdPASS* is the only value that can be returned because xQueueOverwrite() will write* to the queue even when the queue is already full.** Example usage:<pre>void vFunction( void *pvParameters ){xQueueHandle xQueue;unsigned long ulVarToSend, ulValReceived;// Create a queue to hold one unsigned long value. It is strongly// recommended *not* to use xQueueOverwrite() on queues that can// contain more than one value, and doing so will trigger an assertion// if configASSERT() is defined.xQueue = xQueueCreate( 1, sizeof( unsigned long ) );// Write the value 10 to the queue using xQueueOverwrite().ulVarToSend = 10;xQueueOverwrite( xQueue, &ulVarToSend );// Peeking the queue should now return 10, but leave the value 10 in// the queue. A block time of zero is used as it is known that the// queue holds a value.ulValReceived = 0;xQueuePeek( xQueue, &ulValReceived, 0 );if( ulValReceived != 10 ){// Error unless the item was removed by a different task.}// The queue is still full. Use xQueueOverwrite() to overwrite the// value held in the queue with 100.ulVarToSend = 100;xQueueOverwrite( xQueue, &ulVarToSend );// This time read from the queue, leaving the queue empty once more.// A block time of 0 is used again.xQueueReceive( xQueue, &ulValReceived, 0 );// The value read should be the last value written, even though the// queue was already full when the value was written.if( ulValReceived != 100 ){// Error!}// ...}</pre>* \defgroup xQueueOverwrite xQueueOverwrite* \ingroup QueueManagement*/#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE )/*** queue. h* <pre>portBASE_TYPE xQueueGenericSend(xQueueHandle xQueue,const void * pvItemToQueue,portTickType xTicksToWaitportBASE_TYPE xCopyPosition);* </pre>** It is preferred that the macros xQueueSend(), xQueueSendToFront() and* xQueueSendToBack() are used in place of calling this function directly.** Post an item on a queue. The item is queued by copy, not by reference.* This function must not be called from an interrupt service routine.* See xQueueSendFromISR () for an alternative which may be used in an ISR.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param xTicksToWait The maximum amount of time the task should block* waiting for space to become available on the queue, should it already* be full. The call will return immediately if this is set to 0 and the* queue is full. The time is defined in tick periods so the constant* portTICK_RATE_MS should be used to convert to real time if this is required.** @param xCopyPosition Can take the value queueSEND_TO_BACK to place the* item at the back of the queue, or queueSEND_TO_FRONT to place the item* at the front of the queue (for high priority messages).** @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;unsigned long ulVar = 10UL;void vATask( void *pvParameters ){xQueueHandle xQueue1, xQueue2;struct AMessage *pxMessage;// Create a queue capable of containing 10 unsigned long values.xQueue1 = xQueueCreate( 10, sizeof( unsigned long ) );// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );// ...if( xQueue1 != 0 ){// Send an unsigned long. Wait for 10 ticks for space to become// available if necessary.if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( portTickType ) 10, queueSEND_TO_BACK ) != pdPASS ){// Failed to post the message, even after 10 ticks.}}if( xQueue2 != 0 ){// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( portTickType ) 0, queueSEND_TO_BACK );}// ... Rest of task code.}</pre>* \defgroup xQueueSend xQueueSend* \ingroup QueueManagement*/signed portBASE_TYPE xQueueGenericSend( xQueueHandle xQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>portBASE_TYPE xQueuePeek(xQueueHandle xQueue,void *pvBuffer,portTickType xTicksToWait);</pre>** This is a macro that calls the xQueueGenericReceive() function.** Receive an item from a queue without removing the item from the queue.* The item is received by copy so a buffer of adequate size must be* provided. The number of bytes copied into the buffer was defined when* the queue was created.** Successfully received items remain on the queue so will be returned again* by the next call, or a call to xQueueReceive().** This macro must not be used in an interrupt service routine. See* xQueuePeekFromISR() for an alternative that can be called from an interrupt* service routine.** @param xQueue The handle to the queue from which the item is to be* received.** @param pvBuffer Pointer to the buffer into which the received item will* be copied.** @param xTicksToWait The maximum amount of time the task should block* waiting for an item to receive should the queue be empty at the time* of the call. The time is defined in tick periods so the constant* portTICK_RATE_MS should be used to convert to real time if this is required.* xQueuePeek() will return immediately if xTicksToWait is 0 and the queue* is empty.** @return pdTRUE if an item was successfully received from the queue,* otherwise pdFALSE.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;xQueueHandle xQueue;// Task to create a queue and post a value.void vATask( void *pvParameters ){struct AMessage *pxMessage;// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );if( xQueue == 0 ){// Failed to create the queue.}// ...// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueSend( xQueue, ( void * ) &pxMessage, ( portTickType ) 0 );// ... Rest of task code.}// Task to peek the data from the queue.void vADifferentTask( void *pvParameters ){struct AMessage *pxRxedMessage;if( xQueue != 0 ){// Peek a message on the created queue. Block for 10 ticks if a// message is not immediately available.if( xQueuePeek( xQueue, &( pxRxedMessage ), ( portTickType ) 10 ) ){// pcRxedMessage now points to the struct AMessage variable posted// by vATask, but the item still remains on the queue.}}// ... Rest of task code.}</pre>* \defgroup xQueueReceive xQueueReceive* \ingroup QueueManagement*/#define xQueuePeek( xQueue, pvBuffer, xTicksToWait ) xQueueGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdTRUE )/*** queue. h* <pre>portBASE_TYPE xQueuePeekFromISR(xQueueHandle xQueue,void *pvBuffer,);</pre>** A version of xQueuePeek() that can be called from an interrupt service* routine (ISR).** Receive an item from a queue without removing the item from the queue.* The item is received by copy so a buffer of adequate size must be* provided. The number of bytes copied into the buffer was defined when* the queue was created.** Successfully received items remain on the queue so will be returned again* by the next call, or a call to xQueueReceive().** @param xQueue The handle to the queue from which the item is to be* received.** @param pvBuffer Pointer to the buffer into which the received item will* be copied.** @return pdTRUE if an item was successfully received from the queue,* otherwise pdFALSE.** \defgroup xQueuePeekFromISR xQueuePeekFromISR* \ingroup QueueManagement*/signed portBASE_TYPE xQueuePeekFromISR( xQueueHandle xQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>portBASE_TYPE xQueueReceive(xQueueHandle xQueue,void *pvBuffer,portTickType xTicksToWait);</pre>** This is a macro that calls the xQueueGenericReceive() function.** Receive an item from a queue. The item is received by copy so a buffer of* adequate size must be provided. The number of bytes copied into the buffer* was defined when the queue was created.** Successfully received items are removed from the queue.** This function must not be used in an interrupt service routine. See* xQueueReceiveFromISR for an alternative that can.** @param xQueue The handle to the queue from which the item is to be* received.** @param pvBuffer Pointer to the buffer into which the received item will* be copied.** @param xTicksToWait The maximum amount of time the task should block* waiting for an item to receive should the queue be empty at the time* of the call. xQueueReceive() will return immediately if xTicksToWait* is zero and the queue is empty. The time is defined in tick periods so the* constant portTICK_RATE_MS should be used to convert to real time if this is* required.** @return pdTRUE if an item was successfully received from the queue,* otherwise pdFALSE.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;xQueueHandle xQueue;// Task to create a queue and post a value.void vATask( void *pvParameters ){struct AMessage *pxMessage;// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );if( xQueue == 0 ){// Failed to create the queue.}// ...// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueSend( xQueue, ( void * ) &pxMessage, ( portTickType ) 0 );// ... Rest of task code.}// Task to receive from the queue.void vADifferentTask( void *pvParameters ){struct AMessage *pxRxedMessage;if( xQueue != 0 ){// Receive a message on the created queue. Block for 10 ticks if a// message is not immediately available.if( xQueueReceive( xQueue, &( pxRxedMessage ), ( portTickType ) 10 ) ){// pcRxedMessage now points to the struct AMessage variable posted// by vATask.}}// ... Rest of task code.}</pre>* \defgroup xQueueReceive xQueueReceive* \ingroup QueueManagement*/#define xQueueReceive( xQueue, pvBuffer, xTicksToWait ) xQueueGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdFALSE )/*** queue. h* <pre>portBASE_TYPE xQueueGenericReceive(xQueueHandle xQueue,void *pvBuffer,portTickType xTicksToWaitportBASE_TYPE xJustPeek);</pre>** It is preferred that the macro xQueueReceive() be used rather than calling* this function directly.** Receive an item from a queue. The item is received by copy so a buffer of* adequate size must be provided. The number of bytes copied into the buffer* was defined when the queue was created.** This function must not be used in an interrupt service routine. See* xQueueReceiveFromISR for an alternative that can.** @param xQueue The handle to the queue from which the item is to be* received.** @param pvBuffer Pointer to the buffer into which the received item will* be copied.** @param xTicksToWait The maximum amount of time the task should block* waiting for an item to receive should the queue be empty at the time* of the call. The time is defined in tick periods so the constant* portTICK_RATE_MS should be used to convert to real time if this is required.* xQueueGenericReceive() will return immediately if the queue is empty and* xTicksToWait is 0.** @param xJustPeek When set to true, the item received from the queue is not* actually removed from the queue - meaning a subsequent call to* xQueueReceive() will return the same item. When set to false, the item* being received from the queue is also removed from the queue.** @return pdTRUE if an item was successfully received from the queue,* otherwise pdFALSE.** Example usage:<pre>struct AMessage{char ucMessageID;char ucData[ 20 ];} xMessage;xQueueHandle xQueue;// Task to create a queue and post a value.void vATask( void *pvParameters ){struct AMessage *pxMessage;// Create a queue capable of containing 10 pointers to AMessage structures.// These should be passed by pointer as they contain a lot of data.xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );if( xQueue == 0 ){// Failed to create the queue.}// ...// Send a pointer to a struct AMessage object. Don't block if the// queue is already full.pxMessage = & xMessage;xQueueSend( xQueue, ( void * ) &pxMessage, ( portTickType ) 0 );// ... Rest of task code.}// Task to receive from the queue.void vADifferentTask( void *pvParameters ){struct AMessage *pxRxedMessage;if( xQueue != 0 ){// Receive a message on the created queue. Block for 10 ticks if a// message is not immediately available.if( xQueueGenericReceive( xQueue, &( pxRxedMessage ), ( portTickType ) 10 ) ){// pcRxedMessage now points to the struct AMessage variable posted// by vATask.}}// ... Rest of task code.}</pre>* \defgroup xQueueReceive xQueueReceive* \ingroup QueueManagement*/signed portBASE_TYPE xQueueGenericReceive( xQueueHandle xQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeek ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>unsigned portBASE_TYPE uxQueueMessagesWaiting( const xQueueHandle xQueue );</pre>** Return the number of messages stored in a queue.** @param xQueue A handle to the queue being queried.** @return The number of messages available in the queue.** \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting* \ingroup QueueManagement*/unsigned portBASE_TYPE uxQueueMessagesWaiting( const xQueueHandle xQueue ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>unsigned portBASE_TYPE uxQueueSpacesAvailable( const xQueueHandle xQueue );</pre>** Return the number of free spaces available in a queue. This is equal to the* number of items that can be sent to the queue before the queue becomes full* if no items are removed.** @param xQueue A handle to the queue being queried.** @return The number of spaces available in the queue.** \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting* \ingroup QueueManagement*/unsigned portBASE_TYPE uxQueueSpacesAvailable( const xQueueHandle xQueue ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>void vQueueDelete( xQueueHandle xQueue );</pre>** Delete a queue - freeing all the memory allocated for storing of items* placed on the queue.** @param xQueue A handle to the queue to be deleted.** \defgroup vQueueDelete vQueueDelete* \ingroup QueueManagement*/void vQueueDelete( xQueueHandle xQueue ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>portBASE_TYPE xQueueSendToFrontFromISR(xQueueHandle xQueue,const void *pvItemToQueue,portBASE_TYPE *pxHigherPriorityTaskWoken);</pre>** This is a macro that calls xQueueGenericSendFromISR().** Post an item to the front of a queue. It is safe to use this macro from* within an interrupt service routine.** Items are queued by copy not reference so it is preferable to only* queue small items, especially when called from an ISR. In most cases* it would be preferable to store a pointer to the item being queued.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @return pdTRUE if the data was successfully sent to the queue, otherwise* errQUEUE_FULL.** Example usage for buffered IO (where the ISR can obtain more than one value* per call):<pre>void vBufferISR( void ){char cIn;portBASE_TYPE xHigherPrioritTaskWoken;// We have not woken a task at the start of the ISR.xHigherPriorityTaskWoken = pdFALSE;// Loop until the buffer is empty.do{// Obtain a byte from the buffer.cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );// Post the byte.xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );} while( portINPUT_BYTE( BUFFER_COUNT ) );// Now the buffer is empty we can switch context if necessary.if( xHigherPriorityTaskWoken ){taskYIELD ();}}</pre>** \defgroup xQueueSendFromISR xQueueSendFromISR* \ingroup QueueManagement*/#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT )/*** queue. h* <pre>portBASE_TYPE xQueueSendToBackFromISR(xQueueHandle xQueue,const void *pvItemToQueue,portBASE_TYPE *pxHigherPriorityTaskWoken);</pre>** This is a macro that calls xQueueGenericSendFromISR().** Post an item to the back of a queue. It is safe to use this macro from* within an interrupt service routine.** Items are queued by copy not reference so it is preferable to only* queue small items, especially when called from an ISR. In most cases* it would be preferable to store a pointer to the item being queued.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @return pdTRUE if the data was successfully sent to the queue, otherwise* errQUEUE_FULL.** Example usage for buffered IO (where the ISR can obtain more than one value* per call):<pre>void vBufferISR( void ){char cIn;portBASE_TYPE xHigherPriorityTaskWoken;// We have not woken a task at the start of the ISR.xHigherPriorityTaskWoken = pdFALSE;// Loop until the buffer is empty.do{// Obtain a byte from the buffer.cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );// Post the byte.xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );} while( portINPUT_BYTE( BUFFER_COUNT ) );// Now the buffer is empty we can switch context if necessary.if( xHigherPriorityTaskWoken ){taskYIELD ();}}</pre>** \defgroup xQueueSendFromISR xQueueSendFromISR* \ingroup QueueManagement*/#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )/*** queue. h* <pre>portBASE_TYPE xQueueOverwriteFromISR(xQueueHandle xQueue,const void * pvItemToQueue,portBASE_TYPE *pxHigherPriorityTaskWoken);* </pre>** A version of xQueueOverwrite() that can be used in an interrupt service* routine (ISR).** Only for use with queues that can hold a single item - so the queue is either* empty or full.** Post an item on a queue. If the queue is already full then overwrite the* value held in the queue. The item is queued by copy, not by reference.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @return xQueueOverwriteFromISR() is a macro that calls* xQueueGenericSendFromISR(), and therefore has the same return values as* xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be* returned because xQueueOverwriteFromISR() will write to the queue even when* the queue is already full.** Example usage:<pre>xQueueHandle xQueue;void vFunction( void *pvParameters ){// Create a queue to hold one unsigned long value. It is strongly// recommended *not* to use xQueueOverwriteFromISR() on queues that can// contain more than one value, and doing so will trigger an assertion// if configASSERT() is defined.xQueue = xQueueCreate( 1, sizeof( unsigned long ) );}void vAnInterruptHandler( void ){// xHigherPriorityTaskWoken must be set to pdFALSE before it is used.portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;unsigned long ulVarToSend, ulValReceived;// Write the value 10 to the queue using xQueueOverwriteFromISR().ulVarToSend = 10;xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );// The queue is full, but calling xQueueOverwriteFromISR() again will still// pass because the value held in the queue will be overwritten with the// new value.ulVarToSend = 100;xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );// Reading from the queue will now return 100.// ...if( xHigherPrioritytaskWoken == pdTRUE ){// Writing to the queue caused a task to unblock and the unblocked task// has a priority higher than or equal to the priority of the currently// executing task (the task this interrupt interrupted). Perform a context// switch so this interrupt returns directly to the unblocked task.portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port.}}</pre>* \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR* \ingroup QueueManagement*/#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE )/*** queue. h* <pre>portBASE_TYPE xQueueSendFromISR(xQueueHandle xQueue,const void *pvItemToQueue,portBASE_TYPE *pxHigherPriorityTaskWoken);</pre>** This is a macro that calls xQueueGenericSendFromISR(). It is included* for backward compatibility with versions of FreeRTOS.org that did not* include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR()* macros.** Post an item to the back of a queue. It is safe to use this function from* within an interrupt service routine.** Items are queued by copy not reference so it is preferable to only* queue small items, especially when called from an ISR. In most cases* it would be preferable to store a pointer to the item being queued.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param pxHigherPriorityTaskWoken xQueueSendFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xQueueSendFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @return pdTRUE if the data was successfully sent to the queue, otherwise* errQUEUE_FULL.** Example usage for buffered IO (where the ISR can obtain more than one value* per call):<pre>void vBufferISR( void ){char cIn;portBASE_TYPE xHigherPriorityTaskWoken;// We have not woken a task at the start of the ISR.xHigherPriorityTaskWoken = pdFALSE;// Loop until the buffer is empty.do{// Obtain a byte from the buffer.cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );// Post the byte.xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );} while( portINPUT_BYTE( BUFFER_COUNT ) );// Now the buffer is empty we can switch context if necessary.if( xHigherPriorityTaskWoken ){// Actual macro used here is port specific.portYIELD_FROM_ISR ();}}</pre>** \defgroup xQueueSendFromISR xQueueSendFromISR* \ingroup QueueManagement*/#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )/*** queue. h* <pre>portBASE_TYPE xQueueGenericSendFromISR(xQueueHandle xQueue,const void *pvItemToQueue,portBASE_TYPE *pxHigherPriorityTaskWoken,portBASE_TYPE xCopyPosition);</pre>** It is preferred that the macros xQueueSendFromISR(),* xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place* of calling this function directly.** Post an item on a queue. It is safe to use this function from within an* interrupt service routine.** Items are queued by copy not reference so it is preferable to only* queue small items, especially when called from an ISR. In most cases* it would be preferable to store a pointer to the item being queued.** @param xQueue The handle to the queue on which the item is to be posted.** @param pvItemToQueue A pointer to the item that is to be placed on the* queue. The size of the items the queue will hold was defined when the* queue was created, so this many bytes will be copied from pvItemToQueue* into the queue storage area.** @param pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @param xCopyPosition Can take the value queueSEND_TO_BACK to place the* item at the back of the queue, or queueSEND_TO_FRONT to place the item* at the front of the queue (for high priority messages).** @return pdTRUE if the data was successfully sent to the queue, otherwise* errQUEUE_FULL.** Example usage for buffered IO (where the ISR can obtain more than one value* per call):<pre>void vBufferISR( void ){char cIn;portBASE_TYPE xHigherPriorityTaskWokenByPost;// We have not woken a task at the start of the ISR.xHigherPriorityTaskWokenByPost = pdFALSE;// Loop until the buffer is empty.do{// Obtain a byte from the buffer.cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );// Post each byte.xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK );} while( portINPUT_BYTE( BUFFER_COUNT ) );// Now the buffer is empty we can switch context if necessary. Note that the// name of the yield function required is port specific.if( xHigherPriorityTaskWokenByPost ){taskYIELD_YIELD_FROM_ISR();}}</pre>** \defgroup xQueueSendFromISR xQueueSendFromISR* \ingroup QueueManagement*/signed portBASE_TYPE xQueueGenericSendFromISR( xQueueHandle xQueue, const void * const pvItemToQueue, signed portBASE_TYPE *pxHigherPriorityTaskWoken, portBASE_TYPE xCopyPosition ) PRIVILEGED_FUNCTION;/*** queue. h* <pre>portBASE_TYPE xQueueReceiveFromISR(xQueueHandle xQueue,void *pvBuffer,portBASE_TYPE *pxTaskWoken);* </pre>** Receive an item from a queue. It is safe to use this function from within an* interrupt service routine.** @param xQueue The handle to the queue from which the item is to be* received.** @param pvBuffer Pointer to the buffer into which the received item will* be copied.** @param pxTaskWoken A task may be blocked waiting for space to become* available on the queue. If xQueueReceiveFromISR causes such a task to* unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will* remain unchanged.** @return pdTRUE if an item was successfully received from the queue,* otherwise pdFALSE.** Example usage:<pre>xQueueHandle xQueue;// Function to create a queue and post some values.void vAFunction( void *pvParameters ){char cValueToPost;const portTickType xBlockTime = ( portTickType )0xff;// Create a queue capable of containing 10 characters.xQueue = xQueueCreate( 10, sizeof( char ) );if( xQueue == 0 ){// Failed to create the queue.}// ...// Post some characters that will be used within an ISR. If the queue// is full then this task will block for xBlockTime ticks.cValueToPost = 'a';xQueueSend( xQueue, ( void * ) &cValueToPost, xBlockTime );cValueToPost = 'b';xQueueSend( xQueue, ( void * ) &cValueToPost, xBlockTime );// ... keep posting characters ... this task may block when the queue// becomes full.cValueToPost = 'c';xQueueSend( xQueue, ( void * ) &cValueToPost, xBlockTime );}// ISR that outputs all the characters received on the queue.void vISR_Routine( void ){portBASE_TYPE xTaskWokenByReceive = pdFALSE;char cRxedChar;while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ){// A character was received. Output the character now.vOutputCharacter( cRxedChar );// If removing the character from the queue woke the task that was// posting onto the queue cTaskWokenByReceive will have been set to// pdTRUE. No matter how many times this loop iterates only one// task will be woken.}if( cTaskWokenByPost != ( char ) pdFALSE;{taskYIELD ();}}</pre>* \defgroup xQueueReceiveFromISR xQueueReceiveFromISR* \ingroup QueueManagement*/signed portBASE_TYPE xQueueReceiveFromISR( xQueueHandle xQueue, void * const pvBuffer, signed portBASE_TYPE *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;/** Utilities to query queues that are safe to use from an ISR. These utilities* should be used only from witin an ISR, or within a critical section.*/signed portBASE_TYPE xQueueIsQueueEmptyFromISR( const xQueueHandle xQueue ) PRIVILEGED_FUNCTION;signed portBASE_TYPE xQueueIsQueueFullFromISR( const xQueueHandle xQueue ) PRIVILEGED_FUNCTION;unsigned portBASE_TYPE uxQueueMessagesWaitingFromISR( const xQueueHandle xQueue ) PRIVILEGED_FUNCTION;/** xQueueAltGenericSend() is an alternative version of xQueueGenericSend().* Likewise xQueueAltGenericReceive() is an alternative version of* xQueueGenericReceive().** The source code that implements the alternative (Alt) API is much* simpler because it executes everything from within a critical section.* This is the approach taken by many other RTOSes, but FreeRTOS.org has the* preferred fully featured API too. The fully featured API has more* complex code that takes longer to execute, but makes much less use of* critical sections. Therefore the alternative API sacrifices interrupt* responsiveness to gain execution speed, whereas the fully featured API* sacrifices execution speed to ensure better interrupt responsiveness.*/signed portBASE_TYPE xQueueAltGenericSend( xQueueHandle xQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition );signed portBASE_TYPE xQueueAltGenericReceive( xQueueHandle xQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking );#define xQueueAltSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueAltGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )#define xQueueAltSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueAltGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )#define xQueueAltReceive( xQueue, pvBuffer, xTicksToWait ) xQueueAltGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdFALSE )#define xQueueAltPeek( xQueue, pvBuffer, xTicksToWait ) xQueueAltGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdTRUE )/** The functions defined above are for passing data to and from tasks. The* functions below are the equivalents for passing data to and from* co-routines.** These functions are called from the co-routine macro implementation and* should not be called directly from application code. Instead use the macro* wrappers defined within croutine.h.*/signed portBASE_TYPE xQueueCRSendFromISR( xQueueHandle xQueue, const void *pvItemToQueue, signed portBASE_TYPE xCoRoutinePreviouslyWoken );signed portBASE_TYPE xQueueCRReceiveFromISR( xQueueHandle xQueue, void *pvBuffer, signed portBASE_TYPE *pxTaskWoken );signed portBASE_TYPE xQueueCRSend( xQueueHandle xQueue, const void *pvItemToQueue, portTickType xTicksToWait );signed portBASE_TYPE xQueueCRReceive( xQueueHandle xQueue, void *pvBuffer, portTickType xTicksToWait );/** For internal use only. Use xSemaphoreCreateMutex(),* xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling* these functions directly.*/xQueueHandle xQueueCreateMutex( unsigned char ucQueueType ) PRIVILEGED_FUNCTION;xQueueHandle xQueueCreateCountingSemaphore( unsigned portBASE_TYPE uxMaxCount, unsigned portBASE_TYPE uxInitialCount ) PRIVILEGED_FUNCTION;void* xQueueGetMutexHolder( xQueueHandle xSemaphore ) PRIVILEGED_FUNCTION;/** For internal use only. Use xSemaphoreTakeMutexRecursive() or* xSemaphoreGiveMutexRecursive() instead of calling these functions directly.*/portBASE_TYPE xQueueTakeMutexRecursive( xQueueHandle xMutex, portTickType xBlockTime ) PRIVILEGED_FUNCTION;portBASE_TYPE xQueueGiveMutexRecursive( xQueueHandle pxMutex ) PRIVILEGED_FUNCTION;/** Reset a queue back to its original empty state. pdPASS is returned if the* queue is successfully reset. pdFAIL is returned if the queue could not be* reset because there are tasks blocked on the queue waiting to either* receive from the queue or send to the queue.*/#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE )/** The registry is provided as a means for kernel aware debuggers to* locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add* a queue, semaphore or mutex handle to the registry if you want the handle* to be available to a kernel aware debugger. If you are not using a kernel* aware debugger then this function can be ignored.** configQUEUE_REGISTRY_SIZE defines the maximum number of handles the* registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0* within FreeRTOSConfig.h for the registry to be available. Its value* does not effect the number of queues, semaphores and mutexes that can be* created - just the number that the registry can hold.** @param xQueue The handle of the queue being added to the registry. This* is the handle returned by a call to xQueueCreate(). Semaphore and mutex* handles can also be passed in here.** @param pcName The name to be associated with the handle. This is the* name that the kernel aware debugger will display.*/#if configQUEUE_REGISTRY_SIZE > 0void vQueueAddToRegistry( xQueueHandle xQueue, signed char *pcName ) PRIVILEGED_FUNCTION;#endif/** The registry is provided as a means for kernel aware debuggers to* locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add* a queue, semaphore or mutex handle to the registry if you want the handle* to be available to a kernel aware debugger, and vQueueUnregisterQueue() to* remove the queue, semaphore or mutex from the register. If you are not using* a kernel aware debugger then this function can be ignored.** @param xQueue The handle of the queue being removed from the registry.*/#if configQUEUE_REGISTRY_SIZE > 0void vQueueUnregisterQueue( xQueueHandle xQueue ) PRIVILEGED_FUNCTION;#endif/** Generic version of the queue creation function, which is in turn called by* any queue, semaphore or mutex creation function or macro.*/xQueueHandle xQueueGenericCreate( unsigned portBASE_TYPE uxQueueLength, unsigned portBASE_TYPE uxItemSize, unsigned char ucQueueType ) PRIVILEGED_FUNCTION;/** Queue sets provide a mechanism to allow a task to block (pend) on a read* operation from multiple queues or semaphores simultaneously.** See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this* function.** A queue set must be explicitly created using a call to xQueueCreateSet()* before it can be used. Once created, standard FreeRTOS queues and semaphores* can be added to the set using calls to xQueueAddToSet().* xQueueSelectFromSet() is then used to determine which, if any, of the queues* or semaphores contained in the set is in a state where a queue read or* semaphore take operation would be successful.** Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html* for reasons why queue sets are very rarely needed in practice as there are* simpler methods of blocking on multiple objects.** Note 2: Blocking on a queue set that contains a mutex will not cause the* mutex holder to inherit the priority of the blocked task.** Note 3: An additional 4 bytes of RAM is required for each space in a every* queue added to a queue set. Therefore counting semaphores that have a high* maximum count value should not be added to a queue set.** Note 4: A receive (in the case of a queue) or take (in the case of a* semaphore) operation must not be performed on a member of a queue set unless* a call to xQueueSelectFromSet() has first returned a handle to that set member.** @param uxEventQueueLength Queue sets store events that occur on* the queues and semaphores contained in the set. uxEventQueueLength specifies* the maximum number of events that can be queued at once. To be absolutely* certain that events are not lost uxEventQueueLength should be set to the* total sum of the length of the queues added to the set, where binary* semaphores and mutexes have a length of 1, and counting semaphores have a* length set by their maximum count value. Examples:* + If a queue set is to hold a queue of length 5, another queue of length 12,* and a binary semaphore, then uxEventQueueLength should be set to* (5 + 12 + 1), or 18.* + If a queue set is to hold three binary semaphores then uxEventQueueLength* should be set to (1 + 1 + 1 ), or 3.* + If a queue set is to hold a counting semaphore that has a maximum count of* 5, and a counting semaphore that has a maximum count of 3, then* uxEventQueueLength should be set to (5 + 3), or 8.** @return If the queue set is created successfully then a handle to the created* queue set is returned. Otherwise NULL is returned.*/xQueueSetHandle xQueueCreateSet( unsigned portBASE_TYPE uxEventQueueLength ) PRIVILEGED_FUNCTION;/** Adds a queue or semaphore to a queue set that was previously created by a* call to xQueueCreateSet().** See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this* function.** Note 1: A receive (in the case of a queue) or take (in the case of a* semaphore) operation must not be performed on a member of a queue set unless* a call to xQueueSelectFromSet() has first returned a handle to that set member.** @param xQueueOrSemaphore The handle of the queue or semaphore being added to* the queue set (cast to an xQueueSetMemberHandle type).** @param xQueueSet The handle of the queue set to which the queue or semaphore* is being added.** @return If the queue or semaphore was successfully added to the queue set* then pdPASS is returned. If the queue could not be successfully added to the* queue set because it is already a member of a different queue set then pdFAIL* is returned.*/portBASE_TYPE xQueueAddToSet( xQueueSetMemberHandle xQueueOrSemaphore, xQueueSetHandle xQueueSet ) PRIVILEGED_FUNCTION;/** Removes a queue or semaphore from a queue set. A queue or semaphore can only* be removed from a set if the queue or semaphore is empty.** See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this* function.** @param xQueueOrSemaphore The handle of the queue or semaphore being removed* from the queue set (cast to an xQueueSetMemberHandle type).** @param xQueueSet The handle of the queue set in which the queue or semaphore* is included.** @return If the queue or semaphore was successfully removed from the queue set* then pdPASS is returned. If the queue was not in the queue set, or the* queue (or semaphore) was not empty, then pdFAIL is returned.*/portBASE_TYPE xQueueRemoveFromSet( xQueueSetMemberHandle xQueueOrSemaphore, xQueueSetHandle xQueueSet ) PRIVILEGED_FUNCTION;/** xQueueSelectFromSet() selects from the members of a queue set a queue or* semaphore that either contains data (in the case of a queue) or is available* to take (in the case of a semaphore). xQueueSelectFromSet() effectively* allows a task to block (pend) on a read operation on all the queues and* semaphores in a queue set simultaneously.** See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this* function.** Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html* for reasons why queue sets are very rarely needed in practice as there are* simpler methods of blocking on multiple objects.** Note 2: Blocking on a queue set that contains a mutex will not cause the* mutex holder to inherit the priority of the blocked task.** Note 3: A receive (in the case of a queue) or take (in the case of a* semaphore) operation must not be performed on a member of a queue set unless* a call to xQueueSelectFromSet() has first returned a handle to that set member.** @param xQueueSet The queue set on which the task will (potentially) block.** @param xBlockTimeTicks The maximum time, in ticks, that the calling task will* remain in the Blocked state (with other tasks executing) to wait for a member* of the queue set to be ready for a successful queue read or semaphore take* operation.** @return xQueueSelectFromSet() will return the handle of a queue (cast to* a xQueueSetMemberHandle type) contained in the queue set that contains data,* or the handle of a semaphore (cast to a xQueueSetMemberHandle type) contained* in the queue set that is available, or NULL if no such queue or semaphore* exists before before the specified block time expires.*/xQueueSetMemberHandle xQueueSelectFromSet( xQueueSetHandle xQueueSet, portTickType xBlockTimeTicks ) PRIVILEGED_FUNCTION;/** A version of xQueueSelectFromSet() that can be used from an ISR.*/xQueueSetMemberHandle xQueueSelectFromSetFromISR( xQueueSetHandle xQueueSet ) PRIVILEGED_FUNCTION;/* Not public API functions. */void vQueueWaitForMessageRestricted( xQueueHandle xQueue, portTickType xTicksToWait ) PRIVILEGED_FUNCTION;portBASE_TYPE xQueueGenericReset( xQueueHandle xQueue, portBASE_TYPE xNewQueue ) PRIVILEGED_FUNCTION;void vQueueSetQueueNumber( xQueueHandle xQueue, unsigned char ucQueueNumber ) PRIVILEGED_FUNCTION;unsigned char ucQueueGetQueueNumber( xQueueHandle xQueue ) PRIVILEGED_FUNCTION;unsigned char ucQueueGetQueueType( xQueueHandle xQueue ) PRIVILEGED_FUNCTION;#ifdef __cplusplus}#endif#endif /* QUEUE_H */
123version https://git-lfs.github.com/spec/v1oid sha256:5c02f022d2f7fcb7572bbbb3bc8a392426dfcb76c1a7bc8b68969bebd28bbf52size 33928123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef SEMAPHORE_H#define SEMAPHORE_H#ifndef INC_FREERTOS_H#error "include FreeRTOS.h" must appear in source files before "include semphr.h"#endif#include "queue.h"typedef xQueueHandle xSemaphoreHandle;#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( unsigned char ) 1U )#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( unsigned char ) 0U )#define semGIVE_BLOCK_TIME ( ( portTickType ) 0U )/*** semphr. h* <pre>vSemaphoreCreateBinary( xSemaphoreHandle xSemaphore )</pre>** This old vSemaphoreCreateBinary() macro is now deprecated in favour of the* xSemaphoreCreateBinary() function. Note that binary semaphores created using* the vSemaphoreCreateBinary() macro are created in a state such that the* first call to 'take' the semaphore would pass, whereas binary semaphores* created using xSemaphoreCreateBinary() are created in a state such that the* the semaphore must first be 'given' before it can be 'taken'.** <i>Macro</i> that implements a semaphore by using the existing queue mechanism.* The queue length is 1 as this is a binary semaphore. The data size is 0* as we don't want to actually store any data - we just want to know if the* queue is empty or full.** This type of semaphore can be used for pure synchronisation between tasks or* between an interrupt and a task. The semaphore need not be given back once* obtained, so one task/interrupt can continuously 'give' the semaphore while* another continuously 'takes' the semaphore. For this reason this type of* semaphore does not use a priority inheritance mechanism. For an alternative* that does use priority inheritance see xSemaphoreCreateMutex().** @param xSemaphore Handle to the created semaphore. Should be of type xSemaphoreHandle.** Example usage:<pre>xSemaphoreHandle xSemaphore = NULL;void vATask( void * pvParameters ){// Semaphore cannot be used before a call to vSemaphoreCreateBinary ().// This is a macro so pass the variable in directly.vSemaphoreCreateBinary( xSemaphore );if( xSemaphore != NULL ){// The semaphore was created successfully.// The semaphore can now be used.}}</pre>* \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary* \ingroup Semaphores*/#define vSemaphoreCreateBinary( xSemaphore ) \{ \( xSemaphore ) = xQueueGenericCreate( ( unsigned portBASE_TYPE ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \if( ( xSemaphore ) != NULL ) \{ \( void ) xSemaphoreGive( ( xSemaphore ) ); \} \}/*** semphr. h* <pre>xSemaphoreHandle xSemaphoreCreateBinary( void )</pre>** The old vSemaphoreCreateBinary() macro is now deprecated in favour of this* xSemaphoreCreateBinary() function. Note that binary semaphores created using* the vSemaphoreCreateBinary() macro are created in a state such that the* first call to 'take' the semaphore would pass, whereas binary semaphores* created using xSemaphoreCreateBinary() are created in a state such that the* the semaphore must first be 'given' before it can be 'taken'.** Function that creates a semaphore by using the existing queue mechanism.* The queue length is 1 as this is a binary semaphore. The data size is 0* as nothing is actually stored - all that is important is whether the queue is* empty or full (the binary semaphore is available or not).** This type of semaphore can be used for pure synchronisation between tasks or* between an interrupt and a task. The semaphore need not be given back once* obtained, so one task/interrupt can continuously 'give' the semaphore while* another continuously 'takes' the semaphore. For this reason this type of* semaphore does not use a priority inheritance mechanism. For an alternative* that does use priority inheritance see xSemaphoreCreateMutex().** @return Handle to the created semaphore.** Example usage:<pre>xSemaphoreHandle xSemaphore = NULL;void vATask( void * pvParameters ){// Semaphore cannot be used before a call to vSemaphoreCreateBinary ().// This is a macro so pass the variable in directly.xSemaphore = xSemaphoreCreateBinary();if( xSemaphore != NULL ){// The semaphore was created successfully.// The semaphore can now be used.}}</pre>* \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary* \ingroup Semaphores*/#define xSemaphoreCreateBinary() xQueueGenericCreate( ( unsigned portBASE_TYPE ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE )/*** semphr. h* <pre>xSemaphoreTake(* xSemaphoreHandle xSemaphore,* portTickType xBlockTime* )</pre>** <i>Macro</i> to obtain a semaphore. The semaphore must have previously been* created with a call to vSemaphoreCreateBinary(), xSemaphoreCreateMutex() or* xSemaphoreCreateCounting().** @param xSemaphore A handle to the semaphore being taken - obtained when* the semaphore was created.** @param xBlockTime The time in ticks to wait for the semaphore to become* available. The macro portTICK_RATE_MS can be used to convert this to a* real time. A block time of zero can be used to poll the semaphore. A block* time of portMAX_DELAY can be used to block indefinitely (provided* INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h).** @return pdTRUE if the semaphore was obtained. pdFALSE* if xBlockTime expired without the semaphore becoming available.** Example usage:<pre>xSemaphoreHandle xSemaphore = NULL;// A task that creates a semaphore.void vATask( void * pvParameters ){// Create the semaphore to guard a shared resource.vSemaphoreCreateBinary( xSemaphore );}// A task that uses the semaphore.void vAnotherTask( void * pvParameters ){// ... Do other things.if( xSemaphore != NULL ){// See if we can obtain the semaphore. If the semaphore is not available// wait 10 ticks to see if it becomes free.if( xSemaphoreTake( xSemaphore, ( portTickType ) 10 ) == pdTRUE ){// We were able to obtain the semaphore and can now access the// shared resource.// ...// We have finished accessing the shared resource. Release the// semaphore.xSemaphoreGive( xSemaphore );}else{// We could not obtain the semaphore and can therefore not access// the shared resource safely.}}}</pre>* \defgroup xSemaphoreTake xSemaphoreTake* \ingroup Semaphores*/#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueGenericReceive( ( xQueueHandle ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE )/*** semphr. h* xSemaphoreTakeRecursive(* xSemaphoreHandle xMutex,* portTickType xBlockTime* )** <i>Macro</i> to recursively obtain, or 'take', a mutex type semaphore.* The mutex must have previously been created using a call to* xSemaphoreCreateRecursiveMutex();** configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this* macro to be available.** This macro must not be used on mutexes created using xSemaphoreCreateMutex().** A mutex used recursively can be 'taken' repeatedly by the owner. The mutex* doesn't become available again until the owner has called* xSemaphoreGiveRecursive() for each successful 'take' request. For example,* if a task successfully 'takes' the same mutex 5 times then the mutex will* not be available to any other task until it has also 'given' the mutex back* exactly five times.** @param xMutex A handle to the mutex being obtained. This is the* handle returned by xSemaphoreCreateRecursiveMutex();** @param xBlockTime The time in ticks to wait for the semaphore to become* available. The macro portTICK_RATE_MS can be used to convert this to a* real time. A block time of zero can be used to poll the semaphore. If* the task already owns the semaphore then xSemaphoreTakeRecursive() will* return immediately no matter what the value of xBlockTime.** @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime* expired without the semaphore becoming available.** Example usage:<pre>xSemaphoreHandle xMutex = NULL;// A task that creates a mutex.void vATask( void * pvParameters ){// Create the mutex to guard a shared resource.xMutex = xSemaphoreCreateRecursiveMutex();}// A task that uses the mutex.void vAnotherTask( void * pvParameters ){// ... Do other things.if( xMutex != NULL ){// See if we can obtain the mutex. If the mutex is not available// wait 10 ticks to see if it becomes free.if( xSemaphoreTakeRecursive( xSemaphore, ( portTickType ) 10 ) == pdTRUE ){// We were able to obtain the mutex and can now access the// shared resource.// ...// For some reason due to the nature of the code further calls to// xSemaphoreTakeRecursive() are made on the same mutex. In real// code these would not be just sequential calls as this would make// no sense. Instead the calls are likely to be buried inside// a more complex call structure.xSemaphoreTakeRecursive( xMutex, ( portTickType ) 10 );xSemaphoreTakeRecursive( xMutex, ( portTickType ) 10 );// The mutex has now been 'taken' three times, so will not be// available to another task until it has also been given back// three times. Again it is unlikely that real code would have// these calls sequentially, but instead buried in a more complex// call structure. This is just for illustrative purposes.xSemaphoreGiveRecursive( xMutex );xSemaphoreGiveRecursive( xMutex );xSemaphoreGiveRecursive( xMutex );// Now the mutex can be taken by other tasks.}else{// We could not obtain the mutex and can therefore not access// the shared resource safely.}}}</pre>* \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive* \ingroup Semaphores*/#define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) )/** xSemaphoreAltTake() is an alternative version of xSemaphoreTake().** The source code that implements the alternative (Alt) API is much* simpler because it executes everything from within a critical section.* This is the approach taken by many other RTOSes, but FreeRTOS.org has the* preferred fully featured API too. The fully featured API has more* complex code that takes longer to execute, but makes much less use of* critical sections. Therefore the alternative API sacrifices interrupt* responsiveness to gain execution speed, whereas the fully featured API* sacrifices execution speed to ensure better interrupt responsiveness.*/#define xSemaphoreAltTake( xSemaphore, xBlockTime ) xQueueAltGenericReceive( ( xQueueHandle ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE )/*** semphr. h* <pre>xSemaphoreGive( xSemaphoreHandle xSemaphore )</pre>** <i>Macro</i> to release a semaphore. The semaphore must have previously been* created with a call to vSemaphoreCreateBinary(), xSemaphoreCreateMutex() or* xSemaphoreCreateCounting(). and obtained using sSemaphoreTake().** This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for* an alternative which can be used from an ISR.** This macro must also not be used on semaphores created using* xSemaphoreCreateRecursiveMutex().** @param xSemaphore A handle to the semaphore being released. This is the* handle returned when the semaphore was created.** @return pdTRUE if the semaphore was released. pdFALSE if an error occurred.* Semaphores are implemented using queues. An error can occur if there is* no space on the queue to post a message - indicating that the* semaphore was not first obtained correctly.** Example usage:<pre>xSemaphoreHandle xSemaphore = NULL;void vATask( void * pvParameters ){// Create the semaphore to guard a shared resource.vSemaphoreCreateBinary( xSemaphore );if( xSemaphore != NULL ){if( xSemaphoreGive( xSemaphore ) != pdTRUE ){// We would expect this call to fail because we cannot give// a semaphore without first "taking" it!}// Obtain the semaphore - don't block if the semaphore is not// immediately available.if( xSemaphoreTake( xSemaphore, ( portTickType ) 0 ) ){// We now have the semaphore and can access the shared resource.// ...// We have finished accessing the shared resource so can free the// semaphore.if( xSemaphoreGive( xSemaphore ) != pdTRUE ){// We would not expect this call to fail because we must have// obtained the semaphore to get here.}}}}</pre>* \defgroup xSemaphoreGive xSemaphoreGive* \ingroup Semaphores*/#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( xQueueHandle ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )/*** semphr. h* <pre>xSemaphoreGiveRecursive( xSemaphoreHandle xMutex )</pre>** <i>Macro</i> to recursively release, or 'give', a mutex type semaphore.* The mutex must have previously been created using a call to* xSemaphoreCreateRecursiveMutex();** configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this* macro to be available.** This macro must not be used on mutexes created using xSemaphoreCreateMutex().** A mutex used recursively can be 'taken' repeatedly by the owner. The mutex* doesn't become available again until the owner has called* xSemaphoreGiveRecursive() for each successful 'take' request. For example,* if a task successfully 'takes' the same mutex 5 times then the mutex will* not be available to any other task until it has also 'given' the mutex back* exactly five times.** @param xMutex A handle to the mutex being released, or 'given'. This is the* handle returned by xSemaphoreCreateMutex();** @return pdTRUE if the semaphore was given.** Example usage:<pre>xSemaphoreHandle xMutex = NULL;// A task that creates a mutex.void vATask( void * pvParameters ){// Create the mutex to guard a shared resource.xMutex = xSemaphoreCreateRecursiveMutex();}// A task that uses the mutex.void vAnotherTask( void * pvParameters ){// ... Do other things.if( xMutex != NULL ){// See if we can obtain the mutex. If the mutex is not available// wait 10 ticks to see if it becomes free.if( xSemaphoreTakeRecursive( xMutex, ( portTickType ) 10 ) == pdTRUE ){// We were able to obtain the mutex and can now access the// shared resource.// ...// For some reason due to the nature of the code further calls to// xSemaphoreTakeRecursive() are made on the same mutex. In real// code these would not be just sequential calls as this would make// no sense. Instead the calls are likely to be buried inside// a more complex call structure.xSemaphoreTakeRecursive( xMutex, ( portTickType ) 10 );xSemaphoreTakeRecursive( xMutex, ( portTickType ) 10 );// The mutex has now been 'taken' three times, so will not be// available to another task until it has also been given back// three times. Again it is unlikely that real code would have// these calls sequentially, it would be more likely that the calls// to xSemaphoreGiveRecursive() would be called as a call stack// unwound. This is just for demonstrative purposes.xSemaphoreGiveRecursive( xMutex );xSemaphoreGiveRecursive( xMutex );xSemaphoreGiveRecursive( xMutex );// Now the mutex can be taken by other tasks.}else{// We could not obtain the mutex and can therefore not access// the shared resource safely.}}}</pre>* \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive* \ingroup Semaphores*/#define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) )/** xSemaphoreAltGive() is an alternative version of xSemaphoreGive().** The source code that implements the alternative (Alt) API is much* simpler because it executes everything from within a critical section.* This is the approach taken by many other RTOSes, but FreeRTOS.org has the* preferred fully featured API too. The fully featured API has more* complex code that takes longer to execute, but makes much less use of* critical sections. Therefore the alternative API sacrifices interrupt* responsiveness to gain execution speed, whereas the fully featured API* sacrifices execution speed to ensure better interrupt responsiveness.*/#define xSemaphoreAltGive( xSemaphore ) xQueueAltGenericSend( ( xQueueHandle ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )/*** semphr. h* <pre>xSemaphoreGiveFromISR(xSemaphoreHandle xSemaphore,signed portBASE_TYPE *pxHigherPriorityTaskWoken)</pre>** <i>Macro</i> to release a semaphore. The semaphore must have previously been* created with a call to vSemaphoreCreateBinary() or xSemaphoreCreateCounting().** Mutex type semaphores (those created using a call to xSemaphoreCreateMutex())* must not be used with this macro.** This macro can be used from an ISR.** @param xSemaphore A handle to the semaphore being released. This is the* handle returned when the semaphore was created.** @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL.** Example usage:<pre>\#define LONG_TIME 0xffff\#define TICKS_TO_WAIT 10xSemaphoreHandle xSemaphore = NULL;// Repetitive task.void vATask( void * pvParameters ){for( ;; ){// We want this task to run every 10 ticks of a timer. The semaphore// was created before this task was started.// Block waiting for the semaphore to become available.if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ){// It is time to execute.// ...// We have finished our task. Return to the top of the loop where// we will block on the semaphore until it is time to execute// again. Note when using the semaphore for synchronisation with an// ISR in this manner there is no need to 'give' the semaphore back.}}}// Timer ISRvoid vTimerISR( void * pvParameters ){static unsigned char ucLocalTickCount = 0;static signed portBASE_TYPE xHigherPriorityTaskWoken;// A timer tick has occurred.// ... Do other time functions.// Is it time for vATask () to run?xHigherPriorityTaskWoken = pdFALSE;ucLocalTickCount++;if( ucLocalTickCount >= TICKS_TO_WAIT ){// Unblock the task by releasing the semaphore.xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken );// Reset the count so we release the semaphore again in 10 ticks time.ucLocalTickCount = 0;}if( xHigherPriorityTaskWoken != pdFALSE ){// We can force a context switch here. Context switching from an// ISR uses port specific syntax. Check the demo task for your port// to find the syntax required.}}</pre>* \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR* \ingroup Semaphores*/#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueueHandle ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )/*** semphr. h* <pre>xSemaphoreTakeFromISR(xSemaphoreHandle xSemaphore,signed portBASE_TYPE *pxHigherPriorityTaskWoken)</pre>** <i>Macro</i> to take a semaphore from an ISR. The semaphore must have* previously been created with a call to vSemaphoreCreateBinary() or* xSemaphoreCreateCounting().** Mutex type semaphores (those created using a call to xSemaphoreCreateMutex())* must not be used with this macro.** This macro can be used from an ISR, however taking a semaphore from an ISR* is not a common operation. It is likely to only be useful when taking a* counting semaphore when an interrupt is obtaining an object from a resource* pool (when the semaphore count indicates the number of resources available).** @param xSemaphore A handle to the semaphore being taken. This is the* handle returned when the semaphore was created.** @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set* *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task* to unblock, and the unblocked task has a priority higher than the currently* running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then* a context switch should be requested before the interrupt is exited.** @return pdTRUE if the semaphore was successfully taken, otherwise* pdFALSE*/#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( xQueueHandle ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )/*** semphr. h* <pre>xSemaphoreHandle xSemaphoreCreateMutex( void )</pre>** <i>Macro</i> that implements a mutex semaphore by using the existing queue* mechanism.** Mutexes created using this macro can be accessed using the xSemaphoreTake()* and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and* xSemaphoreGiveRecursive() macros should not be used.** This type of semaphore uses a priority inheritance mechanism so a task* 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the* semaphore it is no longer required.** Mutex type semaphores cannot be used from within interrupt service routines.** See vSemaphoreCreateBinary() for an alternative implementation that can be* used for pure synchronisation (where one task or interrupt always 'gives' the* semaphore and another always 'takes' the semaphore) and from within interrupt* service routines.** @return xSemaphore Handle to the created mutex semaphore. Should be of type* xSemaphoreHandle.** Example usage:<pre>xSemaphoreHandle xSemaphore;void vATask( void * pvParameters ){// Semaphore cannot be used before a call to xSemaphoreCreateMutex().// This is a macro so pass the variable in directly.xSemaphore = xSemaphoreCreateMutex();if( xSemaphore != NULL ){// The semaphore was created successfully.// The semaphore can now be used.}}</pre>* \defgroup vSemaphoreCreateMutex vSemaphoreCreateMutex* \ingroup Semaphores*/#define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )/*** semphr. h* <pre>xSemaphoreHandle xSemaphoreCreateRecursiveMutex( void )</pre>** <i>Macro</i> that implements a recursive mutex by using the existing queue* mechanism.** Mutexes created using this macro can be accessed using the* xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The* xSemaphoreTake() and xSemaphoreGive() macros should not be used.** A mutex used recursively can be 'taken' repeatedly by the owner. The mutex* doesn't become available again until the owner has called* xSemaphoreGiveRecursive() for each successful 'take' request. For example,* if a task successfully 'takes' the same mutex 5 times then the mutex will* not be available to any other task until it has also 'given' the mutex back* exactly five times.** This type of semaphore uses a priority inheritance mechanism so a task* 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the* semaphore it is no longer required.** Mutex type semaphores cannot be used from within interrupt service routines.** See vSemaphoreCreateBinary() for an alternative implementation that can be* used for pure synchronisation (where one task or interrupt always 'gives' the* semaphore and another always 'takes' the semaphore) and from within interrupt* service routines.** @return xSemaphore Handle to the created mutex semaphore. Should be of type* xSemaphoreHandle.** Example usage:<pre>xSemaphoreHandle xSemaphore;void vATask( void * pvParameters ){// Semaphore cannot be used before a call to xSemaphoreCreateMutex().// This is a macro so pass the variable in directly.xSemaphore = xSemaphoreCreateRecursiveMutex();if( xSemaphore != NULL ){// The semaphore was created successfully.// The semaphore can now be used.}}</pre>* \defgroup vSemaphoreCreateMutex vSemaphoreCreateMutex* \ingroup Semaphores*/#define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )/*** semphr. h* <pre>xSemaphoreHandle xSemaphoreCreateCounting( unsigned portBASE_TYPE uxMaxCount, unsigned portBASE_TYPE uxInitialCount )</pre>** <i>Macro</i> that creates a counting semaphore by using the existing* queue mechanism.** Counting semaphores are typically used for two things:** 1) Counting events.** In this usage scenario an event handler will 'give' a semaphore each time* an event occurs (incrementing the semaphore count value), and a handler* task will 'take' a semaphore each time it processes an event* (decrementing the semaphore count value). The count value is therefore* the difference between the number of events that have occurred and the* number that have been processed. In this case it is desirable for the* initial count value to be zero.** 2) Resource management.** In this usage scenario the count value indicates the number of resources* available. To obtain control of a resource a task must first obtain a* semaphore - decrementing the semaphore count value. When the count value* reaches zero there are no free resources. When a task finishes with the* resource it 'gives' the semaphore back - incrementing the semaphore count* value. In this case it is desirable for the initial count value to be* equal to the maximum count value, indicating that all resources are free.** @param uxMaxCount The maximum count value that can be reached. When the* semaphore reaches this value it can no longer be 'given'.** @param uxInitialCount The count value assigned to the semaphore when it is* created.** @return Handle to the created semaphore. Null if the semaphore could not be* created.** Example usage:<pre>xSemaphoreHandle xSemaphore;void vATask( void * pvParameters ){xSemaphoreHandle xSemaphore = NULL;// Semaphore cannot be used before a call to xSemaphoreCreateCounting().// The max value to which the semaphore can count should be 10, and the// initial value assigned to the count should be 0.xSemaphore = xSemaphoreCreateCounting( 10, 0 );if( xSemaphore != NULL ){// The semaphore was created successfully.// The semaphore can now be used.}}</pre>* \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting* \ingroup Semaphores*/#define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )/*** semphr. h* <pre>void vSemaphoreDelete( xSemaphoreHandle xSemaphore );</pre>** Delete a semaphore. This function must be used with care. For example,* do not delete a mutex type semaphore if the mutex is held by a task.** @param xSemaphore A handle to the semaphore to be deleted.** \defgroup vSemaphoreDelete vSemaphoreDelete* \ingroup Semaphores*/#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( xQueueHandle ) ( xSemaphore ) )/*** semphr.h* <pre>xTaskHandle xSemaphoreGetMutexHolder( xSemaphoreHandle xMutex );</pre>** If xMutex is indeed a mutex type semaphore, return the current mutex holder.* If xMutex is not a mutex type semaphore, or the mutex is available (not held* by a task), return NULL.** Note: This Is is a good way of determining if the calling task is the mutex* holder, but not a good way of determining the identity of the mutex holder as* the holder may change between the function exiting and the returned value* being tested.*/#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) )#endif /* SEMAPHORE_H */
123version https://git-lfs.github.com/spec/v1oid sha256:95ca508893398f37ea6997918b636bf7b8f889d2a4063f9440a25d37c6457540size 5824812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef INC_TASK_H#define INC_TASK_H#ifndef INC_FREERTOS_H#error "include FreeRTOS.h must appear in source files before include task.h"#endif#include "list.h"#ifdef __cplusplusextern "C" {#endif/*-----------------------------------------------------------* MACROS AND DEFINITIONS*----------------------------------------------------------*/#define tskKERNEL_VERSION_NUMBER "V7.6.0"/*** task. h** Type by which tasks are referenced. For example, a call to xTaskCreate* returns (via a pointer parameter) an xTaskHandle variable that can then* be used as a parameter to vTaskDelete to delete the task.** \defgroup xTaskHandle xTaskHandle* \ingroup Tasks*/typedef void * xTaskHandle;/* Task states returned by eTaskGetState. */typedef enum{eRunning = 0, /* A task is querying the state of itself, so must be running. */eReady, /* The task being queried is in a read or pending ready list. */eBlocked, /* The task being queried is in the Blocked state. */eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */eDeleted /* The task being queried has been deleted, but its TCB has not yet been freed. */} eTaskState;/** Used internally only.*/typedef struct xTIME_OUT{portBASE_TYPE xOverflowCount;portTickType xTimeOnEntering;} xTimeOutType;/** Defines the memory ranges allocated to the task when an MPU is used.*/typedef struct xMEMORY_REGION{void *pvBaseAddress;unsigned long ulLengthInBytes;unsigned long ulParameters;} xMemoryRegion;/** Parameters required to create an MPU protected task.*/typedef struct xTASK_PARAMTERS{pdTASK_CODE pvTaskCode;const signed char * const pcName;unsigned short usStackDepth;void *pvParameters;unsigned portBASE_TYPE uxPriority;portSTACK_TYPE *puxStackBuffer;xMemoryRegion xRegions[ portNUM_CONFIGURABLE_REGIONS ];} xTaskParameters;/* Used with the uxTaskGetSystemState() function to return the state of each taskin the system. */typedef struct xTASK_STATUS{xTaskHandle xHandle; /* The handle of the task to which the rest of the information in the structure relates. */const signed char *pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */unsigned portBASE_TYPE xTaskNumber; /* A number unique to the task. */eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */unsigned portBASE_TYPE uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */unsigned portBASE_TYPE uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */unsigned long ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */unsigned short usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */} xTaskStatusType;/* Possible return values for eTaskConfirmSleepModeStatus(). */typedef enum{eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */} eSleepModeStatus;/** Defines the priority used by the idle task. This must not be modified.** \ingroup TaskUtils*/#define tskIDLE_PRIORITY ( ( unsigned portBASE_TYPE ) 0U )/*** task. h** Macro for forcing a context switch.** \defgroup taskYIELD taskYIELD* \ingroup SchedulerControl*/#define taskYIELD() portYIELD()/*** task. h** Macro to mark the start of a critical code region. Preemptive context* switches cannot occur when in a critical region.** NOTE: This may alter the stack (depending on the portable implementation)* so must be used with care!** \defgroup taskENTER_CRITICAL taskENTER_CRITICAL* \ingroup SchedulerControl*/#define taskENTER_CRITICAL() portENTER_CRITICAL()/*** task. h** Macro to mark the end of a critical code region. Preemptive context* switches cannot occur when in a critical region.** NOTE: This may alter the stack (depending on the portable implementation)* so must be used with care!** \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL* \ingroup SchedulerControl*/#define taskEXIT_CRITICAL() portEXIT_CRITICAL()/*** task. h** Macro to disable all maskable interrupts.** \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS* \ingroup SchedulerControl*/#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS()/*** task. h** Macro to enable microcontroller interrupts.** \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS* \ingroup SchedulerControl*/#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS()/* Definitions returned by xTaskGetSchedulerState(). */#define taskSCHEDULER_NOT_STARTED ( ( portBASE_TYPE ) 0 )#define taskSCHEDULER_RUNNING ( ( portBASE_TYPE ) 1 )#define taskSCHEDULER_SUSPENDED ( ( portBASE_TYPE ) 2 )/*-----------------------------------------------------------* TASK CREATION API*----------------------------------------------------------*//*** task. h*<pre>portBASE_TYPE xTaskCreate(pdTASK_CODE pvTaskCode,const char * const pcName,unsigned short usStackDepth,void *pvParameters,unsigned portBASE_TYPE uxPriority,xTaskHandle *pvCreatedTask);</pre>** Create a new task and add it to the list of tasks that are ready to run.** xTaskCreate() can only be used to create a task that has unrestricted* access to the entire microcontroller memory map. Systems that include MPU* support can alternatively create an MPU constrained task using* xTaskCreateRestricted().** @param pvTaskCode Pointer to the task entry function. Tasks* must be implemented to never return (i.e. continuous loop).** @param pcName A descriptive name for the task. This is mainly used to* facilitate debugging. Max length defined by tskMAX_TASK_NAME_LEN - default* is 16.** @param usStackDepth The size of the task stack specified as the number of* variables the stack can hold - not the number of bytes. For example, if* the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes* will be allocated for stack storage.** @param pvParameters Pointer that will be used as the parameter for the task* being created.** @param uxPriority The priority at which the task should run. Systems that* include MPU support can optionally create tasks in a privileged (system)* mode by setting bit portPRIVILEGE_BIT of the priority parameter. For* example, to create a privileged task at priority 2 the uxPriority parameter* should be set to ( 2 | portPRIVILEGE_BIT ).** @param pvCreatedTask Used to pass back a handle by which the created task* can be referenced.** @return pdPASS if the task was successfully created and added to a ready* list, otherwise an error code defined in the file errors. h** Example usage:<pre>// Task to be created.void vTaskCode( void * pvParameters ){for( ;; ){// Task code goes here.}}// Function that creates a task.void vOtherFunction( void ){static unsigned char ucParameterToPass;xTaskHandle xHandle;// Create the task, storing the handle. Note that the passed parameter ucParameterToPass// must exist for the lifetime of the task, so in this case is declared static. If it was just an// an automatic stack variable it might no longer exist, or at least have been corrupted, by the time// the new task attempts to access it.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle );// Use the handle to delete the task.vTaskDelete( xHandle );}</pre>* \defgroup xTaskCreate xTaskCreate* \ingroup Tasks*/#define xTaskCreate( pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask ) xTaskGenericCreate( ( pvTaskCode ), ( pcName ), ( usStackDepth ), ( pvParameters ), ( uxPriority ), ( pxCreatedTask ), ( NULL ), ( NULL ) )/*** task. h*<pre>portBASE_TYPE xTaskCreateRestricted( xTaskParameters *pxTaskDefinition, xTaskHandle *pxCreatedTask );</pre>** xTaskCreateRestricted() should only be used in systems that include an MPU* implementation.** Create a new task and add it to the list of tasks that are ready to run.* The function parameters define the memory regions and associated access* permissions allocated to the task.** @param pxTaskDefinition Pointer to a structure that contains a member* for each of the normal xTaskCreate() parameters (see the xTaskCreate() API* documentation) plus an optional stack buffer and the memory region* definitions.** @param pxCreatedTask Used to pass back a handle by which the created task* can be referenced.** @return pdPASS if the task was successfully created and added to a ready* list, otherwise an error code defined in the file errors. h** Example usage:<pre>// Create an xTaskParameters structure that defines the task to be created.static const xTaskParameters xCheckTaskParameters ={vATask, // pvTaskCode - the function that implements the task."ATask", // pcName - just a text name for the task to assist debugging.100, // usStackDepth - the stack size DEFINED IN WORDS.NULL, // pvParameters - passed into the task function as the function parameters.( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.// xRegions - Allocate up to three separate memory regions for access by// the task, with appropriate access permissions. Different processors have// different memory alignment requirements - refer to the FreeRTOS documentation// for full information.{// Base address Length Parameters{ cReadWriteArray, 32, portMPU_REGION_READ_WRITE },{ cReadOnlyArray, 32, portMPU_REGION_READ_ONLY },{ cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE }}};int main( void ){xTaskHandle xHandle;// Create a task from the const structure defined above. The task handle// is requested (the second parameter is not NULL) but in this case just for// demonstration purposes as its not actually used.xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );// Start the scheduler.vTaskStartScheduler();// Will only get here if there was insufficient memory to create the idle// task.for( ;; );}</pre>* \defgroup xTaskCreateRestricted xTaskCreateRestricted* \ingroup Tasks*/#define xTaskCreateRestricted( x, pxCreatedTask ) xTaskGenericCreate( ((x)->pvTaskCode), ((x)->pcName), ((x)->usStackDepth), ((x)->pvParameters), ((x)->uxPriority), (pxCreatedTask), ((x)->puxStackBuffer), ((x)->xRegions) )/*** task. h*<pre>void vTaskAllocateMPURegions( xTaskHandle xTask, const xMemoryRegion * const pxRegions );</pre>** Memory regions are assigned to a restricted task when the task is created by* a call to xTaskCreateRestricted(). These regions can be redefined using* vTaskAllocateMPURegions().** @param xTask The handle of the task being updated.** @param xRegions A pointer to an xMemoryRegion structure that contains the* new memory region definitions.** Example usage:<pre>// Define an array of xMemoryRegion structures that configures an MPU region// allowing read/write access for 1024 bytes starting at the beginning of the// ucOneKByte array. The other two of the maximum 3 definable regions are// unused so set to zero.static const xMemoryRegion xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] ={// Base address Length Parameters{ ucOneKByte, 1024, portMPU_REGION_READ_WRITE },{ 0, 0, 0 },{ 0, 0, 0 }};void vATask( void *pvParameters ){// This task was created such that it has access to certain regions of// memory as defined by the MPU configuration. At some point it is// desired that these MPU regions are replaced with that defined in the// xAltRegions const struct above. Use a call to vTaskAllocateMPURegions()// for this purpose. NULL is used as the task handle to indicate that this// function should modify the MPU regions of the calling task.vTaskAllocateMPURegions( NULL, xAltRegions );// Now the task can continue its function, but from this point on can only// access its stack and the ucOneKByte array (unless any other statically// defined or shared regions have been declared elsewhere).}</pre>* \defgroup xTaskCreateRestricted xTaskCreateRestricted* \ingroup Tasks*/void vTaskAllocateMPURegions( xTaskHandle xTask, const xMemoryRegion * const pxRegions ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskDelete( xTaskHandle xTask );</pre>** INCLUDE_vTaskDelete must be defined as 1 for this function to be available.* See the configuration section for more information.** Remove a task from the RTOS real time kernels management. The task being* deleted will be removed from all ready, blocked, suspended and event lists.** NOTE: The idle task is responsible for freeing the kernel allocated* memory from tasks that have been deleted. It is therefore important that* the idle task is not starved of microcontroller processing time if your* application makes any calls to vTaskDelete (). Memory allocated by the* task code is not automatically freed, and should be freed before the task* is deleted.** See the demo application file death.c for sample code that utilises* vTaskDelete ().** @param xTask The handle of the task to be deleted. Passing NULL will* cause the calling task to be deleted.** Example usage:<pre>void vOtherFunction( void ){xTaskHandle xHandle;// Create the task, storing the handle.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );// Use the handle to delete the task.vTaskDelete( xHandle );}</pre>* \defgroup vTaskDelete vTaskDelete* \ingroup Tasks*/void vTaskDelete( xTaskHandle xTaskToDelete ) PRIVILEGED_FUNCTION;/*-----------------------------------------------------------* TASK CONTROL API*----------------------------------------------------------*//*** task. h* <pre>void vTaskDelay( portTickType xTicksToDelay );</pre>** Delay a task for a given number of ticks. The actual time that the* task remains blocked depends on the tick rate. The constant* portTICK_RATE_MS can be used to calculate real time from the tick* rate - with the resolution of one tick period.** INCLUDE_vTaskDelay must be defined as 1 for this function to be available.* See the configuration section for more information.*** vTaskDelay() specifies a time at which the task wishes to unblock relative to* the time at which vTaskDelay() is called. For example, specifying a block* period of 100 ticks will cause the task to unblock 100 ticks after* vTaskDelay() is called. vTaskDelay() does not therefore provide a good method* of controlling the frequency of a cyclical task as the path taken through the* code, as well as other task and interrupt activity, will effect the frequency* at which vTaskDelay() gets called and therefore the time at which the task* next executes. See vTaskDelayUntil() for an alternative API function designed* to facilitate fixed frequency execution. It does this by specifying an* absolute time (rather than a relative time) at which the calling task should* unblock.** @param xTicksToDelay The amount of time, in tick periods, that* the calling task should block.** Example usage:void vTaskFunction( void * pvParameters ){void vTaskFunction( void * pvParameters ){// Block for 500ms.const portTickType xDelay = 500 / portTICK_RATE_MS;for( ;; ){// Simply toggle the LED every 500ms, blocking between each toggle.vToggleLED();vTaskDelay( xDelay );}}* \defgroup vTaskDelay vTaskDelay* \ingroup TaskCtrl*/void vTaskDelay( portTickType xTicksToDelay ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskDelayUntil( portTickType *pxPreviousWakeTime, portTickType xTimeIncrement );</pre>** INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available.* See the configuration section for more information.** Delay a task until a specified time. This function can be used by cyclical* tasks to ensure a constant execution frequency.** This function differs from vTaskDelay () in one important aspect: vTaskDelay () will* cause a task to block for the specified number of ticks from the time vTaskDelay () is* called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed* execution frequency as the time between a task starting to execute and that task* calling vTaskDelay () may not be fixed [the task may take a different path though the* code between calls, or may get interrupted or preempted a different number of times* each time it executes].** Whereas vTaskDelay () specifies a wake time relative to the time at which the function* is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to* unblock.** The constant portTICK_RATE_MS can be used to calculate real time from the tick* rate - with the resolution of one tick period.** @param pxPreviousWakeTime Pointer to a variable that holds the time at which the* task was last unblocked. The variable must be initialised with the current time* prior to its first use (see the example below). Following this the variable is* automatically updated within vTaskDelayUntil ().** @param xTimeIncrement The cycle time period. The task will be unblocked at* time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the* same xTimeIncrement parameter value will cause the task to execute with* a fixed interface period.** Example usage:<pre>// Perform an action every 10 ticks.void vTaskFunction( void * pvParameters ){portTickType xLastWakeTime;const portTickType xFrequency = 10;// Initialise the xLastWakeTime variable with the current time.xLastWakeTime = xTaskGetTickCount ();for( ;; ){// Wait for the next cycle.vTaskDelayUntil( &xLastWakeTime, xFrequency );// Perform action here.}}</pre>* \defgroup vTaskDelayUntil vTaskDelayUntil* \ingroup TaskCtrl*/void vTaskDelayUntil( portTickType * const pxPreviousWakeTime, portTickType xTimeIncrement ) PRIVILEGED_FUNCTION;/*** task. h* <pre>unsigned portBASE_TYPE uxTaskPriorityGet( xTaskHandle xTask );</pre>** INCLUDE_xTaskPriorityGet must be defined as 1 for this function to be available.* See the configuration section for more information.** Obtain the priority of any task.** @param xTask Handle of the task to be queried. Passing a NULL* handle results in the priority of the calling task being returned.** @return The priority of xTask.** Example usage:<pre>void vAFunction( void ){xTaskHandle xHandle;// Create a task, storing the handle.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );// ...// Use the handle to obtain the priority of the created task.// It was created with tskIDLE_PRIORITY, but may have changed// it itself.if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ){// The task has changed it's priority.}// ...// Is our priority higher than the created task?if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ){// Our priority (obtained using NULL handle) is higher.}}</pre>* \defgroup uxTaskPriorityGet uxTaskPriorityGet* \ingroup TaskCtrl*/unsigned portBASE_TYPE uxTaskPriorityGet( xTaskHandle xTask ) PRIVILEGED_FUNCTION;/*** task. h* <pre>eTaskState eTaskGetState( xTaskHandle xTask );</pre>** INCLUDE_eTaskGetState must be defined as 1 for this function to be available.* See the configuration section for more information.** Obtain the state of any task. States are encoded by the eTaskState* enumerated type.** @param xTask Handle of the task to be queried.** @return The state of xTask at the time the function was called. Note the* state of the task might change between the function being called, and the* functions return value being tested by the calling task.*/eTaskState eTaskGetState( xTaskHandle xTask ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskPrioritySet( xTaskHandle xTask, unsigned portBASE_TYPE uxNewPriority );</pre>** INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available.* See the configuration section for more information.** Set the priority of any task.** A context switch will occur before the function returns if the priority* being set is higher than the currently executing task.** @param xTask Handle to the task for which the priority is being set.* Passing a NULL handle results in the priority of the calling task being set.** @param uxNewPriority The priority to which the task will be set.** Example usage:<pre>void vAFunction( void ){xTaskHandle xHandle;// Create a task, storing the handle.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );// ...// Use the handle to raise the priority of the created task.vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 );// ...// Use a NULL handle to raise our priority to the same value.vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 );}</pre>* \defgroup vTaskPrioritySet vTaskPrioritySet* \ingroup TaskCtrl*/void vTaskPrioritySet( xTaskHandle xTask, unsigned portBASE_TYPE uxNewPriority ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskSuspend( xTaskHandle xTaskToSuspend );</pre>** INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.* See the configuration section for more information.** Suspend any task. When suspended a task will never get any microcontroller* processing time, no matter what its priority.** Calls to vTaskSuspend are not accumulative -* i.e. calling vTaskSuspend () twice on the same task still only requires one* call to vTaskResume () to ready the suspended task.** @param xTaskToSuspend Handle to the task being suspended. Passing a NULL* handle will cause the calling task to be suspended.** Example usage:<pre>void vAFunction( void ){xTaskHandle xHandle;// Create a task, storing the handle.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );// ...// Use the handle to suspend the created task.vTaskSuspend( xHandle );// ...// The created task will not run during this period, unless// another task calls vTaskResume( xHandle ).//...// Suspend ourselves.vTaskSuspend( NULL );// We cannot get here unless another task calls vTaskResume// with our handle as the parameter.}</pre>* \defgroup vTaskSuspend vTaskSuspend* \ingroup TaskCtrl*/void vTaskSuspend( xTaskHandle xTaskToSuspend ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskResume( xTaskHandle xTaskToResume );</pre>** INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.* See the configuration section for more information.** Resumes a suspended task.** A task that has been suspended by one of more calls to vTaskSuspend ()* will be made available for running again by a single call to* vTaskResume ().** @param xTaskToResume Handle to the task being readied.** Example usage:<pre>void vAFunction( void ){xTaskHandle xHandle;// Create a task, storing the handle.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );// ...// Use the handle to suspend the created task.vTaskSuspend( xHandle );// ...// The created task will not run during this period, unless// another task calls vTaskResume( xHandle ).//...// Resume the suspended task ourselves.vTaskResume( xHandle );// The created task will once again get microcontroller processing// time in accordance with it priority within the system.}</pre>* \defgroup vTaskResume vTaskResume* \ingroup TaskCtrl*/void vTaskResume( xTaskHandle xTaskToResume ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void xTaskResumeFromISR( xTaskHandle xTaskToResume );</pre>** INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be* available. See the configuration section for more information.** An implementation of vTaskResume() that can be called from within an ISR.** A task that has been suspended by one of more calls to vTaskSuspend ()* will be made available for running again by a single call to* xTaskResumeFromISR ().** @param xTaskToResume Handle to the task being readied.** \defgroup vTaskResumeFromISR vTaskResumeFromISR* \ingroup TaskCtrl*/portBASE_TYPE xTaskResumeFromISR( xTaskHandle xTaskToResume ) PRIVILEGED_FUNCTION;/*-----------------------------------------------------------* SCHEDULER CONTROL*----------------------------------------------------------*//*** task. h* <pre>void vTaskStartScheduler( void );</pre>** Starts the real time kernel tick processing. After calling the kernel* has control over which tasks are executed and when. This function* does not return until an executing task calls vTaskEndScheduler ().** At least one task should be created via a call to xTaskCreate ()* before calling vTaskStartScheduler (). The idle task is created* automatically when the first application task is created.** See the demo application file main.c for an example of creating* tasks and starting the kernel.** Example usage:<pre>void vAFunction( void ){// Create at least one task before starting the kernel.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );// Start the real time kernel with preemption.vTaskStartScheduler ();// Will not get here unless a task calls vTaskEndScheduler ()}</pre>** \defgroup vTaskStartScheduler vTaskStartScheduler* \ingroup SchedulerControl*/void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskEndScheduler( void );</pre>** Stops the real time kernel tick. All created tasks will be automatically* deleted and multitasking (either preemptive or cooperative) will* stop. Execution then resumes from the point where vTaskStartScheduler ()* was called, as if vTaskStartScheduler () had just returned.** See the demo application file main. c in the demo/PC directory for an* example that uses vTaskEndScheduler ().** vTaskEndScheduler () requires an exit function to be defined within the* portable layer (see vPortEndScheduler () in port. c for the PC port). This* performs hardware specific operations such as stopping the kernel tick.** vTaskEndScheduler () will cause all of the resources allocated by the* kernel to be freed - but will not free resources allocated by application* tasks.** Example usage:<pre>void vTaskCode( void * pvParameters ){for( ;; ){// Task code goes here.// At some point we want to end the real time kernel processing// so call ...vTaskEndScheduler ();}}void vAFunction( void ){// Create at least one task before starting the kernel.xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );// Start the real time kernel with preemption.vTaskStartScheduler ();// Will only get here when the vTaskCode () task has called// vTaskEndScheduler (). When we get here we are back to single task// execution.}</pre>** \defgroup vTaskEndScheduler vTaskEndScheduler* \ingroup SchedulerControl*/void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;/*** task. h* <pre>void vTaskSuspendAll( void );</pre>** Suspends all real time kernel activity while keeping interrupts (including the* kernel tick) enabled.** After calling vTaskSuspendAll () the calling task will continue to execute* without risk of being swapped out until a call to xTaskResumeAll () has been* made.** API functions that have the potential to cause a context switch (for example,* vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler* is suspended.** Example usage:<pre>void vTask1( void * pvParameters ){for( ;; ){// Task code goes here.// ...// At some point the task wants to perform a long operation during// which it does not want to get swapped out. It cannot use// taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the// operation may cause interrupts to be missed - including the// ticks.// Prevent the real time kernel swapping out the task.vTaskSuspendAll ();// Perform the operation here. There is no need to use critical// sections as we have all the microcontroller processing time.// During this time interrupts will still operate and the kernel// tick count will be maintained.// ...// The operation is complete. Restart the kernel.xTaskResumeAll ();}}</pre>* \defgroup vTaskSuspendAll vTaskSuspendAll* \ingroup SchedulerControl*/void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION;/*** task. h* <pre>char xTaskResumeAll( void );</pre>** Resumes real time kernel activity following a call to vTaskSuspendAll ().* After a call to vTaskSuspendAll () the kernel will take control of which* task is executing at any time.** @return If resuming the scheduler caused a context switch then pdTRUE is* returned, otherwise pdFALSE is returned.** Example usage:<pre>void vTask1( void * pvParameters ){for( ;; ){// Task code goes here.// ...// At some point the task wants to perform a long operation during// which it does not want to get swapped out. It cannot use// taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the// operation may cause interrupts to be missed - including the// ticks.// Prevent the real time kernel swapping out the task.vTaskSuspendAll ();// Perform the operation here. There is no need to use critical// sections as we have all the microcontroller processing time.// During this time interrupts will still operate and the real// time kernel tick count will be maintained.// ...// The operation is complete. Restart the kernel. We want to force// a context switch - but there is no point if resuming the scheduler// caused a context switch already.if( !xTaskResumeAll () ){taskYIELD ();}}}</pre>* \defgroup xTaskResumeAll xTaskResumeAll* \ingroup SchedulerControl*/signed portBASE_TYPE xTaskResumeAll( void ) PRIVILEGED_FUNCTION;/*** task. h* <pre>signed portBASE_TYPE xTaskIsTaskSuspended( const xTaskHandle xTask );</pre>** Utility task that simply returns pdTRUE if the task referenced by xTask is* currently in the Suspended state, or pdFALSE if the task referenced by xTask* is in any other state.**/signed portBASE_TYPE xTaskIsTaskSuspended( xTaskHandle xTask ) PRIVILEGED_FUNCTION;/*-----------------------------------------------------------* TASK UTILITIES*----------------------------------------------------------*//*** task. h* <PRE>portTickType xTaskGetTickCount( void );</PRE>** @return The count of ticks since vTaskStartScheduler was called.** \defgroup xTaskGetTickCount xTaskGetTickCount* \ingroup TaskUtils*/portTickType xTaskGetTickCount( void ) PRIVILEGED_FUNCTION;/*** task. h* <PRE>portTickType xTaskGetTickCountFromISR( void );</PRE>** @return The count of ticks since vTaskStartScheduler was called.** This is a version of xTaskGetTickCount() that is safe to be called from an* ISR - provided that portTickType is the natural word size of the* microcontroller being used or interrupt nesting is either not supported or* not being used.** \defgroup xTaskGetTickCount xTaskGetTickCount* \ingroup TaskUtils*/portTickType xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION;/*** task. h* <PRE>unsigned short uxTaskGetNumberOfTasks( void );</PRE>** @return The number of tasks that the real time kernel is currently managing.* This includes all ready, blocked and suspended tasks. A task that* has been deleted but not yet freed by the idle task will also be* included in the count.** \defgroup uxTaskGetNumberOfTasks uxTaskGetNumberOfTasks* \ingroup TaskUtils*/unsigned portBASE_TYPE uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION;/*** task. h* <PRE>signed char *pcTaskGetTaskName( xTaskHandle xTaskToQuery );</PRE>** @return The text (human readable) name of the task referenced by the handle* xTaskToQueury. A task can query its own name by either passing in its own* handle, or by setting xTaskToQuery to NULL. INCLUDE_pcTaskGetTaskName must be* set to 1 in FreeRTOSConfig.h for pcTaskGetTaskName() to be available.** \defgroup pcTaskGetTaskName pcTaskGetTaskName* \ingroup TaskUtils*/signed char *pcTaskGetTaskName( xTaskHandle xTaskToQuery );/*** task.h* <PRE>unsigned portBASE_TYPE uxTaskGetStackHighWaterMark( xTaskHandle xTask );</PRE>** INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for* this function to be available.** Returns the high water mark of the stack associated with xTask. That is,* the minimum free stack space there has been (in words, so on a 32 bit machine* a value of 1 means 4 bytes) since the task started. The smaller the returned* number the closer the task has come to overflowing its stack.** @param xTask Handle of the task associated with the stack to be checked.* Set xTask to NULL to check the stack of the calling task.** @return The smallest amount of free stack space there has been (in bytes)* since the task referenced by xTask was created.*/unsigned portBASE_TYPE uxTaskGetStackHighWaterMark( xTaskHandle xTask ) PRIVILEGED_FUNCTION;/* When using trace macros it is sometimes necessary to include tasks.h beforeFreeRTOS.h. When this is done pdTASK_HOOK_CODE will not yet have been defined,so the following two prototypes will cause a compilation error. This can befixed by simply guarding against the inclusion of these two prototypes unlessthey are explicitly required by the configUSE_APPLICATION_TASK_TAG configurationconstant. */#ifdef configUSE_APPLICATION_TASK_TAG#if configUSE_APPLICATION_TASK_TAG == 1/*** task.h* <pre>void vTaskSetApplicationTaskTag( xTaskHandle xTask, pdTASK_HOOK_CODE pxHookFunction );</pre>** Sets pxHookFunction to be the task hook function used by the task xTask.* Passing xTask as NULL has the effect of setting the calling tasks hook* function.*/void vTaskSetApplicationTaskTag( xTaskHandle xTask, pdTASK_HOOK_CODE pxHookFunction ) PRIVILEGED_FUNCTION;/*** task.h* <pre>void xTaskGetApplicationTaskTag( xTaskHandle xTask );</pre>** Returns the pxHookFunction value assigned to the task xTask.*/pdTASK_HOOK_CODE xTaskGetApplicationTaskTag( xTaskHandle xTask ) PRIVILEGED_FUNCTION;#endif /* configUSE_APPLICATION_TASK_TAG ==1 */#endif /* ifdef configUSE_APPLICATION_TASK_TAG *//*** task.h* <pre>portBASE_TYPE xTaskCallApplicationTaskHook( xTaskHandle xTask, pdTASK_HOOK_CODE pxHookFunction );</pre>** Calls the hook function associated with xTask. Passing xTask as NULL has* the effect of calling the Running tasks (the calling task) hook function.** pvParameter is passed to the hook function for the task to interpret as it* wants.*/portBASE_TYPE xTaskCallApplicationTaskHook( xTaskHandle xTask, void *pvParameter ) PRIVILEGED_FUNCTION;/*** xTaskGetIdleTaskHandle() is only available if* INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h.** Simply returns the handle of the idle task. It is not valid to call* xTaskGetIdleTaskHandle() before the scheduler has been started.*/xTaskHandle xTaskGetIdleTaskHandle( void );/*** configUSE_TRACE_FACILITY must bet defined as 1 in FreeRTOSConfig.h for* uxTaskGetSystemState() to be available.** uxTaskGetSystemState() populates an xTaskStatusType structure for each task in* the system. xTaskStatusType structures contain, among other things, members* for the task handle, task name, task priority, task state, and total amount* of run time consumed by the task. See the xTaskStatusType structure* definition in this file for the full member list.** NOTE: This function is intended for debugging use only as its use results in* the scheduler remaining suspended for an extended period.** @param pxTaskStatusArray A pointer to an array of xTaskStatusType structures.* The array must contain at least one xTaskStatusType structure for each task* that is under the control of the RTOS. The number of tasks under the control* of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function.** @param uxArraySize The size of the array pointed to by the pxTaskStatusArray* parameter. The size is specified as the number of indexes in the array, or* the number of xTaskStatusType structures contained in the array, not by the* number of bytes in the array.** @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in* FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the* total run time (as defined by the run time stats clock, see* http://www.freertos.org/rtos-run-time-stats.html) since the target booted.* pulTotalRunTime can be set to NULL to omit the total run time information.** @return The number of xTaskStatusType structures that were populated by* uxTaskGetSystemState(). This should equal the number returned by the* uxTaskGetNumberOfTasks() API function, but will be zero if the value passed* in the uxArraySize parameter was too small.** Example usage:<pre>// This example demonstrates how a human readable table of run time stats// information is generated from raw data provided by uxTaskGetSystemState().// The human readable table is written to pcWriteBuffervoid vTaskGetRunTimeStats( signed char *pcWriteBuffer ){xTaskStatusType *pxTaskStatusArray;volatile unsigned portBASE_TYPE uxArraySize, x;unsigned long ulTotalRunTime, ulStatsAsPercentage;// Make sure the write buffer does not contain a string.*pcWriteBuffer = 0x00;// Take a snapshot of the number of tasks in case it changes while this// function is executing.uxArraySize = uxCurrentNumberOfTasks();// Allocate a xTaskStatusType structure for each task. An array could be// allocated statically at compile time.pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( xTaskStatusType ) );if( pxTaskStatusArray != NULL ){// Generate raw status information about each task.uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );// For percentage calculations.ulTotalRunTime /= 100UL;// Avoid divide by zero errors.if( ulTotalRunTime > 0 ){// For each populated position in the pxTaskStatusArray array,// format the raw data as human readable ASCII datafor( x = 0; x < uxArraySize; x++ ){// What percentage of the total run time has the task used?// This will always be rounded down to the nearest integer.// ulTotalRunTimeDiv100 has already been divided by 100.ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;if( ulStatsAsPercentage > 0UL ){sprintf( ( char * ) pcWriteBuffer, ( char * ) "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );}else{// If the percentage is zero here then the task has// consumed less than 1% of the total run time.sprintf( ( char * ) pcWriteBuffer, ( char * ) "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );}pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );}}// The array is no longer needed, free the memory it consumes.vPortFree( pxTaskStatusArray );}}</pre>*/unsigned portBASE_TYPE uxTaskGetSystemState( xTaskStatusType *pxTaskStatusArray, unsigned portBASE_TYPE uxArraySize, unsigned long *pulTotalRunTime );/*** task. h* <PRE>void vTaskList( char *pcWriteBuffer );</PRE>** configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must* both be defined as 1 for this function to be available. See the* configuration section of the FreeRTOS.org website for more information.** NOTE 1: This function will disable interrupts for its duration. It is* not intended for normal application runtime use but as a debug aid.** Lists all the current tasks, along with their current state and stack* usage high water mark.** Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or* suspended ('S').** PLEASE NOTE:** This function is provided for convenience only, and is used by many of the* demo applications. Do not consider it to be part of the scheduler.** vTaskList() calls uxTaskGetSystemState(), then formats part of the* uxTaskGetSystemState() output into a human readable table that displays task* names, states and stack usage.** vTaskList() has a dependency on the sprintf() C library function that might* bloat the code size, use a lot of stack, and provide different results on* different platforms. An alternative, tiny, third party, and limited* functionality implementation of sprintf() is provided in many of the* FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note* printf-stdarg.c does not provide a full snprintf() implementation!).** It is recommended that production systems call uxTaskGetSystemState()* directly to get access to raw stats data, rather than indirectly through a* call to vTaskList().** @param pcWriteBuffer A buffer into which the above mentioned details* will be written, in ascii form. This buffer is assumed to be large* enough to contain the generated report. Approximately 40 bytes per* task should be sufficient.** \defgroup vTaskList vTaskList* \ingroup TaskUtils*/void vTaskList( signed char *pcWriteBuffer ) PRIVILEGED_FUNCTION;/*** task. h* <PRE>void vTaskGetRunTimeStats( char *pcWriteBuffer );</PRE>** configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS* must both be defined as 1 for this function to be available. The application* must also then provide definitions for* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE* to configure a peripheral timer/counter and return the timers current count* value respectively. The counter should be at least 10 times the frequency of* the tick count.** NOTE 1: This function will disable interrupts for its duration. It is* not intended for normal application runtime use but as a debug aid.** Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total* accumulated execution time being stored for each task. The resolution* of the accumulated time value depends on the frequency of the timer* configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro.* Calling vTaskGetRunTimeStats() writes the total execution time of each* task into a buffer, both as an absolute count value and as a percentage* of the total system execution time.** NOTE 2:** This function is provided for convenience only, and is used by many of the* demo applications. Do not consider it to be part of the scheduler.** vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the* uxTaskGetSystemState() output into a human readable table that displays the* amount of time each task has spent in the Running state in both absolute and* percentage terms.** vTaskGetRunTimeStats() has a dependency on the sprintf() C library function* that might bloat the code size, use a lot of stack, and provide different* results on different platforms. An alternative, tiny, third party, and* limited functionality implementation of sprintf() is provided in many of the* FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note* printf-stdarg.c does not provide a full snprintf() implementation!).** It is recommended that production systems call uxTaskGetSystemState() directly* to get access to raw stats data, rather than indirectly through a call to* vTaskGetRunTimeStats().** @param pcWriteBuffer A buffer into which the execution times will be* written, in ascii form. This buffer is assumed to be large enough to* contain the generated report. Approximately 40 bytes per task should* be sufficient.** \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats* \ingroup TaskUtils*/void vTaskGetRunTimeStats( signed char *pcWriteBuffer ) PRIVILEGED_FUNCTION;/*-----------------------------------------------------------* SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES*----------------------------------------------------------*//** THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY* INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS* AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.** Called from the real time kernel tick (either preemptive or cooperative),* this increments the tick count and checks if any tasks that are blocked* for a finite period required removing from a blocked list and placing on* a ready list. If a non-zero value is returned then a context switch is* required because either:* + A task was removed from a blocked list because its timeout had expired,* or* + Time slicing is in use and there is a task of equal priority to the* currently running task.*/portBASE_TYPE xTaskIncrementTick( void ) PRIVILEGED_FUNCTION;/** THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN* INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.** THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.** Removes the calling task from the ready list and places it both* on the list of tasks waiting for a particular event, and the* list of delayed tasks. The task will be removed from both lists* and replaced on the ready list should either the event occur (and* there be no higher priority tasks waiting on the same event) or* the delay period expires.** @param pxEventList The list containing tasks that are blocked waiting* for the event to occur.** @param xTicksToWait The maximum amount of time that the task should wait* for the event to occur. This is specified in kernel ticks,the constant* portTICK_RATE_MS can be used to convert kernel ticks into a real time* period.*/void vTaskPlaceOnEventList( xList * const pxEventList, portTickType xTicksToWait ) PRIVILEGED_FUNCTION;/** THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN* INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.** THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.** This function performs nearly the same function as vTaskPlaceOnEventList().* The difference being that this function does not permit tasks to block* indefinitely, whereas vTaskPlaceOnEventList() does.** @return pdTRUE if the task being removed has a higher priority than the task* making the call, otherwise pdFALSE.*/void vTaskPlaceOnEventListRestricted( xList * const pxEventList, portTickType xTicksToWait ) PRIVILEGED_FUNCTION;/** THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN* INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.** THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.** Removes a task from both the specified event list and the list of blocked* tasks, and places it on a ready queue.** xTaskRemoveFromEventList () will be called if either an event occurs to* unblock a task, or the block timeout period expires.** @return pdTRUE if the task being removed has a higher priority than the task* making the call, otherwise pdFALSE.*/signed portBASE_TYPE xTaskRemoveFromEventList( const xList * const pxEventList ) PRIVILEGED_FUNCTION;/** THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY* INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS* AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.** Sets the pointer to the current TCB to the TCB of the highest priority task* that is ready to run.*/void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION;/** Return the handle of the calling task.*/xTaskHandle xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION;/** Capture the current time status for future reference.*/void vTaskSetTimeOutState( xTimeOutType * const pxTimeOut ) PRIVILEGED_FUNCTION;/** Compare the time status now with that previously captured to see if the* timeout has expired.*/portBASE_TYPE xTaskCheckForTimeOut( xTimeOutType * const pxTimeOut, portTickType * const pxTicksToWait ) PRIVILEGED_FUNCTION;/** Shortcut used by the queue implementation to prevent unnecessary call to* taskYIELD();*/void vTaskMissedYield( void ) PRIVILEGED_FUNCTION;/** Returns the scheduler state as taskSCHEDULER_RUNNING,* taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED.*/portBASE_TYPE xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION;/** Raises the priority of the mutex holder to that of the calling task should* the mutex holder have a priority less than the calling task.*/void vTaskPriorityInherit( xTaskHandle const pxMutexHolder ) PRIVILEGED_FUNCTION;/** Set the priority of a task back to its proper priority in the case that it* inherited a higher priority while it was holding a semaphore.*/void vTaskPriorityDisinherit( xTaskHandle const pxMutexHolder ) PRIVILEGED_FUNCTION;/** Generic version of the task creation function which is in turn called by the* xTaskCreate() and xTaskCreateRestricted() macros.*/signed portBASE_TYPE xTaskGenericCreate( pdTASK_CODE pxTaskCode, const signed char * const pcName, unsigned short usStackDepth, void *pvParameters, unsigned portBASE_TYPE uxPriority, xTaskHandle *pxCreatedTask, portSTACK_TYPE *puxStackBuffer, const xMemoryRegion * const xRegions ) PRIVILEGED_FUNCTION;/** Get the uxTCBNumber assigned to the task referenced by the xTask parameter.*/unsigned portBASE_TYPE uxTaskGetTaskNumber( xTaskHandle xTask );/** Set the uxTCBNumber of the task referenced by the xTask parameter to* ucHandle.*/void vTaskSetTaskNumber( xTaskHandle xTask, unsigned portBASE_TYPE uxHandle );/** If tickless mode is being used, or a low power mode is implemented, then* the tick interrupt will not execute during idle periods. When this is the* case, the tick count value maintained by the scheduler needs to be kept up* to date with the actual execution time by being skipped forward by the by* a time equal to the idle period.*/void vTaskStepTick( portTickType xTicksToJump );/** Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port* specific sleep function to determine if it is ok to proceed with the sleep,* and if it is ok to proceed, if it is ok to sleep indefinitely.** This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only* called with the scheduler suspended, not from within a critical section. It* is therefore possible for an interrupt to request a context switch between* portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being* entered. eTaskConfirmSleepModeStatus() should be called from a short* critical section between the timer being stopped and the sleep mode being* entered to ensure it is ok to proceed into the sleep mode.*/eSleepModeStatus eTaskConfirmSleepModeStatus( void );#ifdef __cplusplus}#endif#endif /* INC_TASK_H */
123version https://git-lfs.github.com/spec/v1oid sha256:3ecf96d9258125ccb9a5c23909010af9b21b9ca8ec725ead229f70362273683bsize 45744123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef TIMERS_H#define TIMERS_H#ifndef INC_FREERTOS_H#error "include FreeRTOS.h must appear in source files before include timers.h"#endif/*lint -e537 This headers are only multiply included if the application codehappens to also be including task.h. */#include "task.h"/*lint +e956 */#ifdef __cplusplusextern "C" {#endif/* IDs for commands that can be sent/received on the timer queue. These are tobe used solely through the macros that make up the public software timer API,as defined below. */#define tmrCOMMAND_START ( ( portBASE_TYPE ) 0 )#define tmrCOMMAND_STOP ( ( portBASE_TYPE ) 1 )#define tmrCOMMAND_CHANGE_PERIOD ( ( portBASE_TYPE ) 2 )#define tmrCOMMAND_DELETE ( ( portBASE_TYPE ) 3 )/*-----------------------------------------------------------* MACROS AND DEFINITIONS*----------------------------------------------------------*//*** Type by which software timers are referenced. For example, a call to* xTimerCreate() returns an xTimerHandle variable that can then be used to* reference the subject timer in calls to other software timer API functions* (for example, xTimerStart(), xTimerReset(), etc.).*/typedef void * xTimerHandle;/* Define the prototype to which timer callback functions must conform. */typedef void (*tmrTIMER_CALLBACK)( xTimerHandle xTimer );/*** xTimerHandle xTimerCreate( const signed char *pcTimerName,* portTickType xTimerPeriodInTicks,* unsigned portBASE_TYPE uxAutoReload,* void * pvTimerID,* tmrTIMER_CALLBACK pxCallbackFunction );** Creates a new software timer instance. This allocates the storage required* by the new timer, initialises the new timers internal state, and returns a* handle by which the new timer can be referenced.** Timers are created in the dormant state. The xTimerStart(), xTimerReset(),* xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and* xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the* active state.** @param pcTimerName A text name that is assigned to the timer. This is done* purely to assist debugging. The kernel itself only ever references a timer by* its handle, and never by its name.** @param xTimerPeriodInTicks The timer period. The time is defined in tick periods so* the constant portTICK_RATE_MS can be used to convert a time that has been* specified in milliseconds. For example, if the timer must expire after 100* ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer* must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_RATE_MS )* provided configTICK_RATE_HZ is less than or equal to 1000.** @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will* expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If* uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and* enter the dormant state after it expires.** @param pvTimerID An identifier that is assigned to the timer being created.* Typically this would be used in the timer callback function to identify which* timer expired when the same callback function is assigned to more than one* timer.** @param pxCallbackFunction The function to call when the timer expires.* Callback functions must have the prototype defined by tmrTIMER_CALLBACK,* which is "void vCallbackFunction( xTimerHandle xTimer );".** @return If the timer is successfully create then a handle to the newly* created timer is returned. If the timer cannot be created (because either* there is insufficient FreeRTOS heap remaining to allocate the timer* structures, or the timer period was set to 0) then 0 is returned.** Example usage:* @verbatim* #define NUM_TIMERS 5** // An array to hold handles to the created timers.* xTimerHandle xTimers[ NUM_TIMERS ];** // An array to hold a count of the number of times each timer expires.* long lExpireCounters[ NUM_TIMERS ] = { 0 };** // Define a callback function that will be used by multiple timer instances.* // The callback function does nothing but count the number of times the* // associated timer expires, and stop the timer once the timer has expired* // 10 times.* void vTimerCallback( xTimerHandle pxTimer )* {* long lArrayIndex;* const long xMaxExpiryCountBeforeStopping = 10;** // Optionally do something if the pxTimer parameter is NULL.* configASSERT( pxTimer );** // Which timer expired?* lArrayIndex = ( long ) pvTimerGetTimerID( pxTimer );** // Increment the number of times that pxTimer has expired.* lExpireCounters[ lArrayIndex ] += 1;** // If the timer has expired 10 times then stop it from running.* if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping )* {* // Do not use a block time if calling a timer API function from a* // timer callback function, as doing so could cause a deadlock!* xTimerStop( pxTimer, 0 );* }* }** void main( void )* {* long x;** // Create then start some timers. Starting the timers before the scheduler* // has been started means the timers will start running immediately that* // the scheduler starts.* for( x = 0; x < NUM_TIMERS; x++ )* {* xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel.* ( 100 * x ), // The timer period in ticks.* pdTRUE, // The timers will auto-reload themselves when they expire.* ( void * ) x, // Assign each timer a unique id equal to its array index.* vTimerCallback // Each timer calls the same callback when it expires.* );** if( xTimers[ x ] == NULL )* {* // The timer was not created.* }* else* {* // Start the timer. No block time is specified, and even if one was* // it would be ignored because the scheduler has not yet been* // started.* if( xTimerStart( xTimers[ x ], 0 ) != pdPASS )* {* // The timer could not be set into the Active state.* }* }* }** // ...* // Create tasks here.* // ...** // Starting the scheduler will start the timers running as they have already* // been set into the active state.* xTaskStartScheduler();** // Should not reach here.* for( ;; );* }* @endverbatim*/xTimerHandle xTimerCreate( const signed char * const pcTimerName, portTickType xTimerPeriodInTicks, unsigned portBASE_TYPE uxAutoReload, void * pvTimerID, tmrTIMER_CALLBACK pxCallbackFunction ) PRIVILEGED_FUNCTION;/*** void *pvTimerGetTimerID( xTimerHandle xTimer );** Returns the ID assigned to the timer.** IDs are assigned to timers using the pvTimerID parameter of the call to* xTimerCreated() that was used to create the timer.** If the same callback function is assigned to multiple timers then the timer* ID can be used within the callback function to identify which timer actually* expired.** @param xTimer The timer being queried.** @return The ID assigned to the timer being queried.** Example usage:** See the xTimerCreate() API function example usage scenario.*/void *pvTimerGetTimerID( xTimerHandle xTimer ) PRIVILEGED_FUNCTION;/*** portBASE_TYPE xTimerIsTimerActive( xTimerHandle xTimer );** Queries a timer to see if it is active or dormant.** A timer will be dormant if:* 1) It has been created but not started, or* 2) It is an expired on-shot timer that has not been restarted.** Timers are created in the dormant state. The xTimerStart(), xTimerReset(),* xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and* xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the* active state.** @param xTimer The timer being queried.** @return pdFALSE will be returned if the timer is dormant. A value other than* pdFALSE will be returned if the timer is active.** Example usage:* @verbatim* // This function assumes xTimer has already been created.* void vAFunction( xTimerHandle xTimer )* {* if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )"* {* // xTimer is active, do something.* }* else* {* // xTimer is not active, do something else.* }* }* @endverbatim*/portBASE_TYPE xTimerIsTimerActive( xTimerHandle xTimer ) PRIVILEGED_FUNCTION;/*** xTimerGetTimerDaemonTaskHandle() is only available if* INCLUDE_xTimerGetTimerDaemonTaskHandle is set to 1 in FreeRTOSConfig.h.** Simply returns the handle of the timer service/daemon task. It it not valid* to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started.*/xTaskHandle xTimerGetTimerDaemonTaskHandle( void );/*** portBASE_TYPE xTimerStart( xTimerHandle xTimer, portTickType xBlockTime );** Timer functionality is provided by a timer service/daemon task. Many of the* public FreeRTOS timer API functions send commands to the timer service task* though a queue called the timer command queue. The timer command queue is* private to the kernel itself and is not directly accessible to application* code. The length of the timer command queue is set by the* configTIMER_QUEUE_LENGTH configuration constant.** xTimerStart() starts a timer that was previously created using the* xTimerCreate() API function. If the timer had already been started and was* already in the active state, then xTimerStart() has equivalent functionality* to the xTimerReset() API function.** Starting a timer ensures the timer is in the active state. If the timer* is not stopped, deleted, or reset in the mean time, the callback function* associated with the timer will get called 'n' ticks after xTimerStart() was* called, where 'n' is the timers defined period.** It is valid to call xTimerStart() before the scheduler has been started, but* when this is done the timer will not actually start until the scheduler is* started, and the timers expiry time will be relative to when the scheduler is* started, not relative to when xTimerStart() was called.** The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart()* to be available.** @param xTimer The handle of the timer being started/restarted.** @param xBlockTime Specifies the time, in ticks, that the calling task should* be held in the Blocked state to wait for the start command to be successfully* sent to the timer command queue, should the queue already be full when* xTimerStart() was called. xBlockTime is ignored if xTimerStart() is called* before the scheduler is started.** @return pdFAIL will be returned if the start command could not be sent to* the timer command queue even after xBlockTime ticks had passed. pdPASS will* be returned if the command was successfully sent to the timer command queue.* When the command is actually processed will depend on the priority of the* timer service/daemon task relative to other tasks in the system, although the* timers expiry time is relative to when xTimerStart() is actually called. The* timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY* configuration constant.** Example usage:** See the xTimerCreate() API function example usage scenario.**/#define xTimerStart( xTimer, xBlockTime ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xBlockTime ) )/*** portBASE_TYPE xTimerStop( xTimerHandle xTimer, portTickType xBlockTime );** Timer functionality is provided by a timer service/daemon task. Many of the* public FreeRTOS timer API functions send commands to the timer service task* though a queue called the timer command queue. The timer command queue is* private to the kernel itself and is not directly accessible to application* code. The length of the timer command queue is set by the* configTIMER_QUEUE_LENGTH configuration constant.** xTimerStop() stops a timer that was previously started using either of the* The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(),* xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions.** Stopping a timer ensures the timer is not in the active state.** The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop()* to be available.** @param xTimer The handle of the timer being stopped.** @param xBlockTime Specifies the time, in ticks, that the calling task should* be held in the Blocked state to wait for the stop command to be successfully* sent to the timer command queue, should the queue already be full when* xTimerStop() was called. xBlockTime is ignored if xTimerStop() is called* before the scheduler is started.** @return pdFAIL will be returned if the stop command could not be sent to* the timer command queue even after xBlockTime ticks had passed. pdPASS will* be returned if the command was successfully sent to the timer command queue.* When the command is actually processed will depend on the priority of the* timer service/daemon task relative to other tasks in the system. The timer* service/daemon task priority is set by the configTIMER_TASK_PRIORITY* configuration constant.** Example usage:** See the xTimerCreate() API function example usage scenario.**/#define xTimerStop( xTimer, xBlockTime ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xBlockTime ) )/*** portBASE_TYPE xTimerChangePeriod( xTimerHandle xTimer,* portTickType xNewPeriod,* portTickType xBlockTime );** Timer functionality is provided by a timer service/daemon task. Many of the* public FreeRTOS timer API functions send commands to the timer service task* though a queue called the timer command queue. The timer command queue is* private to the kernel itself and is not directly accessible to application* code. The length of the timer command queue is set by the* configTIMER_QUEUE_LENGTH configuration constant.** xTimerChangePeriod() changes the period of a timer that was previously* created using the xTimerCreate() API function.** xTimerChangePeriod() can be called to change the period of an active or* dormant state timer.** The configUSE_TIMERS configuration constant must be set to 1 for* xTimerChangePeriod() to be available.** @param xTimer The handle of the timer that is having its period changed.** @param xNewPeriod The new period for xTimer. Timer periods are specified in* tick periods, so the constant portTICK_RATE_MS can be used to convert a time* that has been specified in milliseconds. For example, if the timer must* expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively,* if the timer must expire after 500ms, then xNewPeriod can be set to* ( 500 / portTICK_RATE_MS ) provided configTICK_RATE_HZ is less than* or equal to 1000.** @param xBlockTime Specifies the time, in ticks, that the calling task should* be held in the Blocked state to wait for the change period command to be* successfully sent to the timer command queue, should the queue already be* full when xTimerChangePeriod() was called. xBlockTime is ignored if* xTimerChangePeriod() is called before the scheduler is started.** @return pdFAIL will be returned if the change period command could not be* sent to the timer command queue even after xBlockTime ticks had passed.* pdPASS will be returned if the command was successfully sent to the timer* command queue. When the command is actually processed will depend on the* priority of the timer service/daemon task relative to other tasks in the* system. The timer service/daemon task priority is set by the* configTIMER_TASK_PRIORITY configuration constant.** Example usage:* @verbatim* // This function assumes xTimer has already been created. If the timer* // referenced by xTimer is already active when it is called, then the timer* // is deleted. If the timer referenced by xTimer is not active when it is* // called, then the period of the timer is set to 500ms and the timer is* // started.* void vAFunction( xTimerHandle xTimer )* {* if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )"* {* // xTimer is already active - delete it.* xTimerDelete( xTimer );* }* else* {* // xTimer is not active, change its period to 500ms. This will also* // cause the timer to start. Block for a maximum of 100 ticks if the* // change period command cannot immediately be sent to the timer* // command queue.* if( xTimerChangePeriod( xTimer, 500 / portTICK_RATE_MS, 100 ) == pdPASS )* {* // The command was successfully sent.* }* else* {* // The command could not be sent, even after waiting for 100 ticks* // to pass. Take appropriate action here.* }* }* }* @endverbatim*/#define xTimerChangePeriod( xTimer, xNewPeriod, xBlockTime ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xBlockTime ) )/*** portBASE_TYPE xTimerDelete( xTimerHandle xTimer, portTickType xBlockTime );** Timer functionality is provided by a timer service/daemon task. Many of the* public FreeRTOS timer API functions send commands to the timer service task* though a queue called the timer command queue. The timer command queue is* private to the kernel itself and is not directly accessible to application* code. The length of the timer command queue is set by the* configTIMER_QUEUE_LENGTH configuration constant.** xTimerDelete() deletes a timer that was previously created using the* xTimerCreate() API function.** The configUSE_TIMERS configuration constant must be set to 1 for* xTimerDelete() to be available.** @param xTimer The handle of the timer being deleted.** @param xBlockTime Specifies the time, in ticks, that the calling task should* be held in the Blocked state to wait for the delete command to be* successfully sent to the timer command queue, should the queue already be* full when xTimerDelete() was called. xBlockTime is ignored if xTimerDelete()* is called before the scheduler is started.** @return pdFAIL will be returned if the delete command could not be sent to* the timer command queue even after xBlockTime ticks had passed. pdPASS will* be returned if the command was successfully sent to the timer command queue.* When the command is actually processed will depend on the priority of the* timer service/daemon task relative to other tasks in the system. The timer* service/daemon task priority is set by the configTIMER_TASK_PRIORITY* configuration constant.** Example usage:** See the xTimerChangePeriod() API function example usage scenario.*/#define xTimerDelete( xTimer, xBlockTime ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xBlockTime ) )/*** portBASE_TYPE xTimerReset( xTimerHandle xTimer, portTickType xBlockTime );** Timer functionality is provided by a timer service/daemon task. Many of the* public FreeRTOS timer API functions send commands to the timer service task* though a queue called the timer command queue. The timer command queue is* private to the kernel itself and is not directly accessible to application* code. The length of the timer command queue is set by the* configTIMER_QUEUE_LENGTH configuration constant.** xTimerReset() re-starts a timer that was previously created using the* xTimerCreate() API function. If the timer had already been started and was* already in the active state, then xTimerReset() will cause the timer to* re-evaluate its expiry time so that it is relative to when xTimerReset() was* called. If the timer was in the dormant state then xTimerReset() has* equivalent functionality to the xTimerStart() API function.** Resetting a timer ensures the timer is in the active state. If the timer* is not stopped, deleted, or reset in the mean time, the callback function* associated with the timer will get called 'n' ticks after xTimerReset() was* called, where 'n' is the timers defined period.** It is valid to call xTimerReset() before the scheduler has been started, but* when this is done the timer will not actually start until the scheduler is* started, and the timers expiry time will be relative to when the scheduler is* started, not relative to when xTimerReset() was called.** The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset()* to be available.** @param xTimer The handle of the timer being reset/started/restarted.** @param xBlockTime Specifies the time, in ticks, that the calling task should* be held in the Blocked state to wait for the reset command to be successfully* sent to the timer command queue, should the queue already be full when* xTimerReset() was called. xBlockTime is ignored if xTimerReset() is called* before the scheduler is started.** @return pdFAIL will be returned if the reset command could not be sent to* the timer command queue even after xBlockTime ticks had passed. pdPASS will* be returned if the command was successfully sent to the timer command queue.* When the command is actually processed will depend on the priority of the* timer service/daemon task relative to other tasks in the system, although the* timers expiry time is relative to when xTimerStart() is actually called. The* timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY* configuration constant.** Example usage:* @verbatim* // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass* // without a key being pressed, then the LCD back-light is switched off. In* // this case, the timer is a one-shot timer.** xTimerHandle xBacklightTimer = NULL;** // The callback function assigned to the one-shot timer. In this case the* // parameter is not used.* void vBacklightTimerCallback( xTimerHandle pxTimer )* {* // The timer expired, therefore 5 seconds must have passed since a key* // was pressed. Switch off the LCD back-light.* vSetBacklightState( BACKLIGHT_OFF );* }** // The key press event handler.* void vKeyPressEventHandler( char cKey )* {* // Ensure the LCD back-light is on, then reset the timer that is* // responsible for turning the back-light off after 5 seconds of* // key inactivity. Wait 10 ticks for the command to be successfully sent* // if it cannot be sent immediately.* vSetBacklightState( BACKLIGHT_ON );* if( xTimerReset( xBacklightTimer, 100 ) != pdPASS )* {* // The reset command was not executed successfully. Take appropriate* // action here.* }** // Perform the rest of the key processing here.* }** void main( void )* {* long x;** // Create then start the one-shot timer that is responsible for turning* // the back-light off if no keys are pressed within a 5 second period.* xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel.* ( 5000 / portTICK_RATE_MS), // The timer period in ticks.* pdFALSE, // The timer is a one-shot timer.* 0, // The id is not used by the callback so can take any value.* vBacklightTimerCallback // The callback function that switches the LCD back-light off.* );** if( xBacklightTimer == NULL )* {* // The timer was not created.* }* else* {* // Start the timer. No block time is specified, and even if one was* // it would be ignored because the scheduler has not yet been* // started.* if( xTimerStart( xBacklightTimer, 0 ) != pdPASS )* {* // The timer could not be set into the Active state.* }* }** // ...* // Create tasks here.* // ...** // Starting the scheduler will start the timer running as it has already* // been set into the active state.* xTaskStartScheduler();** // Should not reach here.* for( ;; );* }* @endverbatim*/#define xTimerReset( xTimer, xBlockTime ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xBlockTime ) )/*** portBASE_TYPE xTimerStartFromISR( xTimerHandle xTimer,* portBASE_TYPE *pxHigherPriorityTaskWoken );** A version of xTimerStart() that can be called from an interrupt service* routine.** @param xTimer The handle of the timer being started/restarted.** @param pxHigherPriorityTaskWoken The timer service/daemon task spends most* of its time in the Blocked state, waiting for messages to arrive on the timer* command queue. Calling xTimerStartFromISR() writes a message to the timer* command queue, so has the potential to transition the timer service/daemon* task out of the Blocked state. If calling xTimerStartFromISR() causes the* timer service/daemon task to leave the Blocked state, and the timer service/* daemon task has a priority equal to or greater than the currently executing* task (the task that was interrupted), then *pxHigherPriorityTaskWoken will* get set to pdTRUE internally within the xTimerStartFromISR() function. If* xTimerStartFromISR() sets this value to pdTRUE then a context switch should* be performed before the interrupt exits.** @return pdFAIL will be returned if the start command could not be sent to* the timer command queue. pdPASS will be returned if the command was* successfully sent to the timer command queue. When the command is actually* processed will depend on the priority of the timer service/daemon task* relative to other tasks in the system, although the timers expiry time is* relative to when xTimerStartFromISR() is actually called. The timer service/daemon* task priority is set by the configTIMER_TASK_PRIORITY configuration constant.** Example usage:* @verbatim* // This scenario assumes xBacklightTimer has already been created. When a* // key is pressed, an LCD back-light is switched on. If 5 seconds pass* // without a key being pressed, then the LCD back-light is switched off. In* // this case, the timer is a one-shot timer, and unlike the example given for* // the xTimerReset() function, the key press event handler is an interrupt* // service routine.** // The callback function assigned to the one-shot timer. In this case the* // parameter is not used.* void vBacklightTimerCallback( xTimerHandle pxTimer )* {* // The timer expired, therefore 5 seconds must have passed since a key* // was pressed. Switch off the LCD back-light.* vSetBacklightState( BACKLIGHT_OFF );* }** // The key press interrupt service routine.* void vKeyPressEventInterruptHandler( void )* {* portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;** // Ensure the LCD back-light is on, then restart the timer that is* // responsible for turning the back-light off after 5 seconds of* // key inactivity. This is an interrupt service routine so can only* // call FreeRTOS API functions that end in "FromISR".* vSetBacklightState( BACKLIGHT_ON );** // xTimerStartFromISR() or xTimerResetFromISR() could be called here* // as both cause the timer to re-calculate its expiry time.* // xHigherPriorityTaskWoken was initialised to pdFALSE when it was* // declared (in this function).* if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS )* {* // The start command was not executed successfully. Take appropriate* // action here.* }** // Perform the rest of the key processing here.** // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch* // should be performed. The syntax required to perform a context switch* // from inside an ISR varies from port to port, and from compiler to* // compiler. Inspect the demos for the port you are using to find the* // actual syntax required.* if( xHigherPriorityTaskWoken != pdFALSE )* {* // Call the interrupt safe yield function here (actual function* // depends on the FreeRTOS port being used.* }* }* @endverbatim*/#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U )/*** portBASE_TYPE xTimerStopFromISR( xTimerHandle xTimer,* portBASE_TYPE *pxHigherPriorityTaskWoken );** A version of xTimerStop() that can be called from an interrupt service* routine.** @param xTimer The handle of the timer being stopped.** @param pxHigherPriorityTaskWoken The timer service/daemon task spends most* of its time in the Blocked state, waiting for messages to arrive on the timer* command queue. Calling xTimerStopFromISR() writes a message to the timer* command queue, so has the potential to transition the timer service/daemon* task out of the Blocked state. If calling xTimerStopFromISR() causes the* timer service/daemon task to leave the Blocked state, and the timer service/* daemon task has a priority equal to or greater than the currently executing* task (the task that was interrupted), then *pxHigherPriorityTaskWoken will* get set to pdTRUE internally within the xTimerStopFromISR() function. If* xTimerStopFromISR() sets this value to pdTRUE then a context switch should* be performed before the interrupt exits.** @return pdFAIL will be returned if the stop command could not be sent to* the timer command queue. pdPASS will be returned if the command was* successfully sent to the timer command queue. When the command is actually* processed will depend on the priority of the timer service/daemon task* relative to other tasks in the system. The timer service/daemon task* priority is set by the configTIMER_TASK_PRIORITY configuration constant.** Example usage:* @verbatim* // This scenario assumes xTimer has already been created and started. When* // an interrupt occurs, the timer should be simply stopped.** // The interrupt service routine that stops the timer.* void vAnExampleInterruptServiceRoutine( void )* {* portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;** // The interrupt has occurred - simply stop the timer.* // xHigherPriorityTaskWoken was set to pdFALSE where it was defined* // (within this function). As this is an interrupt service routine, only* // FreeRTOS API functions that end in "FromISR" can be used.* if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS )* {* // The stop command was not executed successfully. Take appropriate* // action here.* }** // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch* // should be performed. The syntax required to perform a context switch* // from inside an ISR varies from port to port, and from compiler to* // compiler. Inspect the demos for the port you are using to find the* // actual syntax required.* if( xHigherPriorityTaskWoken != pdFALSE )* {* // Call the interrupt safe yield function here (actual function* // depends on the FreeRTOS port being used.* }* }* @endverbatim*/#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0, ( pxHigherPriorityTaskWoken ), 0U )/*** portBASE_TYPE xTimerChangePeriodFromISR( xTimerHandle xTimer,* portTickType xNewPeriod,* portBASE_TYPE *pxHigherPriorityTaskWoken );** A version of xTimerChangePeriod() that can be called from an interrupt* service routine.** @param xTimer The handle of the timer that is having its period changed.** @param xNewPeriod The new period for xTimer. Timer periods are specified in* tick periods, so the constant portTICK_RATE_MS can be used to convert a time* that has been specified in milliseconds. For example, if the timer must* expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively,* if the timer must expire after 500ms, then xNewPeriod can be set to* ( 500 / portTICK_RATE_MS ) provided configTICK_RATE_HZ is less than* or equal to 1000.** @param pxHigherPriorityTaskWoken The timer service/daemon task spends most* of its time in the Blocked state, waiting for messages to arrive on the timer* command queue. Calling xTimerChangePeriodFromISR() writes a message to the* timer command queue, so has the potential to transition the timer service/* daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR()* causes the timer service/daemon task to leave the Blocked state, and the* timer service/daemon task has a priority equal to or greater than the* currently executing task (the task that was interrupted), then* *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the* xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets* this value to pdTRUE then a context switch should be performed before the* interrupt exits.** @return pdFAIL will be returned if the command to change the timers period* could not be sent to the timer command queue. pdPASS will be returned if the* command was successfully sent to the timer command queue. When the command* is actually processed will depend on the priority of the timer service/daemon* task relative to other tasks in the system. The timer service/daemon task* priority is set by the configTIMER_TASK_PRIORITY configuration constant.** Example usage:* @verbatim* // This scenario assumes xTimer has already been created and started. When* // an interrupt occurs, the period of xTimer should be changed to 500ms.** // The interrupt service routine that changes the period of xTimer.* void vAnExampleInterruptServiceRoutine( void )* {* portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;** // The interrupt has occurred - change the period of xTimer to 500ms.* // xHigherPriorityTaskWoken was set to pdFALSE where it was defined* // (within this function). As this is an interrupt service routine, only* // FreeRTOS API functions that end in "FromISR" can be used.* if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS )* {* // The command to change the timers period was not executed* // successfully. Take appropriate action here.* }** // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch* // should be performed. The syntax required to perform a context switch* // from inside an ISR varies from port to port, and from compiler to* // compiler. Inspect the demos for the port you are using to find the* // actual syntax required.* if( xHigherPriorityTaskWoken != pdFALSE )* {* // Call the interrupt safe yield function here (actual function* // depends on the FreeRTOS port being used.* }* }* @endverbatim*/#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U )/*** portBASE_TYPE xTimerResetFromISR( xTimerHandle xTimer,* portBASE_TYPE *pxHigherPriorityTaskWoken );** A version of xTimerReset() that can be called from an interrupt service* routine.** @param xTimer The handle of the timer that is to be started, reset, or* restarted.** @param pxHigherPriorityTaskWoken The timer service/daemon task spends most* of its time in the Blocked state, waiting for messages to arrive on the timer* command queue. Calling xTimerResetFromISR() writes a message to the timer* command queue, so has the potential to transition the timer service/daemon* task out of the Blocked state. If calling xTimerResetFromISR() causes the* timer service/daemon task to leave the Blocked state, and the timer service/* daemon task has a priority equal to or greater than the currently executing* task (the task that was interrupted), then *pxHigherPriorityTaskWoken will* get set to pdTRUE internally within the xTimerResetFromISR() function. If* xTimerResetFromISR() sets this value to pdTRUE then a context switch should* be performed before the interrupt exits.** @return pdFAIL will be returned if the reset command could not be sent to* the timer command queue. pdPASS will be returned if the command was* successfully sent to the timer command queue. When the command is actually* processed will depend on the priority of the timer service/daemon task* relative to other tasks in the system, although the timers expiry time is* relative to when xTimerResetFromISR() is actually called. The timer service/daemon* task priority is set by the configTIMER_TASK_PRIORITY configuration constant.** Example usage:* @verbatim* // This scenario assumes xBacklightTimer has already been created. When a* // key is pressed, an LCD back-light is switched on. If 5 seconds pass* // without a key being pressed, then the LCD back-light is switched off. In* // this case, the timer is a one-shot timer, and unlike the example given for* // the xTimerReset() function, the key press event handler is an interrupt* // service routine.** // The callback function assigned to the one-shot timer. In this case the* // parameter is not used.* void vBacklightTimerCallback( xTimerHandle pxTimer )* {* // The timer expired, therefore 5 seconds must have passed since a key* // was pressed. Switch off the LCD back-light.* vSetBacklightState( BACKLIGHT_OFF );* }** // The key press interrupt service routine.* void vKeyPressEventInterruptHandler( void )* {* portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;** // Ensure the LCD back-light is on, then reset the timer that is* // responsible for turning the back-light off after 5 seconds of* // key inactivity. This is an interrupt service routine so can only* // call FreeRTOS API functions that end in "FromISR".* vSetBacklightState( BACKLIGHT_ON );** // xTimerStartFromISR() or xTimerResetFromISR() could be called here* // as both cause the timer to re-calculate its expiry time.* // xHigherPriorityTaskWoken was initialised to pdFALSE when it was* // declared (in this function).* if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS )* {* // The reset command was not executed successfully. Take appropriate* // action here.* }** // Perform the rest of the key processing here.** // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch* // should be performed. The syntax required to perform a context switch* // from inside an ISR varies from port to port, and from compiler to* // compiler. Inspect the demos for the port you are using to find the* // actual syntax required.* if( xHigherPriorityTaskWoken != pdFALSE )* {* // Call the interrupt safe yield function here (actual function* // depends on the FreeRTOS port being used.* }* }* @endverbatim*/#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U )/** Functions beyond this part are not part of the public API and are intended* for use by the kernel only.*/portBASE_TYPE xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION;portBASE_TYPE xTimerGenericCommand( xTimerHandle xTimer, portBASE_TYPE xCommandID, portTickType xOptionalValue, signed portBASE_TYPE *pxHigherPriorityTaskWoken, portTickType xBlockTime ) PRIVILEGED_FUNCTION;#ifdef __cplusplus}#endif#endif /* TIMERS_H */
123version https://git-lfs.github.com/spec/v1oid sha256:a0ea80bb79d1af64878a096de842e75f8df74151ccd6b3cd30c3a01c5ecef6f7size 9305123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#include <stdlib.h>#include "FreeRTOS.h"#include "list.h"/*-----------------------------------------------------------* PUBLIC LIST API documented in list.h*----------------------------------------------------------*/void vListInitialise( xList * const pxList ){/* The list structure contains a list item which is used to mark theend of the list. To initialise the list the list end is insertedas the only list entry. */pxList->pxIndex = ( xListItem * ) &( pxList->xListEnd ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. *//* The list end value is the highest possible value in the list toensure it remains at the end of the list. */pxList->xListEnd.xItemValue = portMAX_DELAY;/* The list end next and previous pointers point to itself so we knowwhen the list is empty. */pxList->xListEnd.pxNext = ( xListItem * ) &( pxList->xListEnd ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */pxList->xListEnd.pxPrevious = ( xListItem * ) &( pxList->xListEnd );/*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */pxList->uxNumberOfItems = ( unsigned portBASE_TYPE ) 0U;}/*-----------------------------------------------------------*/void vListInitialiseItem( xListItem * const pxItem ){/* Make sure the list item is not recorded as being on a list. */pxItem->pvContainer = NULL;}/*-----------------------------------------------------------*/void vListInsertEnd( xList * const pxList, xListItem * const pxNewListItem ){xListItem * pxIndex;/* Insert a new list item into pxList, but rather than sort the list,makes the new list item the last item to be removed by a call topvListGetOwnerOfNextEntry. */pxIndex = pxList->pxIndex;pxNewListItem->pxNext = pxIndex;pxNewListItem->pxPrevious = pxIndex->pxPrevious;pxIndex->pxPrevious->pxNext = pxNewListItem;pxIndex->pxPrevious = pxNewListItem;/* Remember which list the item is in. */pxNewListItem->pvContainer = ( void * ) pxList;( pxList->uxNumberOfItems )++;}/*-----------------------------------------------------------*/void vListInsert( xList * const pxList, xListItem * const pxNewListItem ){xListItem *pxIterator;portTickType xValueOfInsertion;/* Insert the new list item into the list, sorted in ulListItem order. */xValueOfInsertion = pxNewListItem->xItemValue;/* If the list already contains a list item with the same item value thenthe new list item should be placed after it. This ensures that TCB's whichare stored in ready lists (all of which have the same ulListItem value)get an equal share of the CPU. However, if the xItemValue is the same asthe back marker the iteration loop below will not end. This means we needto guard against this by checking the value first and modifying thealgorithm slightly if necessary. */if( xValueOfInsertion == portMAX_DELAY ){pxIterator = pxList->xListEnd.pxPrevious;}else{/* *** NOTE ***********************************************************If you find your application is crashing here then likely causes are:1) Stack overflow -see http://www.freertos.org/Stacks-and-stack-overflow-checking.html2) Incorrect interrupt priority assignment, especially on Cortex-M3parts where numerically high priority values denote low actualinterrupt priories, which can seem counter intuitive. SeeconfigMAX_SYSCALL_INTERRUPT_PRIORITY on http://www.freertos.org/a00110.html3) Calling an API function from within a critical section or whenthe scheduler is suspended, or calling an API function that doesnot end in "FromISR" from an interrupt.4) Using a queue or semaphore before it has been initialised orbefore the scheduler has been started (are interrupts firingbefore vTaskStartScheduler() has been called?).See http://www.freertos.org/FAQHelp.html for more tips.**********************************************************************/for( pxIterator = ( xListItem * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */{/* There is nothing to do here, we are just iterating to thewanted insertion position. */}}pxNewListItem->pxNext = pxIterator->pxNext;pxNewListItem->pxNext->pxPrevious = pxNewListItem;pxNewListItem->pxPrevious = pxIterator;pxIterator->pxNext = pxNewListItem;/* Remember which list the item is in. This allows fast removal of theitem later. */pxNewListItem->pvContainer = ( void * ) pxList;( pxList->uxNumberOfItems )++;}/*-----------------------------------------------------------*/unsigned portBASE_TYPE uxListRemove( xListItem * const pxItemToRemove ){xList * pxList;pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious;pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext;/* The list item knows which list it is in. Obtain the list from the listitem. */pxList = ( xList * ) pxItemToRemove->pvContainer;/* Make sure the index is left pointing to a valid item. */if( pxList->pxIndex == pxItemToRemove ){pxList->pxIndex = pxItemToRemove->pxPrevious;}pxItemToRemove->pvContainer = NULL;( pxList->uxNumberOfItems )--;return pxList->uxNumberOfItems;}/*-----------------------------------------------------------*/
123version https://git-lfs.github.com/spec/v1oid sha256:36cc532fcb4c3feae6400dcea6cd58eecfb2066e85a6fc5d39dc87cf6b90826fsize 6818123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//** The simplest possible implementation of pvPortMalloc(). Note that this* implementation does NOT allow allocated memory to be freed again.** See heap_2.c, heap_3.c and heap_4.c for alternative implementations, and the* memory management pages of http://www.FreeRTOS.org for more information.*/#include <stdlib.h>/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefiningall the API functions to use the MPU wrappers. That should only be done whentask.h is included from an application file. */#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE#include "FreeRTOS.h"#include "task.h"#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE/* A few bytes might be lost to byte aligning the heap start address. */#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )/* Allocate the memory for the heap. */static unsigned char ucHeap[ configTOTAL_HEAP_SIZE ];static size_t xNextFreeByte = ( size_t ) 0;/*-----------------------------------------------------------*/void *pvPortMalloc( size_t xWantedSize ){void *pvReturn = NULL;static unsigned char *pucAlignedHeap = NULL;/* Ensure that blocks are always aligned to the required number of bytes. */#if portBYTE_ALIGNMENT != 1if( xWantedSize & portBYTE_ALIGNMENT_MASK ){/* Byte alignment required. */xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );}#endifvTaskSuspendAll();{if( pucAlignedHeap == NULL ){/* Ensure the heap starts on a correctly aligned boundary. */pucAlignedHeap = ( unsigned char * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ( portPOINTER_SIZE_TYPE ) ~portBYTE_ALIGNMENT_MASK ) );}/* Check there is enough room left for the allocation. */if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) &&( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) )/* Check for overflow. */{/* Return the next free byte then increment the index past thisblock. */pvReturn = pucAlignedHeap + xNextFreeByte;xNextFreeByte += xWantedSize;}traceMALLOC( pvReturn, xWantedSize );}xTaskResumeAll();#if( configUSE_MALLOC_FAILED_HOOK == 1 ){if( pvReturn == NULL ){extern void vApplicationMallocFailedHook( void );vApplicationMallocFailedHook();}}#endifreturn pvReturn;}/*-----------------------------------------------------------*/void vPortFree( void *pv ){/* Memory cannot be freed using this scheme. See heap_2.c, heap_3.c andheap_4.c for alternative implementations, and the memory management pages ofhttp://www.FreeRTOS.org for more information. */( void ) pv;/* Force an assert as it is invalid to call this function. */configASSERT( pv == NULL );}/*-----------------------------------------------------------*/void vPortInitialiseBlocks( void ){/* Only required when static memory is not cleared. */xNextFreeByte = ( size_t ) 0;}/*-----------------------------------------------------------*/size_t xPortGetFreeHeapSize( void ){return ( configADJUSTED_HEAP_SIZE - xNextFreeByte );}
123version https://git-lfs.github.com/spec/v1oid sha256:c544d6593ef3b54cd4271f008fc117327c6dd31ccb1ad9cb1a114e75ea893c2fsize 11927123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//** A sample implementation of pvPortMalloc() and vPortFree() that permits* allocated blocks to be freed, but does not combine adjacent free blocks* into a single larger block (and so will fragment memory). See heap_4.c for* an equivalent that does combine adjacent blocks into single larger blocks.** See heap_1.c, heap_3.c and heap_4.c for alternative implementations, and the* memory management pages of http://www.FreeRTOS.org for more information.*/#include <stdlib.h>/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefiningall the API functions to use the MPU wrappers. That should only be done whentask.h is included from an application file. */#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE#include "FreeRTOS.h"#include "task.h"#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE/* A few bytes might be lost to byte aligning the heap start address. */#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )/** Initialises the heap structures before their first use.*/static void prvHeapInit( void );/* Allocate the memory for the heap. */static unsigned char ucHeap[ configTOTAL_HEAP_SIZE ];/* Define the linked list structure. This is used to link free blocks in orderof their size. */typedef struct A_BLOCK_LINK{struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */size_t xBlockSize; /*<< The size of the free block. */} xBlockLink;static const unsigned short heapSTRUCT_SIZE = ( ( sizeof ( xBlockLink ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) )/* Create a couple of list links to mark the start and end of the list. */static xBlockLink xStart, xEnd;/* Keeps track of the number of free bytes remaining, but says nothing aboutfragmentation. */static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;/* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. *//** Insert a block into the list of free blocks - which is ordered by size of* the block. Small blocks at the start of the list and large blocks at the end* of the list.*/#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \{ \xBlockLink *pxIterator; \size_t xBlockSize; \\xBlockSize = pxBlockToInsert->xBlockSize; \\/* Iterate through the list until a block is found that has a larger size */ \/* than the block we are inserting. */ \for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \{ \/* There is nothing to do here - just iterate to the correct position. */ \} \\/* Update the list to include the block being inserted in the correct */ \/* position. */ \pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \pxIterator->pxNextFreeBlock = pxBlockToInsert; \}/*-----------------------------------------------------------*/void *pvPortMalloc( size_t xWantedSize ){xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink;static portBASE_TYPE xHeapHasBeenInitialised = pdFALSE;void *pvReturn = NULL;vTaskSuspendAll();{/* If this is the first call to malloc then the heap will requireinitialisation to setup the list of free blocks. */if( xHeapHasBeenInitialised == pdFALSE ){prvHeapInit();xHeapHasBeenInitialised = pdTRUE;}/* The wanted size is increased so it can contain a xBlockLinkstructure in addition to the requested amount of bytes. */if( xWantedSize > 0 ){xWantedSize += heapSTRUCT_SIZE;/* Ensure that blocks are always aligned to the required number of bytes. */if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 ){/* Byte alignment required. */xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );}}if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) ){/* Blocks are stored in byte order - traverse the list from the start(smallest) block until one of adequate size is found. */pxPreviousBlock = &xStart;pxBlock = xStart.pxNextFreeBlock;while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ){pxPreviousBlock = pxBlock;pxBlock = pxBlock->pxNextFreeBlock;}/* If we found the end marker then a block of adequate size was not found. */if( pxBlock != &xEnd ){/* Return the memory space - jumping over the xBlockLink structureat its start. */pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );/* This block is being returned for use so must be taken out of thelist of free blocks. */pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;/* If the block is larger than required it can be split into two. */if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ){/* This block is to be split into two. Create a new blockfollowing the number of bytes requested. The void cast isused to prevent byte alignment warnings from the compiler. */pxNewBlockLink = ( void * ) ( ( ( unsigned char * ) pxBlock ) + xWantedSize );/* Calculate the sizes of two blocks split from the singleblock. */pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;pxBlock->xBlockSize = xWantedSize;/* Insert the new block into the list of free blocks. */prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );}xFreeBytesRemaining -= pxBlock->xBlockSize;}}traceMALLOC( pvReturn, xWantedSize );}xTaskResumeAll();#if( configUSE_MALLOC_FAILED_HOOK == 1 ){if( pvReturn == NULL ){extern void vApplicationMallocFailedHook( void );vApplicationMallocFailedHook();}}#endifreturn pvReturn;}/*-----------------------------------------------------------*/void vPortFree( void *pv ){unsigned char *puc = ( unsigned char * ) pv;xBlockLink *pxLink;if( pv != NULL ){/* The memory being freed will have an xBlockLink structure immediatelybefore it. */puc -= heapSTRUCT_SIZE;/* This unexpected casting is to keep some compilers from issuingbyte alignment warnings. */pxLink = ( void * ) puc;vTaskSuspendAll();{/* Add this block to the list of free blocks. */prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) );xFreeBytesRemaining += pxLink->xBlockSize;traceFREE( pv, pxLink->xBlockSize );}xTaskResumeAll();}}/*-----------------------------------------------------------*/size_t xPortGetFreeHeapSize( void ){return xFreeBytesRemaining;}/*-----------------------------------------------------------*/void vPortInitialiseBlocks( void ){/* This just exists to keep the linker quiet. */}/*-----------------------------------------------------------*/static void prvHeapInit( void ){xBlockLink *pxFirstFreeBlock;unsigned char *pucAlignedHeap;/* Ensure the heap starts on a correctly aligned boundary. */pucAlignedHeap = ( unsigned char * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ( portPOINTER_SIZE_TYPE ) ~portBYTE_ALIGNMENT_MASK ) );/* xStart is used to hold a pointer to the first item in the list of freeblocks. The void cast is used to prevent compiler warnings. */xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;xStart.xBlockSize = ( size_t ) 0;/* xEnd is used to mark the end of the list of free blocks. */xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;xEnd.pxNextFreeBlock = NULL;/* To start with there is a single free block that is sized to take up theentire heap space. */pxFirstFreeBlock = ( void * ) pucAlignedHeap;pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;pxFirstFreeBlock->pxNextFreeBlock = &xEnd;}/*-----------------------------------------------------------*/
123version https://git-lfs.github.com/spec/v1oid sha256:e5bb73448f669445c766fd81f6a9220bfdc629764603fcf775e7a383f6c0672esize 5057123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//** Implementation of pvPortMalloc() and vPortFree() that relies on the* compilers own malloc() and free() implementations.** This file can only be used if the linker is configured to to generate* a heap memory area.** See heap_1.c, heap_2.c and heap_4.c for alternative implementations, and the* memory management pages of http://www.FreeRTOS.org for more information.*/#include <stdlib.h>/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefiningall the API functions to use the MPU wrappers. That should only be done whentask.h is included from an application file. */#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE#include "FreeRTOS.h"#include "task.h"#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE/*-----------------------------------------------------------*/void *pvPortMalloc( size_t xWantedSize ){void *pvReturn;vTaskSuspendAll();{pvReturn = malloc( xWantedSize );traceMALLOC( pvReturn, xWantedSize );}xTaskResumeAll();#if( configUSE_MALLOC_FAILED_HOOK == 1 ){if( pvReturn == NULL ){extern void vApplicationMallocFailedHook( void );vApplicationMallocFailedHook();}}#endifreturn pvReturn;}/*-----------------------------------------------------------*/void vPortFree( void *pv ){if( pv ){vTaskSuspendAll();{free( pv );traceFREE( pv, 0 );}xTaskResumeAll();}}
123version https://git-lfs.github.com/spec/v1oid sha256:3bcf375c903a1fb4f9e2d2140836f1c6501ccf76bddc9658e4fdb91c530760e5size 15141123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//** A sample implementation of pvPortMalloc() and vPortFree() that combines* (coalescences) adjacent memory blocks as they are freed, and in so doing* limits memory fragmentation.** See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the* memory management pages of http://www.FreeRTOS.org for more information.*/#include <stdlib.h>/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefiningall the API functions to use the MPU wrappers. That should only be done whentask.h is included from an application file. */#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE#include "FreeRTOS.h"#include "task.h"#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE/* Block sizes must not get too small. */#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) )/* Assumes 8bit bytes! */#define heapBITS_PER_BYTE ( ( size_t ) 8 )/* A few bytes might be lost to byte aligning the heap start address. */#define heapADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )/* Allocate the memory for the heap. */static unsigned char ucHeap[ configTOTAL_HEAP_SIZE ];/* Define the linked list structure. This is used to link free blocks in orderof their memory address. */typedef struct A_BLOCK_LINK{struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */size_t xBlockSize; /*<< The size of the free block. */} xBlockLink;/*-----------------------------------------------------------*//** Inserts a block of memory that is being freed into the correct position in* the list of free memory blocks. The block being freed will be merged with* the block in front it and/or the block behind it if the memory blocks are* adjacent to each other.*/static void prvInsertBlockIntoFreeList( xBlockLink *pxBlockToInsert );/** Called automatically to setup the required heap structures the first time* pvPortMalloc() is called.*/static void prvHeapInit( void );/*-----------------------------------------------------------*//* The size of the structure placed at the beginning of each allocated memoryblock must by correctly byte aligned. */static const unsigned short heapSTRUCT_SIZE = ( ( sizeof ( xBlockLink ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );/* Ensure the pxEnd pointer will end up on the correct byte alignment. */static const size_t xTotalHeapSize = ( ( size_t ) heapADJUSTED_HEAP_SIZE ) & ( ( size_t ) ~portBYTE_ALIGNMENT_MASK );/* Create a couple of list links to mark the start and end of the list. */static xBlockLink xStart, *pxEnd = NULL;/* Keeps track of the number of free bytes remaining, but says nothing aboutfragmentation. */static size_t xFreeBytesRemaining = ( ( size_t ) heapADJUSTED_HEAP_SIZE ) & ( ( size_t ) ~portBYTE_ALIGNMENT_MASK );/* Gets set to the top bit of an size_t type. When this bit in the xBlockSizemember of an xBlockLink structure is set then the block belongs to theapplication. When the bit is free the block is still part of the free heapspace. */static size_t xBlockAllocatedBit = 0;/*-----------------------------------------------------------*/void *pvPortMalloc( size_t xWantedSize ){xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink;void *pvReturn = NULL;vTaskSuspendAll();{/* If this is the first call to malloc then the heap will requireinitialisation to setup the list of free blocks. */if( pxEnd == NULL ){prvHeapInit();}/* Check the requested block size is not so large that the top bit isset. The top bit of the block size member of the xBlockLink structureis used to determine who owns the block - the application or thekernel, so it must be free. */if( ( xWantedSize & xBlockAllocatedBit ) == 0 ){/* The wanted size is increased so it can contain a xBlockLinkstructure in addition to the requested amount of bytes. */if( xWantedSize > 0 ){xWantedSize += heapSTRUCT_SIZE;/* Ensure that blocks are always aligned to the required numberof bytes. */if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ){/* Byte alignment required. */xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );}}if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ){/* Traverse the list from the start (lowest address) block untilone of adequate size is found. */pxPreviousBlock = &xStart;pxBlock = xStart.pxNextFreeBlock;while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ){pxPreviousBlock = pxBlock;pxBlock = pxBlock->pxNextFreeBlock;}/* If the end marker was reached then a block of adequate sizewas not found. */if( pxBlock != pxEnd ){/* Return the memory space pointed to - jumping over thexBlockLink structure at its start. */pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );/* This block is being returned for use so must be taken outof the list of free blocks. */pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;/* If the block is larger than required it can be split intotwo. */if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ){/* This block is to be split into two. Create a newblock following the number of bytes requested. The voidcast is used to prevent byte alignment warnings from thecompiler. */pxNewBlockLink = ( void * ) ( ( ( unsigned char * ) pxBlock ) + xWantedSize );/* Calculate the sizes of two blocks split from thesingle block. */pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;pxBlock->xBlockSize = xWantedSize;/* Insert the new block into the list of free blocks. */prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );}xFreeBytesRemaining -= pxBlock->xBlockSize;/* The block is being returned - it is allocated and ownedby the application and has no "next" block. */pxBlock->xBlockSize |= xBlockAllocatedBit;pxBlock->pxNextFreeBlock = NULL;}}}traceMALLOC( pvReturn, xWantedSize );}xTaskResumeAll();#if( configUSE_MALLOC_FAILED_HOOK == 1 ){if( pvReturn == NULL ){extern void vApplicationMallocFailedHook( void );vApplicationMallocFailedHook();}}#endifreturn pvReturn;}/*-----------------------------------------------------------*/void vPortFree( void *pv ){unsigned char *puc = ( unsigned char * ) pv;xBlockLink *pxLink;if( pv != NULL ){/* The memory being freed will have an xBlockLink structure immediatelybefore it. */puc -= heapSTRUCT_SIZE;/* This casting is to keep the compiler from issuing warnings. */pxLink = ( void * ) puc;/* Check the block is actually allocated. */configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );configASSERT( pxLink->pxNextFreeBlock == NULL );if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ){if( pxLink->pxNextFreeBlock == NULL ){/* The block is being returned to the heap - it is no longerallocated. */pxLink->xBlockSize &= ~xBlockAllocatedBit;vTaskSuspendAll();{/* Add this block to the list of free blocks. */xFreeBytesRemaining += pxLink->xBlockSize;prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) );traceFREE( pv, pxLink->xBlockSize );}xTaskResumeAll();}}}}/*-----------------------------------------------------------*/size_t xPortGetFreeHeapSize( void ){return xFreeBytesRemaining;}/*-----------------------------------------------------------*/void vPortInitialiseBlocks( void ){/* This just exists to keep the linker quiet. */}/*-----------------------------------------------------------*/static void prvHeapInit( void ){xBlockLink *pxFirstFreeBlock;unsigned char *pucHeapEnd, *pucAlignedHeap;/* Ensure the heap starts on a correctly aligned boundary. */pucAlignedHeap = ( unsigned char * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ( portPOINTER_SIZE_TYPE ) ~portBYTE_ALIGNMENT_MASK ) );/* xStart is used to hold a pointer to the first item in the list of freeblocks. The void cast is used to prevent compiler warnings. */xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;xStart.xBlockSize = ( size_t ) 0;/* pxEnd is used to mark the end of the list of free blocks and is insertedat the end of the heap space. */pucHeapEnd = pucAlignedHeap + xTotalHeapSize;pucHeapEnd -= heapSTRUCT_SIZE;pxEnd = ( void * ) pucHeapEnd;configASSERT( ( ( ( unsigned long ) pxEnd ) & ( ( unsigned long ) portBYTE_ALIGNMENT_MASK ) ) == 0UL );pxEnd->xBlockSize = 0;pxEnd->pxNextFreeBlock = NULL;/* To start with there is a single free block that is sized to take up theentire heap space, minus the space taken by pxEnd. */pxFirstFreeBlock = ( void * ) pucAlignedHeap;pxFirstFreeBlock->xBlockSize = xTotalHeapSize - heapSTRUCT_SIZE;pxFirstFreeBlock->pxNextFreeBlock = pxEnd;/* The heap now contains pxEnd. */xFreeBytesRemaining -= heapSTRUCT_SIZE;/* Work out the position of the top bit in a size_t variable. */xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );}/*-----------------------------------------------------------*/static void prvInsertBlockIntoFreeList( xBlockLink *pxBlockToInsert ){xBlockLink *pxIterator;unsigned char *puc;/* Iterate through the list until a block is found that has a higher addressthan the block being inserted. */for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ){/* Nothing to do here, just iterate to the right position. */}/* Do the block being inserted, and the block it is being inserted aftermake a contiguous block of memory? */puc = ( unsigned char * ) pxIterator;if( ( puc + pxIterator->xBlockSize ) == ( unsigned char * ) pxBlockToInsert ){pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;pxBlockToInsert = pxIterator;}/* Do the block being inserted, and the block it is being inserted beforemake a contiguous block of memory? */puc = ( unsigned char * ) pxBlockToInsert;if( ( puc + pxBlockToInsert->xBlockSize ) == ( unsigned char * ) pxIterator->pxNextFreeBlock ){if( pxIterator->pxNextFreeBlock != pxEnd ){/* Form one big block from the two blocks. */pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;}else{pxBlockToInsert->pxNextFreeBlock = pxEnd;}}else{pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;}/* If the block being inserted plugged a gab, so was merged with the blockbefore and the block after, then it's pxNextFreeBlock pointer will havealready been set, and should not be set here as that would make it pointto itself. */if( pxIterator != pxBlockToInsert ){pxIterator->pxNextFreeBlock = pxBlockToInsert;}}
123version https://git-lfs.github.com/spec/v1oid sha256:a0e45947fb9f1df4d98544af9682bdcd2429d993f713d9e30652d571a51e9c85size 7501234567891011121314151617181920212223242526272829303132#ifndef DEBUG_H#define DEBUG_H#define DBG(a) *(unsigned char*)0xffffff00 = a;#define PRINTC(ch) {}/*#define PRINTC(ch) \{ DBG(ch) \DBG(0) \}*/#define PRINT(s) \{ for(char* ptr = s; ptr && *ptr; ++ptr) DBG(*ptr) \DBG(0) \}#define PRINTL(dw) {}/*#define PRINTL(dw) \{ for(char i=0; i<8; i++) \{ char ch = (dw>>((7-i)*4))&0x0F; \ch = ch > 9 ? ch-10+'A' : ch + '0'; \DBG(ch) \} DBG(0) \}*/#endif
123version https://git-lfs.github.com/spec/v1oid sha256:17816d2f8e6adbb1195d5f709fe4b4d6053d645e6390a5028663fd24ba600f0dsize 28536123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//*-----------------------------------------------------------* Implementation of functions defined in portable.h for the ARM CM3 port.*----------------------------------------------------------*//* Scheduler includes. */#include "FreeRTOS.h"#include "task.h"#include "debug.h"/* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY isdefined. The value should also ensure backward compatibility.FreeRTOS.org versions prior to V4.4.0 did not include this definition. */#ifndef configKERNEL_INTERRUPT_PRIORITY#define configKERNEL_INTERRUPT_PRIORITY 255#endif#ifndef configSYSTICK_CLOCK_HZ#define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ#endif/* Constants required to manipulate the core. Registers first... */#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile unsigned long * ) 0xe000e010 ) )#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile unsigned long * ) 0xe000e014 ) )#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile unsigned long * ) 0xe000e018 ) )#define portNVIC_SYSPRI2_REG ( * ( ( volatile unsigned long * ) 0xe000ed20 ) )/* ...then bits in the registers. */#define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )#define portNVIC_PENDSV_PRI ( ( ( unsigned long ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )#define portNVIC_SYSTICK_PRI ( ( ( unsigned long ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )/* Constants required to check the validity of an interrupt priority. */#define portFIRST_USER_INTERRUPT_NUMBER ( 16 )#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )#define portAIRCR_REG ( * ( ( volatile unsigned long * ) 0xE000ED0C ) )#define portMAX_8_BIT_VALUE ( ( unsigned char ) 0xff )#define portTOP_BIT_OF_BYTE ( ( unsigned char ) 0x80 )#define portMAX_PRIGROUP_BITS ( ( unsigned char ) 7 )#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )#define portPRIGROUP_SHIFT ( 8UL )/* Constants required to set up the initial stack. */#define portINITIAL_XPSR ( 0x01000000UL )/* The systick is a 24-bit counter. */#define portMAX_24_BIT_NUMBER ( 0xffffffUL )/* A fiddle factor to estimate the number of SysTick counts that would haveoccurred while the SysTick counter is stopped during tickless idlecalculations. */#define portMISSED_COUNTS_FACTOR ( 45UL )/* Let the user override the pre-loading of the initial LR with the address ofprvTaskExitError() in case is messes up unwinding of the stack in thedebugger. */#ifdef configTASK_RETURN_ADDRESS#define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS#else#define portTASK_RETURN_ADDRESS prvTaskExitError#endif/* Each task maintains its own interrupt status in the critical nestingvariable. */static unsigned portBASE_TYPE uxCriticalNesting = 0xaaaaaaaa;/** Setup the timer to generate the tick interrupts. The implementation in this* file is weak to allow application writers to change the timer used to* generate the tick interrupt.*/void vPortSetupTimerInterrupt( void );/** Exception handlers.*/void xPortPendSVHandler( void ) __attribute__ (( naked ));void xPortSysTickHandler( void );void vPortSVCHandler( void ) __attribute__ (( naked ));/** Start first task is a separate function so it can be tested in isolation.*/static void prvPortStartFirstTask( void ) __attribute__ (( naked ));/** Used to catch tasks that attempt to return from their implementing function.*/static void prvTaskExitError( void );/*-----------------------------------------------------------*//** The number of SysTick increments that make up one tick period.*/#if configUSE_TICKLESS_IDLE == 1static unsigned long ulTimerCountsForOneTick = 0;#endif /* configUSE_TICKLESS_IDLE *//** The maximum number of tick periods that can be suppressed is limited by the* 24 bit resolution of the SysTick timer.*/#if configUSE_TICKLESS_IDLE == 1static unsigned long xMaximumPossibleSuppressedTicks = 0;#endif /* configUSE_TICKLESS_IDLE *//** Compensate for the CPU cycles that pass while the SysTick is stopped (low* power functionality only.*/#if configUSE_TICKLESS_IDLE == 1static unsigned long ulStoppedTimerCompensation = 0;#endif /* configUSE_TICKLESS_IDLE *//** Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure* FreeRTOS API functions are not called from interrupts that have been assigned* a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.*/#if ( configASSERT_DEFINED == 1 )static unsigned char ucMaxSysCallPriority = 0;static unsigned long ulMaxPRIGROUPValue = 0;static const volatile unsigned char * const pcInterruptPriorityRegisters = ( const volatile unsigned char * const ) portNVIC_IP_REGISTERS_OFFSET_16;#endif /* configASSERT_DEFINED *//*-----------------------------------------------------------*//** See header file for description.*/portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters ){/* Simulate the stack frame as it would be created by a context switchinterrupt. */pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */*pxTopOfStack = portINITIAL_XPSR; /* xPSR */pxTopOfStack--;*pxTopOfStack = ( portSTACK_TYPE ) pxCode; /* PC */pxTopOfStack--;*pxTopOfStack = ( portSTACK_TYPE ) portTASK_RETURN_ADDRESS; /* LR */pxTopOfStack -= 5; /* R12, R3, R2 and R1. */*pxTopOfStack = ( portSTACK_TYPE ) pvParameters; /* R0 */pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */return pxTopOfStack;}/*-----------------------------------------------------------*/static void prvTaskExitError( void ){/* A function that implements a task must not exit or attempt to return toits caller as there is nothing to return to. If a task wants to exit itshould instead call vTaskDelete( NULL ).Artificially force an assert() to be triggered if configASSERT() isdefined, then stop here so application writers can catch the error. */configASSERT( uxCriticalNesting == ~0UL );portDISABLE_INTERRUPTS();for( ;; );}/*-----------------------------------------------------------*/static volatile int svcall;void vPortSVCHandler( void ){svcall++;__asm volatile (" ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */" ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */" ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */" ldmia r0!, {r4-r11} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */" msr psp, r0 \n" /* Restore the task stack pointer. */" mov r0, #0 \n"" msr basepri, r0 \n"" orr r14, #0xd \n"" bx r14 \n"" \n"" .align 2 \n""pxCurrentTCBConst2: .word pxCurrentTCB \n");}/*-----------------------------------------------------------*/static void prvPortStartFirstTask( void ){svcall = 0;__asm volatile(" ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */" ldr r0, [r0] \n"" ldr r0, [r0] \n"" msr msp, r0 \n" /* Set the msp back to the start of the stack. */" cpsie i \n" /* Globally enable interrupts. */" svc 0 \n" /* System call to start first task. */" nop \n");}/*-----------------------------------------------------------*//** See header file for description.*/portBASE_TYPE xPortStartScheduler( void ){/* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY );#if( configASSERT_DEFINED == 1 ){volatile unsigned long ulOriginalPriority;volatile char * const pcFirstUserPriorityRegister = ( volatile char * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );volatile unsigned char ucMaxPriorityValue;/* Determine the maximum priority from which ISR safe FreeRTOS APIfunctions can be called. ISR safe functions are those that end in"FromISR". FreeRTOS maintains separate thread and ISR API functions toensure interrupt entry is as fast and simple as possible.Save the interrupt priority value that is about to be clobbered. */ulOriginalPriority = *pcFirstUserPriorityRegister;/* Determine the number of priority bits available. First write to allpossible bits. */*pcFirstUserPriorityRegister = portMAX_8_BIT_VALUE;/* Read the value back to see how many bits stuck. */ucMaxPriorityValue = *pcFirstUserPriorityRegister;/* Use the same mask on the maximum system call priority. */ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;/* Calculate the maximum acceptable priority group value for the numberof bits read back. */ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE ){ulMaxPRIGROUPValue--;ucMaxPriorityValue <<= ( unsigned char ) 0x01;}/* Shift the priority group value back to its position within the AIRCRregister. */ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;/* Restore the clobbered interrupt priority register to its originalvalue. */*pcFirstUserPriorityRegister = ulOriginalPriority;}#endif /* conifgASSERT_DEFINED *//* Make PendSV and SysTick the lowest priority interrupts. */portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;/* Start the timer that generates the tick ISR. Interrupts are disabledhere already. */vPortSetupTimerInterrupt();/* Initialise the critical nesting count ready for the first task. */uxCriticalNesting = 0;/* Start the first task. */prvPortStartFirstTask();/* Should never get here as the tasks will now be executing! Call the taskexit error function to prevent compiler warnings about a static functionnot being called in the case that the application writer overrides thisfunctionality by defining configTASK_RETURN_ADDRESS. */prvTaskExitError();/* Should not get here! */return 0;}/*-----------------------------------------------------------*/void vPortEndScheduler( void ){/* It is unlikely that the CM3 port will require this function as thereis nothing to return to. */}/*-----------------------------------------------------------*/void vPortYield( void ){PRINTC('Y')/* Set a PendSV to request a context switch. */portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;/* Barriers are normally not required but do ensure the code is completelywithin the specified behaviour for the architecture. */__asm volatile( "dsb" );__asm volatile( "isb" );PRINTC('t')}/*-----------------------------------------------------------*/void vPortEnterCritical( void ){portDISABLE_INTERRUPTS();uxCriticalNesting++;__asm volatile( "dsb" );__asm volatile( "isb" );}/*-----------------------------------------------------------*/void vPortExitCritical( void ){uxCriticalNesting--;if( uxCriticalNesting == 0 ){portENABLE_INTERRUPTS();}}/*-----------------------------------------------------------*/__attribute__(( naked )) unsigned long ulPortSetInterruptMask( void ){__asm volatile \( \" mrs r0, basepri \n" \" mov r1, %0 \n" \" msr basepri, r1 \n" \" bx lr \n" \:: "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "r0", "r1" \);/* This return will not be reached but is necessary to prevent compilerwarnings. */return 0;}/*-----------------------------------------------------------*/__attribute__(( naked )) void vPortClearInterruptMask( unsigned long ulNewMaskValue ){__asm volatile \( \" msr basepri, r0 \n" \" bx lr \n" \:::"r0" \);/* Just to avoid compiler warnings. */( void ) ulNewMaskValue;}/*-----------------------------------------------------------*/void xPortPendSVHandler( void ){/* This is a naked function. */__asm volatile(" mrs r0, psp \n"" \n"" ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */" ldr r2, [r3] \n"" \n"" stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */" str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */" \n"" stmdb sp!, {r3, r14} \n"" mov r0, %0 \n"" msr basepri, r0 \n"" bl vTaskSwitchContext \n"" mov r0, #0 \n"" msr basepri, r0 \n"" ldmia sp!, {r3, r14} \n"" \n" /* Restore the context, including the critical nesting count. */" ldr r1, [r3] \n"" ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */" ldmia r0!, {r4-r11} \n" /* Pop the registers. */" msr psp, r0 \n"" bx r14 \n"" \n"" .align 2 \n""pxCurrentTCBConst: .word pxCurrentTCB \n"::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY));}/*-----------------------------------------------------------*/#include "sam3n4c.h"static Pio* pioa = (Pio*)0x400E0E00;volatile unsigned long tick = 0;void xPortSysTickHandler( void ){/* The SysTick runs at the lowest interrupt priority, so when this interruptexecutes all interrupts must be unmasked. There is therefore no need tosave and then restore the interrupt mask value as its value is alreadyknown. */( void ) portSET_INTERRUPT_MASK_FROM_ISR();{tick++;PRINTL(tick)pioa->PIO_SODR = PIO_SODR_P0;pioa->PIO_CODR = PIO_CODR_P0;/* Increment the RTOS tick. */if( xTaskIncrementTick() != pdFALSE ){/* A context switch is required. Context switching is performed inthe PendSV interrupt. Pend the PendSV interrupt. */PRINTC('S')portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;}}portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );}/*-----------------------------------------------------------*/#if configUSE_TICKLESS_IDLE == 1__attribute__((weak)) void vPortSuppressTicksAndSleep( portTickType xExpectedIdleTime ){unsigned long ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;portTickType xModifiableIdleTime;/* Make sure the SysTick reload value does not overflow the counter. */if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ){xExpectedIdleTime = xMaximumPossibleSuppressedTicks;}/* Stop the SysTick momentarily. The time the SysTick is stopped foris accounted for as best it can be, but using the tickless mode willinevitably result in some tiny drift of the time maintained by thekernel with respect to calendar time. */portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;/* Calculate the reload value required to wait xExpectedIdleTimetick periods. -1 is used because this code will execute part waythrough one of the tick periods. */ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );if( ulReloadValue > ulStoppedTimerCompensation ){ulReloadValue -= ulStoppedTimerCompensation;}/* Enter a critical section but don't use the taskENTER_CRITICAL()method as that will mask interrupts that should exit sleep mode. */__asm volatile( "cpsid i" );/* If a context switch is pending or a task is waiting for the schedulerto be unsuspended then abandon the low power entry. */if( eTaskConfirmSleepModeStatus() == eAbortSleep ){/* Restart from whatever is left in the count register to completethis tick period. */portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;/* Restart SysTick. */portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;/* Reset the reload register to the value required for normal tickperiods. */portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;/* Re-enable interrupts - see comments above the cpsid instruction()above. */__asm volatile( "cpsie i" );}else{/* Set the new reload value. */portNVIC_SYSTICK_LOAD_REG = ulReloadValue;/* Clear the SysTick count flag and set the count value back tozero. */portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;/* Restart SysTick. */portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;/* Sleep until something happens. configPRE_SLEEP_PROCESSING() canset its parameter to 0 to indicate that its implementation containsits own wait for interrupt or wait for event instruction, and so wfishould not be executed again. However, the original expected idletime variable must remain unmodified, so a copy is taken. */xModifiableIdleTime = xExpectedIdleTime;configPRE_SLEEP_PROCESSING( xModifiableIdleTime );if( xModifiableIdleTime > 0 ){__asm volatile( "dsb" );__asm volatile( "wfi" );__asm volatile( "isb" );}configPOST_SLEEP_PROCESSING( xExpectedIdleTime );/* Stop SysTick. Again, the time the SysTick is stopped for isaccounted for as best it can be, but using the tickless mode willinevitably result in some tiny drift of the time maintained by thekernel with respect to calendar time. */portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;/* Re-enable interrupts - see comments above the cpsid instruction()above. */__asm volatile( "cpsie i" );if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ){unsigned long ulCalculatedLoadValue;/* The tick interrupt has already executed, and the SysTickcount reloaded with ulReloadValue. Reset theportNVIC_SYSTICK_LOAD_REG with whatever remains of this tickperiod. */ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );/* Don't allow a tiny value, or values that have somehowunderflowed because the post sleep hook did somethingthat took too long. */if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) ){ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );}portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;/* The tick interrupt handler will already have pended the tickprocessing in the kernel. As the pending tick will beprocessed as soon as this function exits, the tick valuemaintained by the tick is stepped forward by one less than thetime spent waiting. */ulCompleteTickPeriods = xExpectedIdleTime - 1UL;}else{/* Something other than the tick interrupt ended the sleep.Work out how long the sleep lasted rounded to complete tickperiods (not the ulReload value which accounted for partticks). */ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;/* How many complete tick periods passed while the processorwas waiting? */ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;/* The reload value is set to whatever fraction of a single tickperiod remains. */portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1 ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;}/* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REGagain, then set portNVIC_SYSTICK_LOAD_REG back to its standardvalue. The critical section is used to ensure the tick interruptcan only execute once in the case that the reload register is nearzero. */portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;portENTER_CRITICAL();{portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;vTaskStepTick( ulCompleteTickPeriods );portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;}portEXIT_CRITICAL();}}#endif /* #if configUSE_TICKLESS_IDLE *//*-----------------------------------------------------------*//** Setup the systick timer to generate the tick interrupts at the required* frequency.*/__attribute__(( weak )) void vPortSetupTimerInterrupt( void ){/* Calculate the constants required to configure the tick interrupt. */#if configUSE_TICKLESS_IDLE == 1{ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );}#endif /* configUSE_TICKLESS_IDLE *//* Configure SysTick to interrupt at the requested rate. */portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;;portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;}/*-----------------------------------------------------------*/#if( configASSERT_DEFINED == 1 )void vPortValidateInterruptPriority( void ){unsigned long ulCurrentInterrupt;unsigned char ucCurrentPriority;/* Obtain the number of the currently executing interrupt. */__asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) );/* Is the interrupt number a user defined interrupt? */if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER ){/* Look up the interrupt's priority. */ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];/* The following assertion will fail if a service routine (ISR) foran interrupt that has been assigned a priority aboveconfigMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS APIfunction. ISR safe FreeRTOS API functions must *only* be calledfrom interrupts that have been assigned a priority at or belowconfigMAX_SYSCALL_INTERRUPT_PRIORITY.Numerically low interrupt priority numbers represent logically highinterrupt priorities, therefore the priority of the interrupt mustbe set to a value equal to or numerically *higher* thanconfigMAX_SYSCALL_INTERRUPT_PRIORITY.Interrupts that use the FreeRTOS API must not be left at theirdefault priority of zero as that is the highest possible priority,which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,and therefore also guaranteed to be invalid.FreeRTOS maintains separate thread and ISR API functions to ensureinterrupt entry is as fast and simple as possible.The following links provide detailed information:http://www.freertos.org/RTOS-Cortex-M3-M4.htmlhttp://www.freertos.org/FAQHelp.html */configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );}/* Priority grouping: The interrupt controller (NVIC) allows the bitsthat define each interrupt's priority to be split between bits thatdefine the interrupt's pre-emption priority bits and bits that definethe interrupt's sub-priority. For simplicity all bits must be definedto be pre-emption priority bits. The following assertion will fail ifthis is not the case (if some bits represent a sub-priority).If the application only uses CMSIS libraries for interruptconfiguration then the correct setting can be achieved on all Cortex-Mdevices by calling NVIC_SetPriorityGrouping( 0 ); before starting thescheduler. Note however that some vendor specific peripheral librariesassume a non-zero priority group setting, in which cases using a valueof zero will result in unpredicable behaviour. */configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );}#endif /* configASSERT_DEFINED */
123version https://git-lfs.github.com/spec/v1oid sha256:b1d9546202d6aa9f927793b6ed63a0bd54d19c1925117a4a097480947b98cddbsize 8374123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef PORTMACRO_H#define PORTMACRO_H#ifdef __cplusplusextern "C" {#endif/*-----------------------------------------------------------* Port specific definitions.** The settings in this file configure FreeRTOS correctly for the* given hardware and compiler.** These settings should not be altered.*-----------------------------------------------------------*//* Type definitions. */#define portCHAR char#define portFLOAT float#define portDOUBLE double#define portLONG long#define portSHORT short#define portSTACK_TYPE unsigned portLONG#define portBASE_TYPE long#if( configUSE_16_BIT_TICKS == 1 )typedef unsigned portSHORT portTickType;#define portMAX_DELAY ( portTickType ) 0xffff#elsetypedef unsigned portLONG portTickType;#define portMAX_DELAY ( portTickType ) 0xffffffff#endif/*-----------------------------------------------------------*//* Architecture specifics. */#define portSTACK_GROWTH ( -1 )#define portTICK_RATE_MS ( ( portTickType ) 1000 / configTICK_RATE_HZ )#define portBYTE_ALIGNMENT 8/*-----------------------------------------------------------*//* Scheduler utilities. */extern void vPortYield( void );#define portNVIC_INT_CTRL_REG ( * ( ( volatile unsigned long * ) 0xe000ed04 ) )#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )#define portYIELD() vPortYield()#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired ) portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x )/*-----------------------------------------------------------*//* Critical section management. */extern void vPortEnterCritical( void );extern void vPortExitCritical( void );extern unsigned long ulPortSetInterruptMask( void );extern void vPortClearInterruptMask( unsigned long ulNewMaskValue );#define portSET_INTERRUPT_MASK_FROM_ISR() ulPortSetInterruptMask()#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortClearInterruptMask(x)#define portDISABLE_INTERRUPTS() ulPortSetInterruptMask()#define portENABLE_INTERRUPTS() vPortClearInterruptMask(0)#define portENTER_CRITICAL() vPortEnterCritical()#define portEXIT_CRITICAL() vPortExitCritical()/*-----------------------------------------------------------*//* Task function macros as described on the FreeRTOS.org WEB site. These arenot necessary for to use this port. They are defined so the common demo files(which build with all the ports) will build. */#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )/*-----------------------------------------------------------*//* Tickless idle/low power functionality. */#ifndef portSUPPRESS_TICKS_AND_SLEEPextern void vPortSuppressTicksAndSleep( portTickType xExpectedIdleTime );#define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime )#endif/*-----------------------------------------------------------*//* Architecture specific optimisations. */#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1/* Generic helper function. */__attribute__( ( always_inline ) ) static inline unsigned char ucPortCountLeadingZeros( unsigned long ulBitmap ){unsigned char ucReturn;__asm volatile ( "clz %0, %1" : "=r" ( ucReturn ) : "r" ( ulBitmap ) );return ucReturn;}/* Check the configuration. */#if( configMAX_PRIORITIES > 32 )#error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice.#endif/* Store/clear the ready priorities in a bit map. */#define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) )#define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) )/*-----------------------------------------------------------*/#define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31 - ucPortCountLeadingZeros( ( uxReadyPriorities ) ) )#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION *//*-----------------------------------------------------------*/#ifdef configASSERTvoid vPortValidateInterruptPriority( void );#define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority()#endif/* portNOP() is not required by this port. */#define portNOP()#ifdef __cplusplus}#endif#endif /* PORTMACRO_H */
123version https://git-lfs.github.com/spec/v1oid sha256:79f9eabaf862006c469bb9880745d0a11509ec302a94ae9c6dd520b3b6379388size 7072012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#include <stdlib.h>#include <string.h>/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefiningall the API functions to use the MPU wrappers. That should only be done whentask.h is included from an application file. */#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE#include "FreeRTOS.h"#include "task.h"#include "queue.h"#if ( configUSE_CO_ROUTINES == 1 )#include "croutine.h"#endif/* Lint e961 and e750 are suppressed as a MISRA exception justified because theMPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for theheader files above, but not in this file, in order to generate the correctprivileged Vs unprivileged linkage and placement. */#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. *//* Constants used with the cRxLock and xTxLock structure members. */#define queueUNLOCKED ( ( signed portBASE_TYPE ) -1 )#define queueLOCKED_UNMODIFIED ( ( signed portBASE_TYPE ) 0 )/* When the xQUEUE structure is used to represent a base queue its pcHead andpcTail members are used as pointers into the queue storage area. When thexQUEUE structure is used to represent a mutex pcHead and pcTail pointers arenot necessary, and the pcHead pointer is set to NULL to indicate that thepcTail pointer actually points to the mutex holder (if any). Map alternativenames to the pcHead and pcTail structure members to ensure the readability ofthe code is maintained despite this dual use of two structure members. Analternative implementation would be to use a union, but use of a union isagainst the coding standard (although an exception to the standard has beenpermitted where the dual use also significantly changes the type of thestructure member). */#define pxMutexHolder pcTail#define uxQueueType pcHead#define queueQUEUE_IS_MUTEX NULL/* Semaphores do not actually store or copy data, so have an item size ofzero. */#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( unsigned portBASE_TYPE ) 0 )#define queueMUTEX_GIVE_BLOCK_TIME ( ( portTickType ) 0U )#if( configUSE_PREEMPTION == 0 )/* If the cooperative scheduler is being used then a yield should not beperformed just because a higher priority task has been woken. */#define queueYIELD_IF_USING_PREEMPTION()#else#define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()#endif/** Definition of the queue used by the scheduler.* Items are queued by copy, not reference.*/typedef struct QueueDefinition{signed char *pcHead; /*< Points to the beginning of the queue storage area. */signed char *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */signed char *pcWriteTo; /*< Points to the free next place in the storage area. */union /* Use of a union is an exception to the coding standard to ensure two mutually exclusive structure members don't appear simultaneously (wasting RAM). */{signed char *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */unsigned portBASE_TYPE uxRecursiveCallCount;/*< Maintains a count of the numebr of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */} u;xList xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */xList xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */volatile unsigned portBASE_TYPE uxMessagesWaiting;/*< The number of items currently in the queue. */unsigned portBASE_TYPE uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */unsigned portBASE_TYPE uxItemSize; /*< The size of each items that the queue will hold. */volatile signed portBASE_TYPE xRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */volatile signed portBASE_TYPE xTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */#if ( configUSE_TRACE_FACILITY == 1 )unsigned char ucQueueNumber;unsigned char ucQueueType;#endif#if ( configUSE_QUEUE_SETS == 1 )struct QueueDefinition *pxQueueSetContainer;#endif} xQUEUE;/*-----------------------------------------------------------*//** The queue registry is just a means for kernel aware debuggers to locate* queue structures. It has no other purpose so is an optional component.*/#if ( configQUEUE_REGISTRY_SIZE > 0 )/* The type stored within the queue registry array. This allows a nameto be assigned to each queue making kernel aware debugging a littlemore user friendly. */typedef struct QUEUE_REGISTRY_ITEM{signed char *pcQueueName;xQueueHandle xHandle;} xQueueRegistryItem;/* The queue registry is simply an array of xQueueRegistryItem structures.The pcQueueName member of a structure being NULL is indicative of thearray position being vacant. */xQueueRegistryItem xQueueRegistry[ configQUEUE_REGISTRY_SIZE ];#endif /* configQUEUE_REGISTRY_SIZE *//** Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not* prevent an ISR from adding or removing items to the queue, but does prevent* an ISR from removing tasks from the queue event lists. If an ISR finds a* queue is locked it will instead increment the appropriate queue lock count* to indicate that a task may require unblocking. When the queue in unlocked* these lock counts are inspected, and the appropriate action taken.*/static void prvUnlockQueue( xQUEUE *pxQueue ) PRIVILEGED_FUNCTION;/** Uses a critical section to determine if there is any data in a queue.** @return pdTRUE if the queue contains no items, otherwise pdFALSE.*/static signed portBASE_TYPE prvIsQueueEmpty( const xQUEUE *pxQueue ) PRIVILEGED_FUNCTION;/** Uses a critical section to determine if there is any space in a queue.** @return pdTRUE if there is no space, otherwise pdFALSE;*/static signed portBASE_TYPE prvIsQueueFull( const xQUEUE *pxQueue ) PRIVILEGED_FUNCTION;/** Copies an item into the queue, either at the front of the queue or the* back of the queue.*/static void prvCopyDataToQueue( xQUEUE *pxQueue, const void *pvItemToQueue, portBASE_TYPE xPosition ) PRIVILEGED_FUNCTION;/** Copies an item out of a queue.*/static void prvCopyDataFromQueue( xQUEUE * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION;#if ( configUSE_QUEUE_SETS == 1 )/** Checks to see if a queue is a member of a queue set, and if so, notifies* the queue set that the queue contains data.*/static portBASE_TYPE prvNotifyQueueSetContainer( const xQUEUE * const pxQueue, portBASE_TYPE xCopyPosition ) PRIVILEGED_FUNCTION;#endif/*-----------------------------------------------------------*//** Macro to mark a queue as locked. Locking a queue prevents an ISR from* accessing the queue event lists.*/#define prvLockQueue( pxQueue ) \taskENTER_CRITICAL(); \{ \if( ( pxQueue )->xRxLock == queueUNLOCKED ) \{ \( pxQueue )->xRxLock = queueLOCKED_UNMODIFIED; \} \if( ( pxQueue )->xTxLock == queueUNLOCKED ) \{ \( pxQueue )->xTxLock = queueLOCKED_UNMODIFIED; \} \} \taskEXIT_CRITICAL()/*-----------------------------------------------------------*/portBASE_TYPE xQueueGenericReset( xQueueHandle xQueue, portBASE_TYPE xNewQueue ){xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );taskENTER_CRITICAL();{pxQueue->pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize );pxQueue->uxMessagesWaiting = ( unsigned portBASE_TYPE ) 0U;pxQueue->pcWriteTo = pxQueue->pcHead;pxQueue->u.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - ( unsigned portBASE_TYPE ) 1U ) * pxQueue->uxItemSize );pxQueue->xRxLock = queueUNLOCKED;pxQueue->xTxLock = queueUNLOCKED;if( xNewQueue == pdFALSE ){/* If there are tasks blocked waiting to read from the queue, thenthe tasks will remain blocked as after this function exits the queuewill still be empty. If there are tasks blocked waiting to write tothe queue, then one should be unblocked as after this function exitsit will be possible to write to it. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE ){queueYIELD_IF_USING_PREEMPTION();}}}else{/* Ensure the event queues start in the correct state. */vListInitialise( &( pxQueue->xTasksWaitingToSend ) );vListInitialise( &( pxQueue->xTasksWaitingToReceive ) );}}taskEXIT_CRITICAL();/* A value is returned for calling semantic consistency with previousversions. */return pdPASS;}/*-----------------------------------------------------------*/xQueueHandle xQueueGenericCreate( unsigned portBASE_TYPE uxQueueLength, unsigned portBASE_TYPE uxItemSize, unsigned char ucQueueType ){xQUEUE *pxNewQueue;size_t xQueueSizeInBytes;xQueueHandle xReturn = NULL;/* Remove compiler warnings about unused parameters shouldconfigUSE_TRACE_FACILITY not be set to 1. */( void ) ucQueueType;/* Allocate the new queue structure. */if( uxQueueLength > ( unsigned portBASE_TYPE ) 0 ){pxNewQueue = ( xQUEUE * ) pvPortMalloc( sizeof( xQUEUE ) );if( pxNewQueue != NULL ){/* Create the list of pointers to queue items. The queue is one bytelonger than asked for to make wrap checking easier/faster. */xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ) + ( size_t ) 1; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */pxNewQueue->pcHead = ( signed char * ) pvPortMalloc( xQueueSizeInBytes );if( pxNewQueue->pcHead != NULL ){/* Initialise the queue members as described above where thequeue type is defined. */pxNewQueue->uxLength = uxQueueLength;pxNewQueue->uxItemSize = uxItemSize;( void ) xQueueGenericReset( pxNewQueue, pdTRUE );#if ( configUSE_TRACE_FACILITY == 1 ){pxNewQueue->ucQueueType = ucQueueType;}#endif /* configUSE_TRACE_FACILITY */#if( configUSE_QUEUE_SETS == 1 ){pxNewQueue->pxQueueSetContainer = NULL;}#endif /* configUSE_QUEUE_SETS */traceQUEUE_CREATE( pxNewQueue );xReturn = pxNewQueue;}else{traceQUEUE_CREATE_FAILED( ucQueueType );vPortFree( pxNewQueue );}}}configASSERT( xReturn );return xReturn;}/*-----------------------------------------------------------*/#if ( configUSE_MUTEXES == 1 )xQueueHandle xQueueCreateMutex( unsigned char ucQueueType ){xQUEUE *pxNewQueue;/* Prevent compiler warnings about unused parameters ifconfigUSE_TRACE_FACILITY does not equal 1. */( void ) ucQueueType;/* Allocate the new queue structure. */pxNewQueue = ( xQUEUE * ) pvPortMalloc( sizeof( xQUEUE ) );if( pxNewQueue != NULL ){/* Information required for priority inheritance. */pxNewQueue->pxMutexHolder = NULL;pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX;/* Queues used as a mutex no data is actually copied into or outof the queue. */pxNewQueue->pcWriteTo = NULL;pxNewQueue->u.pcReadFrom = NULL;/* Each mutex has a length of 1 (like a binary semaphore) andan item size of 0 as nothing is actually copied into or outof the mutex. */pxNewQueue->uxMessagesWaiting = ( unsigned portBASE_TYPE ) 0U;pxNewQueue->uxLength = ( unsigned portBASE_TYPE ) 1U;pxNewQueue->uxItemSize = ( unsigned portBASE_TYPE ) 0U;pxNewQueue->xRxLock = queueUNLOCKED;pxNewQueue->xTxLock = queueUNLOCKED;#if ( configUSE_TRACE_FACILITY == 1 ){pxNewQueue->ucQueueType = ucQueueType;}#endif#if ( configUSE_QUEUE_SETS == 1 ){pxNewQueue->pxQueueSetContainer = NULL;}#endif/* Ensure the event queues start with the correct state. */vListInitialise( &( pxNewQueue->xTasksWaitingToSend ) );vListInitialise( &( pxNewQueue->xTasksWaitingToReceive ) );traceCREATE_MUTEX( pxNewQueue );/* Start with the semaphore in the expected state. */( void ) xQueueGenericSend( pxNewQueue, NULL, ( portTickType ) 0U, queueSEND_TO_BACK );}else{traceCREATE_MUTEX_FAILED();}configASSERT( pxNewQueue );return pxNewQueue;}#endif /* configUSE_MUTEXES *//*-----------------------------------------------------------*/#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) )void* xQueueGetMutexHolder( xQueueHandle xSemaphore ){void *pxReturn;/* This function is called by xSemaphoreGetMutexHolder(), and should notbe called directly. Note: This is is a good way of determining if thecalling task is the mutex holder, but not a good way of determining theidentity of the mutex holder, as the holder may change between thefollowing critical section exiting and the function returning. */taskENTER_CRITICAL();{if( ( ( xQUEUE * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ){pxReturn = ( void * ) ( ( xQUEUE * ) xSemaphore )->pxMutexHolder;}else{pxReturn = NULL;}}taskEXIT_CRITICAL();return pxReturn;}#endif/*-----------------------------------------------------------*/#if ( configUSE_RECURSIVE_MUTEXES == 1 )portBASE_TYPE xQueueGiveMutexRecursive( xQueueHandle xMutex ){portBASE_TYPE xReturn;xQUEUE * const pxMutex = ( xQUEUE * ) xMutex;configASSERT( pxMutex );/* If this is the task that holds the mutex then pxMutexHolder will notchange outside of this task. If this task does not hold the mutex thenpxMutexHolder can never coincidentally equal the tasks handle, and asthis is the only condition we are interested in it does not matter ifpxMutexHolder is accessed simultaneously by another task. Therefore nomutual exclusion is required to test the pxMutexHolder variable. */if( pxMutex->pxMutexHolder == ( void * ) xTaskGetCurrentTaskHandle() ) /*lint !e961 Not a redundant cast as xTaskHandle is a typedef. */{traceGIVE_MUTEX_RECURSIVE( pxMutex );/* uxRecursiveCallCount cannot be zero if pxMutexHolder is equal tothe task handle, therefore no underflow check is required. Also,uxRecursiveCallCount is only modified by the mutex holder, and asthere can only be one, no mutual exclusion is required to modify theuxRecursiveCallCount member. */( pxMutex->u.uxRecursiveCallCount )--;/* Have we unwound the call count? */if( pxMutex->u.uxRecursiveCallCount == ( unsigned portBASE_TYPE ) 0 ){/* Return the mutex. This will automatically unblock any othertask that might be waiting to access the mutex. */( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK );}xReturn = pdPASS;}else{/* We cannot give the mutex because we are not the holder. */xReturn = pdFAIL;traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex );}return xReturn;}#endif /* configUSE_RECURSIVE_MUTEXES *//*-----------------------------------------------------------*/#if ( configUSE_RECURSIVE_MUTEXES == 1 )portBASE_TYPE xQueueTakeMutexRecursive( xQueueHandle xMutex, portTickType xBlockTime ){portBASE_TYPE xReturn;xQUEUE * const pxMutex = ( xQUEUE * ) xMutex;configASSERT( pxMutex );/* Comments regarding mutual exclusion as per those withinxQueueGiveMutexRecursive(). */traceTAKE_MUTEX_RECURSIVE( pxMutex );if( pxMutex->pxMutexHolder == ( void * ) xTaskGetCurrentTaskHandle() ) /*lint !e961 Cast is not redundant as xTaskHandle is a typedef. */{( pxMutex->u.uxRecursiveCallCount )++;xReturn = pdPASS;}else{xReturn = xQueueGenericReceive( pxMutex, NULL, xBlockTime, pdFALSE );/* pdPASS will only be returned if we successfully obtained the mutex,we may have blocked to reach here. */if( xReturn == pdPASS ){( pxMutex->u.uxRecursiveCallCount )++;}else{traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex );}}return xReturn;}#endif /* configUSE_RECURSIVE_MUTEXES *//*-----------------------------------------------------------*/#if ( configUSE_COUNTING_SEMAPHORES == 1 )xQueueHandle xQueueCreateCountingSemaphore( unsigned portBASE_TYPE uxMaxCount, unsigned portBASE_TYPE uxInitialCount ){xQueueHandle xHandle;configASSERT( uxMaxCount != 0 );configASSERT( uxInitialCount <= uxMaxCount );xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE );if( xHandle != NULL ){( ( xQUEUE * ) xHandle )->uxMessagesWaiting = uxInitialCount;traceCREATE_COUNTING_SEMAPHORE();}else{traceCREATE_COUNTING_SEMAPHORE_FAILED();}configASSERT( xHandle );return xHandle;}#endif /* configUSE_COUNTING_SEMAPHORES *//*-----------------------------------------------------------*/signed portBASE_TYPE xQueueGenericSend( xQueueHandle xQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ){signed portBASE_TYPE xEntryTimeSet = pdFALSE;xTimeOutType xTimeOut;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) );/* This function relaxes the coding standard somewhat to allow returnstatements within the function itself. This is done in the interestof execution time efficiency. */for( ;; ){taskENTER_CRITICAL();{/* Is there room on the queue now? The running task must bethe highest priority task wanting to access the queue. Ifthe head item in the queue is to be overwritten then it doesnot matter if the queue is full. */if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ){traceQUEUE_SEND( pxQueue );prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );#if ( configUSE_QUEUE_SETS == 1 ){if( pxQueue->pxQueueSetContainer != NULL ){if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) == pdTRUE ){/* The queue is a member of a queue set, and postingto the queue set caused a higher priority task tounblock. A context switch is required. */queueYIELD_IF_USING_PREEMPTION();}}else{/* If there was a task waiting for data to arrive on thequeue then unblock it now. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE ){/* The unblocked task has a priority higher thanour own so yield immediately. Yes it is ok todo this from within the critical section - thekernel takes care of that. */queueYIELD_IF_USING_PREEMPTION();}}}}#else /* configUSE_QUEUE_SETS */{/* If there was a task waiting for data to arrive on thequeue then unblock it now. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE ){/* The unblocked task has a priority higher thanour own so yield immediately. Yes it is ok to dothis from within the critical section - the kerneltakes care of that. */queueYIELD_IF_USING_PREEMPTION();}}}#endif /* configUSE_QUEUE_SETS */taskEXIT_CRITICAL();/* Return to the original privilege level before exiting thefunction. */return pdPASS;}else{if( xTicksToWait == ( portTickType ) 0 ){/* The queue was full and no block time is specified (orthe block time has expired) so leave now. */taskEXIT_CRITICAL();/* Return to the original privilege level before exitingthe function. */traceQUEUE_SEND_FAILED( pxQueue );return errQUEUE_FULL;}else if( xEntryTimeSet == pdFALSE ){/* The queue was full and a block time was specified soconfigure the timeout structure. */vTaskSetTimeOutState( &xTimeOut );xEntryTimeSet = pdTRUE;}else{/* Entry time was already set. */}}}taskEXIT_CRITICAL();/* Interrupts and other tasks can send to and receive from the queuenow the critical section has been exited. */vTaskSuspendAll();prvLockQueue( pxQueue );/* Update the timeout state to see if it has expired yet. */if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ){if( prvIsQueueFull( pxQueue ) != pdFALSE ){traceBLOCKING_ON_QUEUE_SEND( pxQueue );vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait );/* Unlocking the queue means queue events can effect theevent list. It is possible that interrupts occurring nowremove this task from the event list again - but as thescheduler is suspended the task will go onto the pendingready last instead of the actual ready list. */prvUnlockQueue( pxQueue );/* Resuming the scheduler will move tasks from the pendingready list into the ready list - so it is feasible that thistask is already in a ready list before it yields - in whichcase the yield will not cause a context switch unless thereis also a higher priority task in the pending ready list. */if( xTaskResumeAll() == pdFALSE ){portYIELD_WITHIN_API();}}else{/* Try again. */prvUnlockQueue( pxQueue );( void ) xTaskResumeAll();}}else{/* The timeout has expired. */prvUnlockQueue( pxQueue );( void ) xTaskResumeAll();/* Return to the original privilege level before exiting thefunction. */traceQUEUE_SEND_FAILED( pxQueue );return errQUEUE_FULL;}}}/*-----------------------------------------------------------*/#if ( configUSE_ALTERNATIVE_API == 1 )signed portBASE_TYPE xQueueAltGenericSend( xQueueHandle xQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ){signed portBASE_TYPE xEntryTimeSet = pdFALSE;xTimeOutType xTimeOut;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );for( ;; ){taskENTER_CRITICAL();{/* Is there room on the queue now? To be running we must bethe highest priority task wanting to access the queue. */if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ){traceQUEUE_SEND( pxQueue );prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );/* If there was a task waiting for data to arrive on thequeue then unblock it now. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE ){/* The unblocked task has a priority higher thanour own so yield immediately. */portYIELD_WITHIN_API();}}taskEXIT_CRITICAL();return pdPASS;}else{if( xTicksToWait == ( portTickType ) 0 ){taskEXIT_CRITICAL();return errQUEUE_FULL;}else if( xEntryTimeSet == pdFALSE ){vTaskSetTimeOutState( &xTimeOut );xEntryTimeSet = pdTRUE;}}}taskEXIT_CRITICAL();taskENTER_CRITICAL();{if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ){if( prvIsQueueFull( pxQueue ) != pdFALSE ){traceBLOCKING_ON_QUEUE_SEND( pxQueue );vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait );portYIELD_WITHIN_API();}}else{taskEXIT_CRITICAL();traceQUEUE_SEND_FAILED( pxQueue );return errQUEUE_FULL;}}taskEXIT_CRITICAL();}}#endif /* configUSE_ALTERNATIVE_API *//*-----------------------------------------------------------*/#if ( configUSE_ALTERNATIVE_API == 1 )signed portBASE_TYPE xQueueAltGenericReceive( xQueueHandle xQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking ){signed portBASE_TYPE xEntryTimeSet = pdFALSE;xTimeOutType xTimeOut;signed char *pcOriginalReadPosition;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );for( ;; ){taskENTER_CRITICAL();{if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){/* Remember our read position in case we are just peeking. */pcOriginalReadPosition = pxQueue->u.pcReadFrom;prvCopyDataFromQueue( pxQueue, pvBuffer );if( xJustPeeking == pdFALSE ){traceQUEUE_RECEIVE( pxQueue );/* Data is actually being removed (not just peeked). */--( pxQueue->uxMessagesWaiting );#if ( configUSE_MUTEXES == 1 ){if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ){/* Record the information required to implementpriority inheritance should it become necessary. */pxQueue->pxMutexHolder = ( signed char * ) xTaskGetCurrentTaskHandle();}}#endifif( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE ){portYIELD_WITHIN_API();}}}else{traceQUEUE_PEEK( pxQueue );/* We are not removing the data, so reset our readpointer. */pxQueue->u.pcReadFrom = pcOriginalReadPosition;/* The data is being left in the queue, so see if there areany other tasks waiting for the data. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){/* Tasks that are removed from the event list will get added tothe pending ready list as the scheduler is still suspended. */if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority than this task. */portYIELD_WITHIN_API();}}}taskEXIT_CRITICAL();return pdPASS;}else{if( xTicksToWait == ( portTickType ) 0 ){taskEXIT_CRITICAL();traceQUEUE_RECEIVE_FAILED( pxQueue );return errQUEUE_EMPTY;}else if( xEntryTimeSet == pdFALSE ){vTaskSetTimeOutState( &xTimeOut );xEntryTimeSet = pdTRUE;}}}taskEXIT_CRITICAL();taskENTER_CRITICAL();{if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ){if( prvIsQueueEmpty( pxQueue ) != pdFALSE ){traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue );#if ( configUSE_MUTEXES == 1 ){if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ){portENTER_CRITICAL();{vTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder );}portEXIT_CRITICAL();}}#endifvTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );portYIELD_WITHIN_API();}}else{taskEXIT_CRITICAL();traceQUEUE_RECEIVE_FAILED( pxQueue );return errQUEUE_EMPTY;}}taskEXIT_CRITICAL();}}#endif /* configUSE_ALTERNATIVE_API *//*-----------------------------------------------------------*/signed portBASE_TYPE xQueueGenericSendFromISR( xQueueHandle xQueue, const void * const pvItemToQueue, signed portBASE_TYPE *pxHigherPriorityTaskWoken, portBASE_TYPE xCopyPosition ){signed portBASE_TYPE xReturn;unsigned portBASE_TYPE uxSavedInterruptStatus;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) );/* RTOS ports that support interrupt nesting have the concept of a maximumsystem call (or maximum API call) interrupt priority. Interrupts that areabove the maximum system call priority are keep permanently enabled, evenwhen the RTOS kernel is in a critical section, but cannot make any calls toFreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.hthen portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertionfailure if a FreeRTOS API function is called from an interrupt that has beenassigned a priority above the configured maximum system call priority.Only FreeRTOS functions that end in FromISR can be called from interruptsthat have been assigned a priority at or (logically) below the maximumsystem call interrupt priority. FreeRTOS maintains a separate interruptsafe API to ensure interrupt entry is as fast and as simple as possible.More information (albeit Cortex-M specific) is provided on the followinglink: http://www.freertos.org/RTOS-Cortex-M3-M4.html */portASSERT_IF_INTERRUPT_PRIORITY_INVALID();/* Similar to xQueueGenericSend, except we don't block if there is no roomin the queue. Also we don't directly wake a task that was blocked on aqueue read, instead we return a flag to say whether a context switch isrequired or not (i.e. has a task with a higher priority than us been wokenby this post). */uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();{if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ){traceQUEUE_SEND_FROM_ISR( pxQueue );prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );/* If the queue is locked we do not alter the event list. This willbe done when the queue is unlocked later. */if( pxQueue->xTxLock == queueUNLOCKED ){#if ( configUSE_QUEUE_SETS == 1 ){if( pxQueue->pxQueueSetContainer != NULL ){if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) == pdTRUE ){/* The queue is a member of a queue set, and postingto the queue set caused a higher priority task tounblock. A context switch is required. */if( pxHigherPriorityTaskWoken != NULL ){*pxHigherPriorityTaskWoken = pdTRUE;}}}else{if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority so record that acontext switch is required. */if( pxHigherPriorityTaskWoken != NULL ){*pxHigherPriorityTaskWoken = pdTRUE;}}}}}#else /* configUSE_QUEUE_SETS */{if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority so record that acontext switch is required. */if( pxHigherPriorityTaskWoken != NULL ){*pxHigherPriorityTaskWoken = pdTRUE;}}}}#endif /* configUSE_QUEUE_SETS */}else{/* Increment the lock count so the task that unlocks the queueknows that data was posted while it was locked. */++( pxQueue->xTxLock );}xReturn = pdPASS;}else{traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue );xReturn = errQUEUE_FULL;}}portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );return xReturn;}/*-----------------------------------------------------------*/signed portBASE_TYPE xQueueGenericReceive( xQueueHandle xQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking ){signed portBASE_TYPE xEntryTimeSet = pdFALSE;xTimeOutType xTimeOut;signed char *pcOriginalReadPosition;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );/* This function relaxes the coding standard somewhat to allow returnstatements within the function itself. This is done in the interestof execution time efficiency. */for( ;; ){taskENTER_CRITICAL();{/* Is there data in the queue now? To be running we must bethe highest priority task wanting to access the queue. */if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){/* Remember the read position in case the queue is only beingpeeked. */pcOriginalReadPosition = pxQueue->u.pcReadFrom;prvCopyDataFromQueue( pxQueue, pvBuffer );if( xJustPeeking == pdFALSE ){traceQUEUE_RECEIVE( pxQueue );/* Actually removing data, not just peeking. */--( pxQueue->uxMessagesWaiting );#if ( configUSE_MUTEXES == 1 ){if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ){/* Record the information required to implementpriority inheritance should it become necessary. */pxQueue->pxMutexHolder = ( signed char * ) xTaskGetCurrentTaskHandle(); /*lint !e961 Cast is not redundant as xTaskHandle is a typedef. */}}#endifif( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE ){queueYIELD_IF_USING_PREEMPTION();}}}else{traceQUEUE_PEEK( pxQueue );/* The data is not being removed, so reset the readpointer. */pxQueue->u.pcReadFrom = pcOriginalReadPosition;/* The data is being left in the queue, so see if there areany other tasks waiting for the data. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){/* Tasks that are removed from the event list will get added tothe pending ready list as the scheduler is still suspended. */if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority than this task. */queueYIELD_IF_USING_PREEMPTION();}}}taskEXIT_CRITICAL();return pdPASS;}else{if( xTicksToWait == ( portTickType ) 0 ){/* The queue was empty and no block time is specified (orthe block time has expired) so leave now. */taskEXIT_CRITICAL();traceQUEUE_RECEIVE_FAILED( pxQueue );return errQUEUE_EMPTY;}else if( xEntryTimeSet == pdFALSE ){/* The queue was empty and a block time was specified soconfigure the timeout structure. */vTaskSetTimeOutState( &xTimeOut );xEntryTimeSet = pdTRUE;}else{/* Entry time was already set. */}}}taskEXIT_CRITICAL();/* Interrupts and other tasks can send to and receive from the queuenow the critical section has been exited. */vTaskSuspendAll();prvLockQueue( pxQueue );/* Update the timeout state to see if it has expired yet. */if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ){if( prvIsQueueEmpty( pxQueue ) != pdFALSE ){traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue );#if ( configUSE_MUTEXES == 1 ){if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ){portENTER_CRITICAL();{vTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder );}portEXIT_CRITICAL();}}#endifvTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );prvUnlockQueue( pxQueue );if( xTaskResumeAll() == pdFALSE ){portYIELD_WITHIN_API();}}else{/* Try again. */prvUnlockQueue( pxQueue );( void ) xTaskResumeAll();}}else{prvUnlockQueue( pxQueue );( void ) xTaskResumeAll();traceQUEUE_RECEIVE_FAILED( pxQueue );return errQUEUE_EMPTY;}}}/*-----------------------------------------------------------*/signed portBASE_TYPE xQueueReceiveFromISR( xQueueHandle xQueue, void * const pvBuffer, signed portBASE_TYPE *pxHigherPriorityTaskWoken ){signed portBASE_TYPE xReturn;unsigned portBASE_TYPE uxSavedInterruptStatus;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );/* RTOS ports that support interrupt nesting have the concept of a maximumsystem call (or maximum API call) interrupt priority. Interrupts that areabove the maximum system call priority are keep permanently enabled, evenwhen the RTOS kernel is in a critical section, but cannot make any calls toFreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.hthen portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertionfailure if a FreeRTOS API function is called from an interrupt that has beenassigned a priority above the configured maximum system call priority.Only FreeRTOS functions that end in FromISR can be called from interruptsthat have been assigned a priority at or (logically) below the maximumsystem call interrupt priority. FreeRTOS maintains a separate interruptsafe API to ensure interrupt entry is as fast and as simple as possible.More information (albeit Cortex-M specific) is provided on the followinglink: http://www.freertos.org/RTOS-Cortex-M3-M4.html */portASSERT_IF_INTERRUPT_PRIORITY_INVALID();uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();{/* Cannot block in an ISR, so check there is data available. */if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){traceQUEUE_RECEIVE_FROM_ISR( pxQueue );prvCopyDataFromQueue( pxQueue, pvBuffer );--( pxQueue->uxMessagesWaiting );/* If the queue is locked the event list will not be modified.Instead update the lock count so the task that unlocks the queuewill know that an ISR has removed data while the queue waslocked. */if( pxQueue->xRxLock == queueUNLOCKED ){if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ){/* The task waiting has a higher priority than us soforce a context switch. */if( pxHigherPriorityTaskWoken != NULL ){*pxHigherPriorityTaskWoken = pdTRUE;}}}}else{/* Increment the lock count so the task that unlocks the queueknows that data was removed while it was locked. */++( pxQueue->xRxLock );}xReturn = pdPASS;}else{xReturn = pdFAIL;traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue );}}portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );return xReturn;}/*-----------------------------------------------------------*/signed portBASE_TYPE xQueuePeekFromISR( xQueueHandle xQueue, void * const pvBuffer ){signed portBASE_TYPE xReturn;unsigned portBASE_TYPE uxSavedInterruptStatus;signed char *pcOriginalReadPosition;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) );/* RTOS ports that support interrupt nesting have the concept of a maximumsystem call (or maximum API call) interrupt priority. Interrupts that areabove the maximum system call priority are keep permanently enabled, evenwhen the RTOS kernel is in a critical section, but cannot make any calls toFreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.hthen portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertionfailure if a FreeRTOS API function is called from an interrupt that has beenassigned a priority above the configured maximum system call priority.Only FreeRTOS functions that end in FromISR can be called from interruptsthat have been assigned a priority at or (logically) below the maximumsystem call interrupt priority. FreeRTOS maintains a separate interruptsafe API to ensure interrupt entry is as fast and as simple as possible.More information (albeit Cortex-M specific) is provided on the followinglink: http://www.freertos.org/RTOS-Cortex-M3-M4.html */portASSERT_IF_INTERRUPT_PRIORITY_INVALID();uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();{/* Cannot block in an ISR, so check there is data available. */if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){traceQUEUE_PEEK_FROM_ISR( pxQueue );/* Remember the read position so it can be reset as nothing isactually being removed from the queue. */pcOriginalReadPosition = pxQueue->u.pcReadFrom;prvCopyDataFromQueue( pxQueue, pvBuffer );pxQueue->u.pcReadFrom = pcOriginalReadPosition;xReturn = pdPASS;}else{xReturn = pdFAIL;traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue );}}portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );return xReturn;}/*-----------------------------------------------------------*/unsigned portBASE_TYPE uxQueueMessagesWaiting( const xQueueHandle xQueue ){unsigned portBASE_TYPE uxReturn;configASSERT( xQueue );taskENTER_CRITICAL();uxReturn = ( ( xQUEUE * ) xQueue )->uxMessagesWaiting;taskEXIT_CRITICAL();return uxReturn;} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. *//*-----------------------------------------------------------*/unsigned portBASE_TYPE uxQueueSpacesAvailable( const xQueueHandle xQueue ){unsigned portBASE_TYPE uxReturn;xQUEUE *pxQueue;pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );taskENTER_CRITICAL();uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting;taskEXIT_CRITICAL();return uxReturn;} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. *//*-----------------------------------------------------------*/unsigned portBASE_TYPE uxQueueMessagesWaitingFromISR( const xQueueHandle xQueue ){unsigned portBASE_TYPE uxReturn;configASSERT( xQueue );uxReturn = ( ( xQUEUE * ) xQueue )->uxMessagesWaiting;return uxReturn;} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. *//*-----------------------------------------------------------*/void vQueueDelete( xQueueHandle xQueue ){xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;configASSERT( pxQueue );traceQUEUE_DELETE( pxQueue );#if ( configQUEUE_REGISTRY_SIZE > 0 ){vQueueUnregisterQueue( pxQueue );}#endifvPortFree( pxQueue->pcHead );vPortFree( pxQueue );}/*-----------------------------------------------------------*/#if ( configUSE_TRACE_FACILITY == 1 )unsigned char ucQueueGetQueueNumber( xQueueHandle xQueue ){return ( ( xQUEUE * ) xQueue )->ucQueueNumber;}#endif /* configUSE_TRACE_FACILITY *//*-----------------------------------------------------------*/#if ( configUSE_TRACE_FACILITY == 1 )void vQueueSetQueueNumber( xQueueHandle xQueue, unsigned char ucQueueNumber ){( ( xQUEUE * ) xQueue )->ucQueueNumber = ucQueueNumber;}#endif /* configUSE_TRACE_FACILITY *//*-----------------------------------------------------------*/#if ( configUSE_TRACE_FACILITY == 1 )unsigned char ucQueueGetQueueType( xQueueHandle xQueue ){return ( ( xQUEUE * ) xQueue )->ucQueueType;}#endif /* configUSE_TRACE_FACILITY *//*-----------------------------------------------------------*/static void prvCopyDataToQueue( xQUEUE *pxQueue, const void *pvItemToQueue, portBASE_TYPE xPosition ){if( pxQueue->uxItemSize == ( unsigned portBASE_TYPE ) 0 ){#if ( configUSE_MUTEXES == 1 ){if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ){/* The mutex is no longer being held. */vTaskPriorityDisinherit( ( void * ) pxQueue->pxMutexHolder );pxQueue->pxMutexHolder = NULL;}}#endif /* configUSE_MUTEXES */}else if( xPosition == queueSEND_TO_BACK ){( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. */pxQueue->pcWriteTo += pxQueue->uxItemSize;if( pxQueue->pcWriteTo >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */{pxQueue->pcWriteTo = pxQueue->pcHead;}}else{( void ) memcpy( ( void * ) pxQueue->u.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */pxQueue->u.pcReadFrom -= pxQueue->uxItemSize;if( pxQueue->u.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */{pxQueue->u.pcReadFrom = ( pxQueue->pcTail - pxQueue->uxItemSize );}if( xPosition == queueOVERWRITE ){if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){/* An item is not being added but overwritten, so subtractone from the recorded number of items in the queue so whenone is added again below the number of recorded items remainscorrect. */--( pxQueue->uxMessagesWaiting );}}}++( pxQueue->uxMessagesWaiting );}/*-----------------------------------------------------------*/static void prvCopyDataFromQueue( xQUEUE * const pxQueue, void * const pvBuffer ){if( pxQueue->uxQueueType != queueQUEUE_IS_MUTEX ){pxQueue->u.pcReadFrom += pxQueue->uxItemSize;if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */{pxQueue->u.pcReadFrom = pxQueue->pcHead;}( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. */}}/*-----------------------------------------------------------*/static void prvUnlockQueue( xQUEUE *pxQueue ){/* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. *//* The lock counts contains the number of extra data items placed orremoved from the queue while the queue was locked. When a queue islocked items can be added or removed, but the event lists cannot beupdated. */taskENTER_CRITICAL();{/* See if data was added to the queue while it was locked. */while( pxQueue->xTxLock > queueLOCKED_UNMODIFIED ){/* Data was posted while the queue was locked. Are any tasksblocked waiting for data to become available? */#if ( configUSE_QUEUE_SETS == 1 ){if( pxQueue->pxQueueSetContainer != NULL ){if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) == pdTRUE ){/* The queue is a member of a queue set, and posting tothe queue set caused a higher priority task to unblock.A context switch is required. */vTaskMissedYield();}}else{/* Tasks that are removed from the event list will get added tothe pending ready list as the scheduler is still suspended. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority so record that acontext switch is required. */vTaskMissedYield();}}else{break;}}}#else /* configUSE_QUEUE_SETS */{/* Tasks that are removed from the event list will get added tothe pending ready list as the scheduler is still suspended. */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority so record that acontext switch is required. */vTaskMissedYield();}}else{break;}}#endif /* configUSE_QUEUE_SETS */--( pxQueue->xTxLock );}pxQueue->xTxLock = queueUNLOCKED;}taskEXIT_CRITICAL();/* Do the same for the Rx lock. */taskENTER_CRITICAL();{while( pxQueue->xRxLock > queueLOCKED_UNMODIFIED ){if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ){vTaskMissedYield();}--( pxQueue->xRxLock );}else{break;}}pxQueue->xRxLock = queueUNLOCKED;}taskEXIT_CRITICAL();}/*-----------------------------------------------------------*/static signed portBASE_TYPE prvIsQueueEmpty( const xQUEUE *pxQueue ){signed portBASE_TYPE xReturn;taskENTER_CRITICAL();{if( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0 ){xReturn = pdTRUE;}else{xReturn = pdFALSE;}}taskEXIT_CRITICAL();return xReturn;}/*-----------------------------------------------------------*/signed portBASE_TYPE xQueueIsQueueEmptyFromISR( const xQueueHandle xQueue ){signed portBASE_TYPE xReturn;configASSERT( xQueue );if( ( ( xQUEUE * ) xQueue )->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0 ){xReturn = pdTRUE;}else{xReturn = pdFALSE;}return xReturn;} /*lint !e818 xQueue could not be pointer to const because it is a typedef. *//*-----------------------------------------------------------*/static signed portBASE_TYPE prvIsQueueFull( const xQUEUE *pxQueue ){signed portBASE_TYPE xReturn;taskENTER_CRITICAL();{if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ){xReturn = pdTRUE;}else{xReturn = pdFALSE;}}taskEXIT_CRITICAL();return xReturn;}/*-----------------------------------------------------------*/signed portBASE_TYPE xQueueIsQueueFullFromISR( const xQueueHandle xQueue ){signed portBASE_TYPE xReturn;configASSERT( xQueue );if( ( ( xQUEUE * ) xQueue )->uxMessagesWaiting == ( ( xQUEUE * ) xQueue )->uxLength ){xReturn = pdTRUE;}else{xReturn = pdFALSE;}return xReturn;} /*lint !e818 xQueue could not be pointer to const because it is a typedef. *//*-----------------------------------------------------------*/#if ( configUSE_CO_ROUTINES == 1 )signed portBASE_TYPE xQueueCRSend( xQueueHandle xQueue, const void *pvItemToQueue, portTickType xTicksToWait ){signed portBASE_TYPE xReturn;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;/* If the queue is already full we may have to block. A critical sectionis required to prevent an interrupt removing something from the queuebetween the check to see if the queue is full and blocking on the queue. */portDISABLE_INTERRUPTS();{if( prvIsQueueFull( pxQueue ) != pdFALSE ){/* The queue is full - do we want to block or just leave withoutposting? */if( xTicksToWait > ( portTickType ) 0 ){/* As this is called from a coroutine we cannot block directly, butreturn indicating that we need to block. */vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) );portENABLE_INTERRUPTS();return errQUEUE_BLOCKED;}else{portENABLE_INTERRUPTS();return errQUEUE_FULL;}}}portENABLE_INTERRUPTS();portDISABLE_INTERRUPTS();{if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ){/* There is room in the queue, copy the data into the queue. */prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK );xReturn = pdPASS;/* Were any co-routines waiting for data to become available? */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){/* In this instance the co-routine could be placed directlyinto the ready list as we are within a critical section.Instead the same pending ready list mechanism is used as ifthe event were caused from within an interrupt. */if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){/* The co-routine waiting has a higher priority so recordthat a yield might be appropriate. */xReturn = errQUEUE_YIELD;}}}else{xReturn = errQUEUE_FULL;}}portENABLE_INTERRUPTS();return xReturn;}#endif /* configUSE_CO_ROUTINES *//*-----------------------------------------------------------*/#if ( configUSE_CO_ROUTINES == 1 )signed portBASE_TYPE xQueueCRReceive( xQueueHandle xQueue, void *pvBuffer, portTickType xTicksToWait ){signed portBASE_TYPE xReturn;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;/* If the queue is already empty we may have to block. A critical sectionis required to prevent an interrupt adding something to the queuebetween the check to see if the queue is empty and blocking on the queue. */portDISABLE_INTERRUPTS();{if( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0 ){/* There are no messages in the queue, do we want to block or justleave with nothing? */if( xTicksToWait > ( portTickType ) 0 ){/* As this is a co-routine we cannot block directly, but returnindicating that we need to block. */vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) );portENABLE_INTERRUPTS();return errQUEUE_BLOCKED;}else{portENABLE_INTERRUPTS();return errQUEUE_FULL;}}}portENABLE_INTERRUPTS();portDISABLE_INTERRUPTS();{if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){/* Data is available from the queue. */pxQueue->u.pcReadFrom += pxQueue->uxItemSize;if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ){pxQueue->u.pcReadFrom = pxQueue->pcHead;}--( pxQueue->uxMessagesWaiting );( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize );xReturn = pdPASS;/* Were any co-routines waiting for space to become available? */if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){/* In this instance the co-routine could be placed directlyinto the ready list as we are within a critical section.Instead the same pending ready list mechanism is used as ifthe event were caused from within an interrupt. */if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ){xReturn = errQUEUE_YIELD;}}}else{xReturn = pdFAIL;}}portENABLE_INTERRUPTS();return xReturn;}#endif /* configUSE_CO_ROUTINES *//*-----------------------------------------------------------*/#if ( configUSE_CO_ROUTINES == 1 )signed portBASE_TYPE xQueueCRSendFromISR( xQueueHandle xQueue, const void *pvItemToQueue, signed portBASE_TYPE xCoRoutinePreviouslyWoken ){xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;/* Cannot block within an ISR so if there is no space on the queue thenexit without doing anything. */if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ){prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK );/* We only want to wake one co-routine per ISR, so check that aco-routine has not already been woken. */if( xCoRoutinePreviouslyWoken == pdFALSE ){if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ){if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ){return pdTRUE;}}}}return xCoRoutinePreviouslyWoken;}#endif /* configUSE_CO_ROUTINES *//*-----------------------------------------------------------*/#if ( configUSE_CO_ROUTINES == 1 )signed portBASE_TYPE xQueueCRReceiveFromISR( xQueueHandle xQueue, void *pvBuffer, signed portBASE_TYPE *pxCoRoutineWoken ){signed portBASE_TYPE xReturn;xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;/* We cannot block from an ISR, so check there is data available. Ifnot then just leave without doing anything. */if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ){/* Copy the data from the queue. */pxQueue->u.pcReadFrom += pxQueue->uxItemSize;if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ){pxQueue->u.pcReadFrom = pxQueue->pcHead;}--( pxQueue->uxMessagesWaiting );( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize );if( ( *pxCoRoutineWoken ) == pdFALSE ){if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ){if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ){*pxCoRoutineWoken = pdTRUE;}}}xReturn = pdPASS;}else{xReturn = pdFAIL;}return xReturn;}#endif /* configUSE_CO_ROUTINES *//*-----------------------------------------------------------*/#if ( configQUEUE_REGISTRY_SIZE > 0 )void vQueueAddToRegistry( xQueueHandle xQueue, signed char *pcQueueName ){unsigned portBASE_TYPE ux;/* See if there is an empty space in the registry. A NULL name denotesa free slot. */for( ux = ( unsigned portBASE_TYPE ) 0U; ux < ( unsigned portBASE_TYPE ) configQUEUE_REGISTRY_SIZE; ux++ ){if( xQueueRegistry[ ux ].pcQueueName == NULL ){/* Store the information on this queue. */xQueueRegistry[ ux ].pcQueueName = pcQueueName;xQueueRegistry[ ux ].xHandle = xQueue;break;}}}#endif /* configQUEUE_REGISTRY_SIZE *//*-----------------------------------------------------------*/#if ( configQUEUE_REGISTRY_SIZE > 0 )void vQueueUnregisterQueue( xQueueHandle xQueue ){unsigned portBASE_TYPE ux;/* See if the handle of the queue being unregistered in actually in theregistry. */for( ux = ( unsigned portBASE_TYPE ) 0U; ux < ( unsigned portBASE_TYPE ) configQUEUE_REGISTRY_SIZE; ux++ ){if( xQueueRegistry[ ux ].xHandle == xQueue ){/* Set the name to NULL to show that this slot if free again. */xQueueRegistry[ ux ].pcQueueName = NULL;break;}}} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */#endif /* configQUEUE_REGISTRY_SIZE *//*-----------------------------------------------------------*/#if ( configUSE_TIMERS == 1 )void vQueueWaitForMessageRestricted( xQueueHandle xQueue, portTickType xTicksToWait ){xQUEUE * const pxQueue = ( xQUEUE * ) xQueue;/* This function should not be called by application code hence the'Restricted' in its name. It is not part of the public API. It isdesigned for use by kernel code, and has special calling requirements.It can result in vListInsert() being called on a list that can onlypossibly ever have one item in it, so the list will be fast, but evenso it should be called with the scheduler locked and not from a criticalsection. *//* Only do anything if there are no messages in the queue. This functionwill not actually cause the task to block, just place it on a blockedlist. It will not block until the scheduler is unlocked - at whichtime a yield will be performed. If an item is added to the queue whilethe queue is locked, and the calling task blocks on the queue, then thecalling task will be immediately unblocked when the queue is unlocked. */prvLockQueue( pxQueue );if( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0U ){/* There is nothing in the queue, block for the specified period. */vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );}prvUnlockQueue( pxQueue );}#endif /* configUSE_TIMERS *//*-----------------------------------------------------------*/#if ( configUSE_QUEUE_SETS == 1 )xQueueSetHandle xQueueCreateSet( unsigned portBASE_TYPE uxEventQueueLength ){xQueueSetHandle pxQueue;pxQueue = xQueueGenericCreate( uxEventQueueLength, sizeof( xQUEUE * ), queueQUEUE_TYPE_SET );return pxQueue;}#endif /* configUSE_QUEUE_SETS *//*-----------------------------------------------------------*/#if ( configUSE_QUEUE_SETS == 1 )portBASE_TYPE xQueueAddToSet( xQueueSetMemberHandle xQueueOrSemaphore, xQueueSetHandle xQueueSet ){portBASE_TYPE xReturn;if( ( ( xQUEUE * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ){/* Cannot add a queue/semaphore to more than one queue set. */xReturn = pdFAIL;}else if( ( ( xQUEUE * ) xQueueOrSemaphore )->uxMessagesWaiting != ( unsigned portBASE_TYPE ) 0 ){/* Cannot add a queue/semaphore to a queue set if there are alreadyitems in the queue/semaphore. */xReturn = pdFAIL;}else{taskENTER_CRITICAL();{( ( xQUEUE * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet;}taskEXIT_CRITICAL();xReturn = pdPASS;}return xReturn;}#endif /* configUSE_QUEUE_SETS *//*-----------------------------------------------------------*/#if ( configUSE_QUEUE_SETS == 1 )portBASE_TYPE xQueueRemoveFromSet( xQueueSetMemberHandle xQueueOrSemaphore, xQueueSetHandle xQueueSet ){portBASE_TYPE xReturn;xQUEUE * const pxQueueOrSemaphore = ( xQUEUE * ) xQueueOrSemaphore;if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ){/* The queue was not a member of the set. */xReturn = pdFAIL;}else if( pxQueueOrSemaphore->uxMessagesWaiting != ( unsigned portBASE_TYPE ) 0 ){/* It is dangerous to remove a queue from a set when the queue isnot empty because the queue set will still hold pending events forthe queue. */xReturn = pdFAIL;}else{taskENTER_CRITICAL();{/* The queue is no longer contained in the set. */pxQueueOrSemaphore->pxQueueSetContainer = NULL;}taskEXIT_CRITICAL();xReturn = pdPASS;}return xReturn;} /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */#endif /* configUSE_QUEUE_SETS *//*-----------------------------------------------------------*/#if ( configUSE_QUEUE_SETS == 1 )xQueueSetMemberHandle xQueueSelectFromSet( xQueueSetHandle xQueueSet, portTickType xBlockTimeTicks ){xQueueSetMemberHandle xReturn = NULL;( void ) xQueueGenericReceive( ( xQueueHandle ) xQueueSet, &xReturn, xBlockTimeTicks, pdFALSE ); /*lint !e961 Casting from one typedef to another is not redundant. */return xReturn;}#endif /* configUSE_QUEUE_SETS *//*-----------------------------------------------------------*/#if ( configUSE_QUEUE_SETS == 1 )xQueueSetMemberHandle xQueueSelectFromSetFromISR( xQueueSetHandle xQueueSet ){xQueueSetMemberHandle xReturn = NULL;( void ) xQueueReceiveFromISR( ( xQueueHandle ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */return xReturn;}#endif /* configUSE_QUEUE_SETS *//*-----------------------------------------------------------*/#if ( configUSE_QUEUE_SETS == 1 )static portBASE_TYPE prvNotifyQueueSetContainer( const xQUEUE * const pxQueue, portBASE_TYPE xCopyPosition ){xQUEUE *pxQueueSetContainer = pxQueue->pxQueueSetContainer;portBASE_TYPE xReturn = pdFALSE;configASSERT( pxQueueSetContainer );configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength );if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ){traceQUEUE_SEND( pxQueueSetContainer );/* The data copies is the handle of the queue that contains data. */prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition );if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ){if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ){/* The task waiting has a higher priority */xReturn = pdTRUE;}}}return xReturn;}#endif /* configUSE_QUEUE_SETS */
123version https://git-lfs.github.com/spec/v1oid sha256:a012374984bc07c161efc887002b9bc9b774e04b20e94c488d37618ba1bd4204size 27593123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//* Standard includes. */#include <stdlib.h>/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefiningall the API functions to use the MPU wrappers. That should only be done whentask.h is included from an application file. */#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE#include "FreeRTOS.h"#include "task.h"#include "queue.h"#include "timers.h"/* Lint e961 and e750 are suppressed as a MISRA exception justified because theMPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for theheader files above, but not in this file, in order to generate the correctprivileged Vs unprivileged linkage and placement. */#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. *//* This entire source file will be skipped if the application is not configuredto include software timer functionality. This #if is closed at the very bottomof this file. If you want to include software timer functionality then ensureconfigUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */#if ( configUSE_TIMERS == 1 )/* Misc definitions. */#define tmrNO_DELAY ( portTickType ) 0U/* The definition of the timers themselves. */typedef struct tmrTimerControl{const signed char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */xListItem xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */portTickType xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */unsigned portBASE_TYPE uxAutoReload; /*<< Set to pdTRUE if the timer should be automatically restarted once expired. Set to pdFALSE if the timer is, in effect, a one shot timer. */void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */tmrTIMER_CALLBACK pxCallbackFunction; /*<< The function that will be called when the timer expires. */} xTIMER;/* The definition of messages that can be sent and received on the timerqueue. */typedef struct tmrTimerQueueMessage{portBASE_TYPE xMessageID; /*<< The command being sent to the timer service task. */portTickType xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */xTIMER * pxTimer; /*<< The timer to which the command will be applied. */} xTIMER_MESSAGE;/*lint -e956 A manual analysis and inspection has been used to determine whichstatic variables must be declared volatile. *//* The list in which active timers are stored. Timers are referenced in expiretime order, with the nearest expiry time at the front of the list. Only thetimer service task is allowed to access xActiveTimerList. */PRIVILEGED_DATA static xList xActiveTimerList1;PRIVILEGED_DATA static xList xActiveTimerList2;PRIVILEGED_DATA static xList *pxCurrentTimerList;PRIVILEGED_DATA static xList *pxOverflowTimerList;/* A queue that is used to send commands to the timer service task. */PRIVILEGED_DATA static xQueueHandle xTimerQueue = NULL;#if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )PRIVILEGED_DATA static xTaskHandle xTimerTaskHandle = NULL;#endif/*lint +e956 *//*-----------------------------------------------------------*//** Initialise the infrastructure used by the timer service task if it has not* been initialised already.*/static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;/** The timer service task (daemon). Timer functionality is controlled by this* task. Other tasks communicate with the timer service task using the* xTimerQueue queue.*/static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION;/** Called by the timer service task to interpret and process a command it* received on the timer queue.*/static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;/** Insert the timer into either xActiveTimerList1, or xActiveTimerList2,* depending on if the expire time causes a timer counter overflow.*/static portBASE_TYPE prvInsertTimerInActiveList( xTIMER *pxTimer, portTickType xNextExpiryTime, portTickType xTimeNow, portTickType xCommandTime ) PRIVILEGED_FUNCTION;/** An active timer has reached its expire time. Reload the timer if it is an* auto reload timer, then call its callback.*/static void prvProcessExpiredTimer( portTickType xNextExpireTime, portTickType xTimeNow ) PRIVILEGED_FUNCTION;/** The tick count has overflowed. Switch the timer lists after ensuring the* current timer list does not still reference some timers.*/static void prvSwitchTimerLists( portTickType xLastTime ) PRIVILEGED_FUNCTION;/** Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE* if a tick count overflow occurred since prvSampleTimeNow() was last called.*/static portTickType prvSampleTimeNow( portBASE_TYPE *pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;/** If the timer list contains any active timers then return the expire time of* the timer that will expire first and set *pxListWasEmpty to false. If the* timer list does not contain any timers then return 0 and set *pxListWasEmpty* to pdTRUE.*/static portTickType prvGetNextExpireTime( portBASE_TYPE *pxListWasEmpty ) PRIVILEGED_FUNCTION;/** If a timer has expired, process it. Otherwise, block the timer service task* until either a timer does expire or a command is received.*/static void prvProcessTimerOrBlockTask( portTickType xNextExpireTime, portBASE_TYPE xListWasEmpty ) PRIVILEGED_FUNCTION;/*-----------------------------------------------------------*/portBASE_TYPE xTimerCreateTimerTask( void ){portBASE_TYPE xReturn = pdFAIL;/* This function is called when the scheduler is started ifconfigUSE_TIMERS is set to 1. Check that the infrastructure used by thetimer service task has been created/initialised. If timers have alreadybeen created then the initialisation will already have been performed. */prvCheckForValidListAndQueue();if( xTimerQueue != NULL ){#if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 ){/* Create the timer task, storing its handle in xTimerTaskHandle soit can be returned by the xTimerGetTimerDaemonTaskHandle() function. */xReturn = xTaskCreate( prvTimerTask, ( const signed char * ) "Tmr Svc", ( unsigned short ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( unsigned portBASE_TYPE ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, &xTimerTaskHandle );}#else{/* Create the timer task without storing its handle. */xReturn = xTaskCreate( prvTimerTask, ( const signed char * ) "Tmr Svc", ( unsigned short ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( unsigned portBASE_TYPE ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, NULL);}#endif}configASSERT( xReturn );return xReturn;}/*-----------------------------------------------------------*/xTimerHandle xTimerCreate( const signed char * const pcTimerName, portTickType xTimerPeriodInTicks, unsigned portBASE_TYPE uxAutoReload, void *pvTimerID, tmrTIMER_CALLBACK pxCallbackFunction ){xTIMER *pxNewTimer;/* Allocate the timer structure. */if( xTimerPeriodInTicks == ( portTickType ) 0U ){pxNewTimer = NULL;}else{pxNewTimer = ( xTIMER * ) pvPortMalloc( sizeof( xTIMER ) );if( pxNewTimer != NULL ){/* Ensure the infrastructure used by the timer service task has beencreated/initialised. */prvCheckForValidListAndQueue();/* Initialise the timer structure members using the function parameters. */pxNewTimer->pcTimerName = pcTimerName;pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;pxNewTimer->uxAutoReload = uxAutoReload;pxNewTimer->pvTimerID = pvTimerID;pxNewTimer->pxCallbackFunction = pxCallbackFunction;vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );traceTIMER_CREATE( pxNewTimer );}else{traceTIMER_CREATE_FAILED();}}/* 0 is not a valid value for xTimerPeriodInTicks. */configASSERT( ( xTimerPeriodInTicks > 0 ) );return ( xTimerHandle ) pxNewTimer;}/*-----------------------------------------------------------*/portBASE_TYPE xTimerGenericCommand( xTimerHandle xTimer, portBASE_TYPE xCommandID, portTickType xOptionalValue, signed portBASE_TYPE *pxHigherPriorityTaskWoken, portTickType xBlockTime ){portBASE_TYPE xReturn = pdFAIL;xTIMER_MESSAGE xMessage;/* Send a message to the timer service task to perform a particular actionon a particular timer definition. */if( xTimerQueue != NULL ){/* Send a command to the timer service task to start the xTimer timer. */xMessage.xMessageID = xCommandID;xMessage.xMessageValue = xOptionalValue;xMessage.pxTimer = ( xTIMER * ) xTimer;if( pxHigherPriorityTaskWoken == NULL ){if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ){xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xBlockTime );}else{xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );}}else{xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );}traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );}return xReturn;}/*-----------------------------------------------------------*/#if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )xTaskHandle xTimerGetTimerDaemonTaskHandle( void ){/* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has beenstarted, then xTimerTaskHandle will be NULL. */configASSERT( ( xTimerTaskHandle != NULL ) );return xTimerTaskHandle;}#endif/*-----------------------------------------------------------*/static void prvProcessExpiredTimer( portTickType xNextExpireTime, portTickType xTimeNow ){xTIMER *pxTimer;portBASE_TYPE xResult;/* Remove the timer from the list of active timers. A check has alreadybeen performed to ensure the list is not empty. */pxTimer = ( xTIMER * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );( void ) uxListRemove( &( pxTimer->xTimerListItem ) );traceTIMER_EXPIRED( pxTimer );/* If the timer is an auto reload timer then calculate the nextexpiry time and re-insert the timer in the list of active timers. */if( pxTimer->uxAutoReload == ( unsigned portBASE_TYPE ) pdTRUE ){/* This is the only time a timer is inserted into a list usinga time relative to anything other than the current time. Itwill therefore be inserted into the correct list relative tothe time this task thinks it is now, even if a command toswitch lists due to a tick count overflow is already waiting inthe timer queue. */if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) == pdTRUE ){/* The timer expired before it was added to the active timerlist. Reload it now. */xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START, xNextExpireTime, NULL, tmrNO_DELAY );configASSERT( xResult );( void ) xResult;}}/* Call the timer callback. */pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer );}/*-----------------------------------------------------------*/static void prvTimerTask( void *pvParameters ){portTickType xNextExpireTime;portBASE_TYPE xListWasEmpty;/* Just to avoid compiler warnings. */( void ) pvParameters;for( ;; ){/* Query the timers list to see if it contains any timers, and if so,obtain the time at which the next timer will expire. */xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );/* If a timer has expired, process it. Otherwise, block this taskuntil either a timer does expire, or a command is received. */prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );/* Empty the command queue. */prvProcessReceivedCommands();}}/*-----------------------------------------------------------*/static void prvProcessTimerOrBlockTask( portTickType xNextExpireTime, portBASE_TYPE xListWasEmpty ){portTickType xTimeNow;portBASE_TYPE xTimerListsWereSwitched;vTaskSuspendAll();{/* Obtain the time now to make an assessment as to whether the timerhas expired or not. If obtaining the time causes the lists to switchthen don't process this timer as any timers that remained in the listwhen the lists were switched will have been processed within theprvSampelTimeNow() function. */xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );if( xTimerListsWereSwitched == pdFALSE ){/* The tick count has not overflowed, has the timer expired? */if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ){( void ) xTaskResumeAll();prvProcessExpiredTimer( xNextExpireTime, xTimeNow );}else{/* The tick count has not overflowed, and the next expiretime has not been reached yet. This task should thereforeblock to wait for the next expire time or a command to bereceived - whichever comes first. The following line cannotbe reached unless xNextExpireTime > xTimeNow, except in thecase when the current timer list is empty. */vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ) );if( xTaskResumeAll() == pdFALSE ){/* Yield to wait for either a command to arrive, or the block timeto expire. If a command arrived between the critical section beingexited and this yield then the yield will not cause the taskto block. */portYIELD_WITHIN_API();}}}else{( void ) xTaskResumeAll();}}}/*-----------------------------------------------------------*/static portTickType prvGetNextExpireTime( portBASE_TYPE *pxListWasEmpty ){portTickType xNextExpireTime;/* Timers are listed in expiry time order, with the head of the listreferencing the task that will expire first. Obtain the time at whichthe timer with the nearest expiry time will expire. If there are noactive timers then just set the next expire time to 0. That will causethis task to unblock when the tick count overflows, at which point thetimer lists will be switched and the next expiry time can bere-assessed. */*pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );if( *pxListWasEmpty == pdFALSE ){xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );}else{/* Ensure the task unblocks when the tick count rolls over. */xNextExpireTime = ( portTickType ) 0U;}return xNextExpireTime;}/*-----------------------------------------------------------*/static portTickType prvSampleTimeNow( portBASE_TYPE *pxTimerListsWereSwitched ){portTickType xTimeNow;PRIVILEGED_DATA static portTickType xLastTime = ( portTickType ) 0U; /*lint !e956 Variable is only accessible to one task. */xTimeNow = xTaskGetTickCount();if( xTimeNow < xLastTime ){prvSwitchTimerLists( xLastTime );*pxTimerListsWereSwitched = pdTRUE;}else{*pxTimerListsWereSwitched = pdFALSE;}xLastTime = xTimeNow;return xTimeNow;}/*-----------------------------------------------------------*/static portBASE_TYPE prvInsertTimerInActiveList( xTIMER *pxTimer, portTickType xNextExpiryTime, portTickType xTimeNow, portTickType xCommandTime ){portBASE_TYPE xProcessTimerNow = pdFALSE;listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );if( xNextExpiryTime <= xTimeNow ){/* Has the expiry time elapsed between the command to start/reset atimer was issued, and the time the command was processed? */if( ( xTimeNow - xCommandTime ) >= pxTimer->xTimerPeriodInTicks ){/* The time between a command being issued and the command beingprocessed actually exceeds the timers period. */xProcessTimerNow = pdTRUE;}else{vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );}}else{if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ){/* If, since the command was issued, the tick count has overflowedbut the expiry time has not, then the timer must have already passedits expiry time and should be processed immediately. */xProcessTimerNow = pdTRUE;}else{vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );}}return xProcessTimerNow;}/*-----------------------------------------------------------*/static void prvProcessReceivedCommands( void ){xTIMER_MESSAGE xMessage;xTIMER *pxTimer;portBASE_TYPE xTimerListsWereSwitched, xResult;portTickType xTimeNow;while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */{pxTimer = xMessage.pxTimer;if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ){/* The timer is in a list, remove it. */( void ) uxListRemove( &( pxTimer->xTimerListItem ) );}traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.xMessageValue );/* In this case the xTimerListsWereSwitched parameter is not used, butit must be present in the function call. prvSampleTimeNow() must becalled after the message is received from xTimerQueue so there is nopossibility of a higher priority task adding a message to the messagequeue with a time that is ahead of the timer daemon task (because itpre-empted the timer daemon task after the xTimeNow value was set). */xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );switch( xMessage.xMessageID ){case tmrCOMMAND_START :/* Start or restart a timer. */if( prvInsertTimerInActiveList( pxTimer, xMessage.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.xMessageValue ) == pdTRUE ){/* The timer expired before it was added to the active timerlist. Process it now. */pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer );if( pxTimer->uxAutoReload == ( unsigned portBASE_TYPE ) pdTRUE ){xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START, xMessage.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );configASSERT( xResult );( void ) xResult;}}break;case tmrCOMMAND_STOP :/* The timer has already been removed from the active list.There is nothing to do here. */break;case tmrCOMMAND_CHANGE_PERIOD :pxTimer->xTimerPeriodInTicks = xMessage.xMessageValue;configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );/* The new period does not really have a reference, and can belonger or shorter than the old one. The command time istherefore set to the current time, and as the period cannot bezero the next expiry time can only be in the future, meaning(unlike for the xTimerStart() case above) there is no fail casethat needs to be handled here. */( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );break;case tmrCOMMAND_DELETE :/* The timer has already been removed from the active list,just free up the memory. */vPortFree( pxTimer );break;default :/* Don't expect to get here. */break;}}}/*-----------------------------------------------------------*/static void prvSwitchTimerLists( portTickType xLastTime ){portTickType xNextExpireTime, xReloadTime;xList *pxTemp;xTIMER *pxTimer;portBASE_TYPE xResult;/* Remove compiler warnings if configASSERT() is not defined. */( void ) xLastTime;/* The tick count has overflowed. The timer lists must be switched.If there are any timers still referenced from the current timer listthen they must have expired and should be processed before the listsare switched. */while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ){xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );/* Remove the timer from the list. */pxTimer = ( xTIMER * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );( void ) uxListRemove( &( pxTimer->xTimerListItem ) );/* Execute its callback, then send a command to restart the timer ifit is an auto-reload timer. It cannot be restarted here as the listshave not yet been switched. */pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer );if( pxTimer->uxAutoReload == ( unsigned portBASE_TYPE ) pdTRUE ){/* Calculate the reload value, and if the reload value results inthe timer going into the same timer list then it has already expiredand the timer should be re-inserted into the current list so it isprocessed again within this loop. Otherwise a command should be sentto restart the timer to ensure it is only inserted into a list afterthe lists have been swapped. */xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );if( xReloadTime > xNextExpireTime ){listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );}else{xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START, xNextExpireTime, NULL, tmrNO_DELAY );configASSERT( xResult );( void ) xResult;}}}pxTemp = pxCurrentTimerList;pxCurrentTimerList = pxOverflowTimerList;pxOverflowTimerList = pxTemp;}/*-----------------------------------------------------------*/static void prvCheckForValidListAndQueue( void ){/* Check that the list from which active timers are referenced, and thequeue used to communicate with the timer service, have beeninitialised. */taskENTER_CRITICAL();{if( xTimerQueue == NULL ){vListInitialise( &xActiveTimerList1 );vListInitialise( &xActiveTimerList2 );pxCurrentTimerList = &xActiveTimerList1;pxOverflowTimerList = &xActiveTimerList2;xTimerQueue = xQueueCreate( ( unsigned portBASE_TYPE ) configTIMER_QUEUE_LENGTH, sizeof( xTIMER_MESSAGE ) );}}taskEXIT_CRITICAL();}/*-----------------------------------------------------------*/portBASE_TYPE xTimerIsTimerActive( xTimerHandle xTimer ){portBASE_TYPE xTimerIsInActiveList;xTIMER *pxTimer = ( xTIMER * ) xTimer;/* Is the timer in the list of active timers? */taskENTER_CRITICAL();{/* Checking to see if it is in the NULL list in effect checks to see ifit is referenced from either the current or the overflow timer lists inone go, but the logic has to be reversed, hence the '!'. */xTimerIsInActiveList = !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) );}taskEXIT_CRITICAL();return xTimerIsInActiveList;}/*-----------------------------------------------------------*/void *pvTimerGetTimerID( xTimerHandle xTimer ){xTIMER *pxTimer = ( xTIMER * ) xTimer;return pxTimer->pvTimerID;}/*-----------------------------------------------------------*//* This entire source file will be skipped if the application is not configuredto include software timer functionality. If you want to include software timerfunctionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */#endif /* configUSE_TIMERS == 1 */
123version https://git-lfs.github.com/spec/v1oid sha256:3100c5b2df10d8dc4b938935fe751f90c2686d4b9d4ce8a0d1be9533ec50cdf3size 22931234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162del *.elfecho onset targetcpu=__SAM3N4C__rem SETUP FREERTOS MEMEORY MANAGERrem heap_1: allocate onlyrem heap_2: allocate + deallocateset RTOSMEMMGR=heap_2set gccpath="../../software\ARMGCCToolchain/bin"set include1=freertos/includeset include2=freertos/portableset include3=cm3/includeset include4=source/includeset include5=cm3/include/componentset include6=cm3/include/instanceset include7=cm3/include/pioset include=-I %include1% -I %include2% -I %include3% -I %include4% -I %include5% -I %include6% -I %include7%set compiler_args=%include% -D%targetcpu% -DBOARD=SAM3N_EK -mthumb -mcpu=cortex-m3 -O0 -fdata-sections -ffunction-sections -mlong-calls -g3 -Wall -c -std=gnu99 -MD -MPset linker_args=%include% -Wl,-Map=out.map -Wl,--start-group -lm -Wl,--end-group -L\"../../cmsis/linkerScripts\" -Wl,--gc-sections -Tflash.ld -Wl,--cref -Wl,--entry=Reset_Handler -mthumb -mcpu=cortex-m3set assembler_args=%include% -mthumb -g -mcpu=cortex-m3set compiler=arm-none-eabi-gccset linker=arm-none-eabi-gccset assembler=arm-none-eabi-asset size=arm-none-eabi-size.exerem ============= COMPILE DEMO =============%gccpath%\%compiler% source/main.c %compiler_args%%gccpath%\%compiler% source/serial.c %compiler_args%rem ============= COMPILE FREERTOS =============%gccpath%\%compiler% freertos/croutine.c %compiler_args%%gccpath%\%compiler% freertos/list.c %compiler_args%%gccpath%\%compiler% freertos/queue.c %compiler_args%%gccpath%\%compiler% freertos/tasks.c %compiler_args%%gccpath%\%compiler% freertos/timers.c %compiler_args%%gccpath%\%compiler% freertos/mem/%RTOSMEMMGR%.c %compiler_args%%gccpath%\%compiler% freertos/portable/port.c %compiler_args%rem ============= COMPILE CM3 CORE =============%gccpath%\%compiler% cm3/exceptions.c %compiler_args%%gccpath%\%compiler% cm3/startup_sam3n.c %compiler_args%%gccpath%\%compiler% cm3/system_sam3n.c %compiler_args%rem ============= LINK ALL =============%gccpath%\%linker% -o demo.elf %RTOSMEMMGR%.o port.o croutine.o list.o queue.o tasks.o timers.o exceptions.o startup_sam3n.o system_sam3n.o serial.o main.o %linker_args%%gccpath%\%size% demo.elfecho offdel *.mapdel *.asmdel *.sdfdel *.pwidel *.dbkdel *.odel *.d
123version https://git-lfs.github.com/spec/v1oid sha256:4f911bb3c772b692be876d8281a46346b0eea5f612482da5817007c135319079size 3933123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596#ifndef FREERTOS_CONFIG_H#define FREERTOS_CONFIG_H/*-----------------------------------------------------------* Application specific definitions.** These definitions should be adjusted for your particular hardware and* application requirements.** THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE* FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.** See http://www.freertos.org/a00110.html.*----------------------------------------------------------*/#include <stdint.h>extern uint32_t SystemCoreClock;#define configUSE_PREEMPTION 1#define configUSE_IDLE_HOOK 0#define configUSE_TICK_HOOK 0#define configCPU_CLOCK_HZ ( SystemCoreClock )#define configTICK_RATE_HZ ( ( portTickType ) 1000 )#define configMAX_PRIORITIES ( ( unsigned portBASE_TYPE ) 5 )#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 130 )#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 4096 ) ) //( ( size_t ) ( 16384 )#define configMAX_TASK_NAME_LEN ( 10 )#define configUSE_TRACE_FACILITY 0#define configUSE_16_BIT_TICKS 0#define configIDLE_SHOULD_YIELD 1#define configUSE_MUTEXES 1#define configQUEUE_REGISTRY_SIZE 0#define configCHECK_FOR_STACK_OVERFLOW 0#define configUSE_RECURSIVE_MUTEXES 1#define configUSE_MALLOC_FAILED_HOOK 1#define configUSE_APPLICATION_TASK_TAG 0#define configUSE_COUNTING_SEMAPHORES 1#define configGENERATE_RUN_TIME_STATS 0/* Co-routine definitions. */#define configUSE_CO_ROUTINES 0#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )/* Software timer definitions. */#define configUSE_TIMERS 1#define configTIMER_TASK_PRIORITY ( 2 )#define configTIMER_QUEUE_LENGTH 5#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 )/* Set the following definitions to 1 to include the API function, or zeroto exclude the API function. */#define INCLUDE_vTaskPrioritySet 1#define INCLUDE_uxTaskPriorityGet 1#define INCLUDE_vTaskDelete 1#define INCLUDE_vTaskCleanUpResources 1#define INCLUDE_vTaskSuspend 1#define INCLUDE_vTaskDelayUntil 1#define INCLUDE_vTaskDelay 1/* Cortex-M specific definitions. */#ifdef __NVIC_PRIO_BITS/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */#define configPRIO_BITS __NVIC_PRIO_BITS#else#define configPRIO_BITS 4 /* 15 priority levels */#endif/* The lowest interrupt priority that can be used in a call to a "set priority"function. */#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x0f/* The highest interrupt priority that can be used by any interrupt serviceroutine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALLINTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHERPRIORITY THAN THIS! (higher priorities are lower numeric values. */#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 10/* Interrupt priorities used by the kernel port layer itself. These are genericto all Cortex-M ports, and do not rely on any particular library functions. */#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )/* Normal assert() semantics without relying on the provision of an assert.hheader file. */#define configASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); }/* Definitions that map the FreeRTOS port interrupt handlers to their CMSISstandard names. */#define vPortSVCHandler SVC_Handler#define xPortPendSVHandler PendSV_Handler#define xPortSysTickHandler SysTick_Handler#endif /* FREERTOS_CONFIG_H */
123version https://git-lfs.github.com/spec/v1oid sha256:e0fea2e8ac8f844e6c87cfb984bb407a8e0306b40444318a834f8be2a22357besize 5073123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*/#ifndef SERIAL_COMMS_H#define SERIAL_COMMS_Htypedef void * xComPortHandle;typedef enum{serCOM1,serCOM2,serCOM3,serCOM4,serCOM5,serCOM6,serCOM7,serCOM8} eCOMPort;typedef enum{serNO_PARITY,serODD_PARITY,serEVEN_PARITY,serMARK_PARITY,serSPACE_PARITY} eParity;typedef enum{serSTOP_1,serSTOP_2} eStopBits;typedef enum{serBITS_5,serBITS_6,serBITS_7,serBITS_8} eDataBits;typedef enum{ser50,ser75,ser110,ser134,ser150,ser200,ser300,ser600,ser1200,ser1800,ser2400,ser4800,ser9600,ser19200,ser38400,ser57600,ser115200} eBaud;xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, unsigned portBASE_TYPE uxQueueLength );xComPortHandle xSerialPortInit( eCOMPort ePort, eBaud eWantedBaud, eParity eWantedParity, eDataBits eWantedDataBits, eStopBits eWantedStopBits, unsigned portBASE_TYPE uxBufferLength );void vSerialPutString( xComPortHandle pxPort, const signed char * const pcString, unsigned short usStringLength );signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, signed char *pcRxedChar, portTickType xBlockTime );signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, portTickType xBlockTime );portBASE_TYPE xSerialWaitForSemaphore( xComPortHandle xPort );void vSerialClose( xComPortHandle xPort );#endif
123version https://git-lfs.github.com/spec/v1oid sha256:06b3c9fd5cbf5f68f19d6d0ca453227daae9ebf38b392d005ea11ea0f0bab346size 8680123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234/******************************************************************************* This project provides two demo applications. A simple blinky style project,* and a more comprehensive test and demo application. The* mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting (defined in this file) is used to* select between the two. The simply blinky demo is implemented and described* in main_blinky.c. The more comprehensive test and demo application is* implemented and described in main_full.c.** This file implements the code that is not demo specific, including the* hardware setup and FreeRTOS hook functions.**//* Standard includes. */#include <stdio.h>/* Kernel includes. */#include "FreeRTOS.h"#include "task.h"#include "sam3n4c.h"#include "serial.h"//#include "component_pio.h"/** main_blinky() is used when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1.* main_full() is used when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 0.*///extern void main_blinky( void );//extern void main_full( void );/* Prototypes for the standard FreeRTOS callback/hook functions implemented within this file. */void vApplicationMallocFailedHook( void );void vApplicationIdleHook( void );void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName );void vApplicationTickHook( void );Pio* pioa = (Pio*)0x400E0E00;char led[2] = {0,0};char txbuf[32];char tx_exists = 0;#define BIT(x,b) ((x&b)==b)/*---------------------------------*//* ������ #1 *//*---------------------------------*/void vTaskRx( void *pvParameters ){Usart* usart1 = (Usart*)0x40028000;char ch;char bf[32]; bf[0] = 0;/* ������ ��������� �� ���� ������������ ����� */xComPortHandle serialport = (xComPortHandle)pvParameters;for(;;){if (xSerialGetChar(serialport, &ch, 0xFFFF) != pdTRUE)continue;// while (!BIT(usart1->US_CSR, US_CSR_RXRDY));// ch = usart1->US_RHR;switch (ch){case '1':led[0] = ~led[0];if (led[0])strcpy(txbuf, "\nLED1 On\r\n");elsestrcpy(txbuf, "\nLED1 Off\r\n");tx_exists = 1;break;case '2':led[1] = ~led[1];if (led[1])strcpy(txbuf, "\nLED2 On\r\n");elsestrcpy(txbuf, "\nLED2 Off\r\n");tx_exists = 1;break;}/* �������� �� ��������� ������ �1 */vTaskDelay(10); // T1 = 10 ��������� �����}/* ���������� ������ ���� ��������� ����� �� ������������ ����� */vTaskDelete(NULL);}/*---------------------------------*//* ������ #2 *//*---------------------------------*/void vTaskTx( void *pvParameters ){Usart* usart1 = (Usart*)0x40028000;xComPortHandle serialport = (xComPortHandle)pvParameters;for(;;){if (tx_exists == 1){for (int i=0; txbuf[i]!=0; i++){while (!BIT(usart1->US_CSR, US_CSR_TXRDY));usart1->US_THR = ( uint32_t ) txbuf[i];// xSerialPutChar(serialport, txbuf[i], (portTickType)0);}if (led[0])pioa->PIO_SODR = PIO_SODR_P1;elsepioa->PIO_CODR = PIO_CODR_P1;if (led[1])pioa->PIO_SODR = PIO_SODR_P2;elsepioa->PIO_CODR = PIO_CODR_P2;tx_exists = 0;}/* �������� �� ��������� ������ �2 */vTaskDelay(10); // �2 = 10 ��������� �����}vTaskDelete(NULL);}/*-----------------------------------------------------------*//* See the documentation page for this demo on the FreeRTOS.org web site forfull information - including hardware setup requirements. */int main( void ){/* Prepare the hardware to run this demo. */extern void SystemCoreClockUpdate( void );/* ASF function to setup clocking. */// sysclk_init();pioa->PIO_OER |= PIO_OER_P0 | PIO_OER_P1 | PIO_OER_P2; // output for task1 and task2pioa->PIO_CODR |= PIO_SODR_P0 | PIO_SODR_P1 | PIO_SODR_P2; // PA0,1,2 = 0/* Ensure all priority bits are assigned as preemption priority bits. */NVIC_SetPriorityGrouping( 0 );/* Atmel library function to setup for the evaluation kit being used. */// board_init();xComPortHandle serialport = xSerialPortInitMinimal(9600, 10);strcpy(txbuf, "Type 1 or 2 to change LEDx state!\r");tx_exists = 1;/* ��������� ������ #1. ��� ������ ������� xTaskCreate��������� ������ ��� �� ������������, ���������������� ����������.� ���� ������� �� ������������ �������� �� ���������� �������� ������ */xTaskCreate( vTaskRx, /* ��������� �� ����������� ������� */(signed char *) "TaskRx", /* ��� ������, ����������� ��� ������� FreeRTOS */configMINIMAL_STACK_SIZE, /* ������ ����� ������ */serialport, /* ������������ �������� */1, /* ��������� ������ */NULL ); /* ���������� ������ *//* ��������� ������ #2 */xTaskCreate( vTaskTx, /* ��������� �� ����������� ������� */(signed char * ) "TaskTx", /* ��� ������, ����������� ��� ������� FreeRTOS */configMINIMAL_STACK_SIZE, /* ������ ����� ������ */serialport, /* ������������ �������� */1, /* ��������� ������ */NULL ); /* ���������� ������ *//* ��������� �����������. � ����� ����� ������ �������� ��� ��������� ����� ������.����������� ������ ��������� ������ ������ � ����� ������� �����������.���� ������� ��������� ����� � ������������ �����������, �� ��� ����� �������� ���������.��� ���������� ������ FreeRTOS, ����������� ������ �������� �����.*/vTaskStartScheduler();return 0;}/*-----------------------------------------------------------*/void vApplicationMallocFailedHook( void ){/* vApplicationMallocFailedHook() will only be called ifconfigUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hookfunction that will get called if a call to pvPortMalloc() fails.pvPortMalloc() is called internally by the kernel whenever a task, queue,timer or semaphore is created. It is also called by various parts of thedemo application. If heap_1.c or heap_2.c are used, then the size of theheap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE inFreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be usedto query the size of free heap space that remains (although it does notprovide information on how the remaining heap might be fragmented). */taskDISABLE_INTERRUPTS();for( ;; );}/*-----------------------------------------------------------*/void vApplicationIdleHook( void ){/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is setto 1 in FreeRTOSConfig.h. It will be called on each iteration of the idletask. It is essential that code added to this hook function never attemptsto block in any way (for example, call xQueueReceive() with a block timespecified, or call vTaskDelay()). If the application makes use of thevTaskDelete() API function (as this demo application does) then it is alsoimportant that vApplicationIdleHook() is permitted to return to its callingfunction, because it is the responsibility of the idle task to clean upmemory allocated by the kernel to any task that has since been deleted. */}/*-----------------------------------------------------------*/void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName ){( void ) pcTaskName;( void ) pxTask;/* Run time stack overflow checking is performed ifconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hookfunction is called if a stack overflow is detected. */taskDISABLE_INTERRUPTS();for( ;; );}/*-----------------------------------------------------------*/void vApplicationTickHook( void ){/* This function will be called by each tick interrupt ifconfigUSE_TICK_HOOK is set to 1 in FreeRTOSConfig.h. User code can beadded here, but the tick hook is called from an interrupt context, socode must not attempt to block, and only the interrupt safe FreeRTOS APIfunctions can be used (those that end in FromISR()). */}/*-----------------------------------------------------------*/
123version https://git-lfs.github.com/spec/v1oid sha256:e80f1a43c5999dbf88a5d635aff816917809113afbc89c39daaef62d0f4632a5size 11705123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317/*FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.All rights reservedVISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.**************************************************************************** ** FreeRTOS provides completely free yet professionally developed, ** robust, strictly quality controlled, supported, and cross ** platform software that has become a de facto standard. ** ** Help yourself get started quickly and support the FreeRTOS ** project by purchasing a FreeRTOS tutorial book, reference ** manual, or both from: http://www.FreeRTOS.org/Documentation ** ** Thank you! ** ****************************************************************************This file is part of the FreeRTOS distribution.FreeRTOS is free software; you can redistribute it and/or modify it underthe terms of the GNU General Public License (version 2) as published by theFree Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.>>! NOTE: The modification to the GPL is included to allow you to distribute>>! a combined work that includes FreeRTOS without being obliged to provide>>! the source code for proprietary components outside of the FreeRTOS>>! kernel.FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESSFOR A PARTICULAR PURPOSE. Full license text is available from the followinglink: http://www.freertos.org/a00114.html1 tab == 4 spaces!**************************************************************************** ** Having a problem? Start by reading the FAQ "My application does ** not run, what could be wrong?" ** ** http://www.FreeRTOS.org/FAQHelp.html ** ****************************************************************************http://www.FreeRTOS.org - Documentation, books, training, latest versions,license and Real Time Engineers Ltd. contact details.http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,including FreeRTOS+Trace - an indispensable productivity tool, a DOScompatible FAT file system, and our tiny thread aware UDP/IP stack.http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to HighIntegrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOSlicenses offer ticketed support, indemnification and middleware.http://www.SafeRTOS.com - High Integrity Systems also provide a safetyengineered and independently SIL3 certified version for use in safety andmission critical applications that require provable dependability.1 tab == 4 spaces!*//*BASIC INTERRUPT DRIVEN SERIAL PORT DRIVER FOR USART1.***Note*** This example uses queues to send each character into an interruptservice routine and out of an interrupt service routine individually. Thisis done to demonstrate queues being used in an interrupt, and to deliberatelyload the system to test the FreeRTOS port. It is *NOT* meant to be anexample of an efficient implementation. An efficient implementation shoulduse FIFO's or DMA if available, and only use FreeRTOS API functions whenenough has been received to warrant a task being unblocked to process thedata.*//* Scheduler includes. */#include "FreeRTOS.h"#include "queue.h"#include "sam3n.h"#include "serial.h"/*-----------------------------------------------------------*//** Master clock frequency (when using board_lowlevel.c) */#define MAINCK 4000000 // 4 MHz/* Misc defines. */#define serINVALID_QUEUE ( ( xQueueHandle ) 0 )#define serNO_BLOCK ( ( portTickType ) 0 )#define serPMC_USART_ID ( BOARD_ID_USART )/* The USART supported by this file. */#define serUSART_PORT ( USART1 )#define serUSART_IRQ ( USART1_IRQn )/* Every bit in the interrupt mask. */#define serMASK_ALL_INTERRUPTS ( 0xffffffffUL )#define BIT(x,b) ((x&b)==b)/*-----------------------------------------------------------*//* The queue used to hold received characters. */static xQueueHandle xRxedChars;static xQueueHandle xCharsForTx;/*-----------------------------------------------------------*//** See the serial.h header file.*/xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, unsigned portBASE_TYPE uxQueueLength ){uint32_t ulChar;xComPortHandle xReturn;/* Create the queues used to hold Rx/Tx characters. */xRxedChars = xQueueCreate( uxQueueLength, ( unsigned portBASE_TYPE ) sizeof( signed char ) );xCharsForTx = xQueueCreate( uxQueueLength + 1, ( unsigned portBASE_TYPE ) sizeof( signed char ) );/* If the queues were created correctly then setup the serial porthardware. */if( ( xRxedChars != serINVALID_QUEUE ) && ( xCharsForTx != serINVALID_QUEUE ) ){Usart* usart0 = (Usart*)0x40024000;Usart* usart1 = (Usart*)0x40028000;Pmc* pmc = (Pmc*)0x400E0400;Pio* pioa = (Pio*)0x400E0E00;/* Enable usart1 peripheral clock */pmc->PMC_PCER0 = 1 << ID_USART1;/*#define PIO_PA25A_CTS1#define PIO_PA24A_RTS1#define PIO_PA21A_RXD1#define PIO_PA23A_SCK1#define PIO_PA22A_TXD1*/uint32_t abcdsr;uint32_t pin_mask = PIO_PA21A_RXD1 | PIO_PA22A_TXD1;pioa->PIO_IDR = pin_mask;pioa->PIO_PUDR = pin_mask;abcdsr = pioa->PIO_ABCDSR[0];pioa->PIO_ABCDSR[0] &= (~pin_mask & abcdsr);abcdsr = pioa->PIO_ABCDSR[1];pioa->PIO_ABCDSR[1] &= (~pin_mask & abcdsr);pioa->PIO_PDR = pin_mask;/* Reset and disable receiver & transmitter */usart1->US_CR = US_CR_RSTRX | US_CR_RSTTX| US_CR_RXDIS | US_CR_TXDIS;/* Setup interrupts */usart1->US_IDR = 0xFFFFFF; // All Interrupts Disable/* Configure baudrate *//* Asynchronous, no oversampling*/usart1->US_BRGR = (MAINCK / ulWantedBaud) / 16; // if ulWantedBaud = 9600 => baudrate = 9600/*** Configures USART in normal (serial rs232) mode, asynchronous, 8 bits, 1 stop* bit, no parity, 9600 bauds and enables its transmitter and receiver.*/unsigned int mode = US_MR_USART_MODE_NORMAL| US_MR_USCLKS_MCK| US_MR_CHRL_8_BIT| US_MR_PAR_NO| US_MR_NBSTOP_1_BIT| US_MR_CHMODE_NORMAL;/* Configure mode */usart1->US_MR = mode; // even parity, normal mode/* Disable PDC channel */usart1->US_PTCR = US_PTCR_RXTDIS | US_PTCR_TXTDIS;/* Enable transmitter and receiver */usart1->US_CR = US_CR_TXEN | UART_CR_RXEN;usart1->US_IER = US_IER_RXRDY; // Rx Interrupt Enable/* Configure and enable interrupt of USART. */NVIC_SetPriority( serUSART_IRQ, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY );NVIC_EnableIRQ( serUSART_IRQ );}else{xReturn = ( xComPortHandle ) 0;}/* This demo file only supports a single port but we have to returnsomething to comply with the standard demo header file. */return xReturn;}/*-----------------------------------------------------------*/signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, signed char *pcRxedChar, portTickType xBlockTime ){/* The port handle is not required as this driver only supports one port. */( void ) pxPort;/* Get the next character from the buffer. Return false if no charactersare available, or arrive before xBlockTime expires. */if( xQueueReceive( xRxedChars, pcRxedChar, xBlockTime ) ){return pdTRUE;}else{return pdFALSE;}}/*-----------------------------------------------------------*/void vSerialPutString( xComPortHandle pxPort, const signed char * const pcString, unsigned short usStringLength ){signed char *pxNext;/* A couple of parameters that this port does not use. */( void ) usStringLength;( void ) pxPort;/* NOTE: This implementation does not handle the queue being full as no block time is used! *//* The port handle is not required as this driver only supports USART1. */( void ) pxPort;/* Send each character in the string, one at a time. */pxNext = ( signed char * ) pcString;while( *pxNext ){xSerialPutChar( pxPort, *pxNext, serNO_BLOCK );pxNext++;}}/*-----------------------------------------------------------*/signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, portTickType xBlockTime ){signed portBASE_TYPE xReturn;/* This simple example only supports one port. */( void ) pxPort;Usart* usart0 = (Usart*)0x40024000;Usart* usart1 = (Usart*)0x40028000;if( xQueueSend( xCharsForTx, &cOutChar, xBlockTime ) == pdPASS ){xReturn = pdPASS;/* Setup interrupts */usart1->US_IER = US_IER_TXRDY;}else{xReturn = pdFAIL;}return xReturn;}/*-----------------------------------------------------------*/void vSerialClose( xComPortHandle xPort ){/* Not supported as not required by the demo application. */( void ) xPort;}/*-----------------------------------------------------------*//** It should be noted that the com test tasks (which use make use of this file)* are included to demonstrate queues being used to communicate between tasks* and interrupts, and to demonstrate a context switch being performed from* inside an interrupt service routine. The serial driver used here is *not** intended to represent an efficient implementation. Real applications should* make use of the USARTS peripheral DMA channel (PDC).*/void USART1_Handler( void ){portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;uint8_t ucChar;uint32_t ulChar;uint32_t ulUSARTStatus, ulUSARTMask;Usart* usart0 = (Usart*)0x40024000;Usart* usart1 = (Usart*)0x40028000;ulUSARTStatus = usart1->US_CSR;if(BIT(ulUSARTStatus, US_CSR_RXRDY)){/* A character has been received on the USART, send it to the Rx handler task. */ulChar = usart1->US_RHR;ucChar = ( uint8_t ) ( ulChar & 0xffUL );xQueueSendFromISR( xRxedChars, &ucChar, &xHigherPriorityTaskWoken );}/* If sending or receiving from a queue has caused a task to unblock, andthe unblocked task has a priority equal to or higher than the currentlyrunning task (the task this ISR interrupted), then xHigherPriorityTaskWokenwill have automatically been set to pdTRUE within the queue send or receivefunction. portEND_SWITCHING_ISR() will then ensure that this ISR returnsdirectly to the higher priority unblocked task. */portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );}
123version https://git-lfs.github.com/spec/v1oid sha256:fa42e34af5075b39a7e9c5e9d78a52045f1cc67174feba804cd52888c4dcbe07size 28312345678910111213/* Customer-specific DLib configuration. *//* Copyright (C) 2003 IAR Systems. All rights reserved. */#ifndef _DLIB_CONFIG_H#define _DLIB_CONFIG_H#ifndef _SYSTEM_BUILD#pragma system_include#endif/* No changes to the defaults. */#endif /* _DLIB_CONFIG_H */
123version https://git-lfs.github.com/spec/v1oid sha256:97ae031eb517f64ff0e65597aaf0ae14f43a33891b593a940fa5f599a699789dsize 35715123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979//*****************************************************************************//// adc.c - Driver for the ADC.//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup adc_api//! @{////*****************************************************************************#include "../inc/hw_adc.h"#include "../inc/hw_ints.h"#include "../inc/hw_memmap.h"#include "../inc/hw_types.h"#include "../driverlib/adc.h"#include "../driverlib/debug.h"#include "../driverlib/interrupt.h"//*****************************************************************************//// These defines are used by the ADC driver to simplify access to the ADC// sequencer's registers.////*****************************************************************************#define ADC_SEQ (ADC_O_SSMUX0)#define ADC_SEQ_STEP (ADC_O_SSMUX1 - ADC_O_SSMUX0)#define ADC_SSMUX (ADC_O_SSMUX0 - ADC_O_SSMUX0)#define ADC_SSCTL (ADC_O_SSCTL0 - ADC_O_SSMUX0)#define ADC_SSFIFO (ADC_O_SSFIFO0 - ADC_O_SSMUX0)#define ADC_SSFSTAT (ADC_O_SSFSTAT0 - ADC_O_SSMUX0)//*****************************************************************************//// The currently configured software oversampling factor for each of the ADC// sequencers.////*****************************************************************************static unsigned char g_pucOversampleFactor[3];//*****************************************************************************////! Registers an interrupt handler for an ADC interrupt.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param pfnHandler is a pointer to the function to be called when the//! ADC sample sequence interrupt occurs.//!//! This function sets the handler to be called when a sample sequence//! interrupt occurs. This will enable the global interrupt in the interrupt//! controller; the sequence interrupt must be enabled with ADCIntEnable(). It//! is the interrupt handler's responsibility to clear the interrupt source via//! ADCIntClear().//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidADCIntRegister(unsigned long ulBase, unsigned long ulSequenceNum,void (*pfnHandler)(void)){unsigned long ulInt;//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Determine the interrupt to register based on the sequence number.//ulInt = INT_ADC0 + ulSequenceNum;//// Register the interrupt handler.//IntRegister(ulInt, pfnHandler);//// Enable the timer interrupt.//IntEnable(ulInt);}//*****************************************************************************////! Unregisters the interrupt handler for an ADC interrupt.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This function unregisters the interrupt handler. This will disable the//! global interrupt in the interrupt controller; the sequence interrupt must//! be disabled via ADCIntDisable().//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidADCIntUnregister(unsigned long ulBase, unsigned long ulSequenceNum){unsigned long ulInt;//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Determine the interrupt to unregister based on the sequence number.//ulInt = INT_ADC0 + ulSequenceNum;//// Disable the interrupt.//IntDisable(ulInt);//// Unregister the interrupt handler.//IntUnregister(ulInt);}//*****************************************************************************////! Disables a sample sequence interrupt.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This function disables the requested sample sequence interrupt.//!//! \return None.////*****************************************************************************voidADCIntDisable(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Disable this sample sequence interrupt.//HWREG(ulBase + ADC_O_IM) &= ~(1 << ulSequenceNum);}//*****************************************************************************////! Enables a sample sequence interrupt.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This function enables the requested sample sequence interrupt. Any//! outstanding interrupts are cleared before enabling the sample sequence//! interrupt.//!//! \return None.////*****************************************************************************voidADCIntEnable(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Clear any outstanding interrupts on this sample sequence.//HWREG(ulBase + ADC_O_ISC) = 1 << ulSequenceNum;//// Enable this sample sequence interrupt.//HWREG(ulBase + ADC_O_IM) |= 1 << ulSequenceNum;}//*****************************************************************************////! Gets the current interrupt status.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param bMasked is false if the raw interrupt status is required and true if//! the masked interrupt status is required.//!//! This returns the interrupt status for the specified sample sequence.//! Either the raw interrupt status or the status of interrupts that are//! allowed to reflect to the processor can be returned.//!//! \return The current raw or masked interrupt status.////*****************************************************************************unsigned longADCIntStatus(unsigned long ulBase, unsigned long ulSequenceNum,tBoolean bMasked){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Return either the interrupt status or the raw interrupt status as// requested.//if(bMasked){return(HWREG(ulBase + ADC_O_ISC) & (1 << ulSequenceNum));}else{return(HWREG(ulBase + ADC_O_RIS) & (1 << ulSequenceNum));}}//*****************************************************************************////! Clears sample sequence interrupt source.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! The specified sample sequence interrupt is cleared, so that it no longer//! asserts. This must be done in the interrupt handler to keep it from being//! called again immediately upon exit.//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidADCIntClear(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arugments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Clear the interrupt.//HWREG(ulBase + ADC_O_ISC) = 1 << ulSequenceNum;}//*****************************************************************************////! Enables a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! Allows the specified sample sequence to be captured when its trigger is//! detected. A sample sequence must be configured before it is enabled.//!//! \return None.////*****************************************************************************voidADCSequenceEnable(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arugments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Enable the specified sequence.//HWREG(ulBase + ADC_O_ACTSS) |= 1 << ulSequenceNum;}//*****************************************************************************////! Disables a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! Prevents the specified sample sequence from being captured when its trigger//! is detected. A sample sequence should be disabled before it is configured.//!//! \return None.////*****************************************************************************voidADCSequenceDisable(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arugments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Disable the specified sequences.//HWREG(ulBase + ADC_O_ACTSS) &= ~(1 << ulSequenceNum);}//*****************************************************************************////! Configures the trigger source and priority of a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param ulTrigger is the trigger source that initiates the sample sequence;//! must be one of the \b ADC_TRIGGER_* values.//! \param ulPriority is the relative priority of the sample sequence with//! respect to the other sample sequences.//!//! This function configures the initiation criteria for a sample sequence.//! Valid sample sequences range from zero to three; sequence zero will capture//! up to eight samples, sequences one and two will capture up to four samples,//! and sequence three will capture a single sample. The trigger condition and//! priority (with respect to other sample sequence execution) is set.//!//! The \e ulTrigger parameter can take on the following values://!//! - \b ADC_TRIGGER_PROCESSOR - A trigger generated by the processor, via the//! ADCProcessorTrigger() function.//! - \b ADC_TRIGGER_COMP0 - A trigger generated by the first analog//! comparator; configured with ComparatorConfigure().//! - \b ADC_TRIGGER_COMP1 - A trigger generated by the second analog//! comparator; configured with ComparatorConfigure().//! - \b ADC_TRIGGER_COMP2 - A trigger generated by the third analog//! comparator; configured with ComparatorConfigure().//! - \b ADC_TRIGGER_EXTERNAL - A trigger generated by an input from the Port//! B4 pin.//! - \b ADC_TRIGGER_TIMER - A trigger generated by a timer; configured with//! TimerControlTrigger().//! - \b ADC_TRIGGER_PWM0 - A trigger generated by the first PWM generator;//! configured with PWMGenIntTrigEnable().//! - \b ADC_TRIGGER_PWM1 - A trigger generated by the second PWM generator;//! configured with PWMGenIntTrigEnable().//! - \b ADC_TRIGGER_PWM2 - A trigger generated by the third PWM generator;//! configured with PWMGenIntTrigEnable().//! - \b ADC_TRIGGER_ALWAYS - A trigger that is always asserted, causing the//! sample sequence to capture repeatedly (so long as//! there is not a higher priority source active).//!//! Note that not all trigger sources are available on all Stellaris family//! members; consult the data sheet for the device in question to determine the//! availability of triggers.//!//! The \e ulPriority parameter is a value between 0 and 3, where 0 represents//! the highest priority and 3 the lowest. Note that when programming the//! priority among a set of sample sequences, each must have unique priority;//! it is up to the caller to guarantee the uniqueness of the priorities.//!//! \return None.////*****************************************************************************voidADCSequenceConfigure(unsigned long ulBase, unsigned long ulSequenceNum,unsigned long ulTrigger, unsigned long ulPriority){//// Check the arugments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);ASSERT((ulTrigger == ADC_TRIGGER_PROCESSOR) ||(ulTrigger == ADC_TRIGGER_COMP0) ||(ulTrigger == ADC_TRIGGER_COMP1) ||(ulTrigger == ADC_TRIGGER_COMP2) ||(ulTrigger == ADC_TRIGGER_EXTERNAL) ||(ulTrigger == ADC_TRIGGER_TIMER) ||(ulTrigger == ADC_TRIGGER_PWM0) ||(ulTrigger == ADC_TRIGGER_PWM1) ||(ulTrigger == ADC_TRIGGER_PWM2) ||(ulTrigger == ADC_TRIGGER_ALWAYS));ASSERT(ulPriority < 4);//// Compute the shift for the bits that control this sample sequence.//ulSequenceNum *= 4;//// Set the trigger event for this sample sequence.//HWREG(ulBase + ADC_O_EMUX) = ((HWREG(ulBase + ADC_O_EMUX) &~(0xf << ulSequenceNum)) |((ulTrigger & 0xf) << ulSequenceNum));//// Set the priority for this sample sequence.//HWREG(ulBase + ADC_O_SSPRI) = ((HWREG(ulBase + ADC_O_SSPRI) &~(0xf << ulSequenceNum)) |((ulPriority & 0x3) << ulSequenceNum));}//*****************************************************************************////! Configure a step of the sample sequencer.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param ulStep is the step to be configured.//! \param ulConfig is the configuration of this step; must be a logical OR of//! \b ADC_CTL_TS, \b ADC_CTL_IE, \b ADC_CTL_END, \b ADC_CTL_D, and one of the//! input channel selects (\b ADC_CTL_CH0 through \b ADC_CTL_CH7).//!//! This function will set the configuration of the ADC for one step of a//! sample sequence. The ADC can be configured for single-ended or//! differential operation (the \b ADC_CTL_D bit selects differential//! operation when set), the channel to be sampled can be chosen (the//! \b ADC_CTL_CH0 through \b ADC_CTL_CH7 values), and the internal temperature//! sensor can be selected (the \b ADC_CTL_TS bit). Additionally, this step//! can be defined as the last in the sequence (the \b ADC_CTL_END bit) and it//! can be configured to cause an interrupt when the step is complete (the//! \b ADC_CTL_IE bit). The configuration is used by the ADC at the//! appropriate time when the trigger for this sequence occurs.//!//! The \e ulStep parameter determines the order in which the samples are//! captured by the ADC when the trigger occurs. It can range from zero to//! seven for the first sample sequence, from zero to three for the second and//! third sample sequence, and can only be zero for the fourth sample sequence.//!//! Differential mode only works with adjacent channel pairs (for example, 0//! and 1). The channel select must be the number of the channel pair to//! sample (for example, \b ADC_CTL_CH0 for 0 and 1, or \b ADC_CTL_CH1 for 2//! and 3) or undefined results will be returned by the ADC. Additionally, if//! differential mode is selected when the temperature sensor is being sampled,//! undefined results will be returned by the ADC.//!//! It is the responsibility of the caller to ensure that a valid configuration//! is specified; this function does not check the validity of the specified//! configuration.//!//! \return None.////*****************************************************************************voidADCSequenceStepConfigure(unsigned long ulBase, unsigned long ulSequenceNum,unsigned long ulStep, unsigned long ulConfig){//// Check the arugments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);ASSERT(((ulSequenceNum == 0) && (ulStep < 8)) ||((ulSequenceNum == 1) && (ulStep < 4)) ||((ulSequenceNum == 2) && (ulStep < 4)) ||((ulSequenceNum == 3) && (ulStep < 1)));//// Get the offset of the sequence to be configured.//ulBase += ADC_SEQ + (ADC_SEQ_STEP * ulSequenceNum);//// Compute the shift for the bits that control this step.//ulStep *= 4;//// Set the analog mux value for this step.//HWREG(ulBase + ADC_SSMUX) = ((HWREG(ulBase + ADC_SSMUX) &~(0x0000000f << ulStep)) |((ulConfig & 0x0f) << ulStep));//// Set the control value for this step.//HWREG(ulBase + ADC_SSCTL) = ((HWREG(ulBase + ADC_SSCTL) &~(0x0000000f << ulStep)) |(((ulConfig & 0xf0) >> 4) << ulStep));}//*****************************************************************************////! Determines if a sample sequence overflow occurred.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This determines if a sample sequence overflow has occurred. This will//! happen if the captured samples are not read from the FIFO before the next//! trigger occurs.//!//! \return Returns zero if there was not an overflow, and non-zero if there//! was.////*****************************************************************************longADCSequenceOverflow(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Determine if there was an overflow on this sequence.//return(HWREG(ulBase + ADC_O_OSTAT) & (1 << ulSequenceNum));}//*****************************************************************************////! Clears the overflow condition on a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This will clear an overflow condition on one of the sample sequences. The//! overflow condition must be cleared in order to detect a subsequent overflow//! condition (it otherwise causes no harm).//!//! \return None.////*****************************************************************************voidADCSequenceOverflowClear(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Clear the overflow condition for this sequence.//HWREG(ulBase + ADC_O_OSTAT) = 1 << ulSequenceNum;}//*****************************************************************************////! Determines if a sample sequence underflow occurred.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This determines if a sample sequence underflow has occurred. This will//! happen if too many samples are read from the FIFO.//!//! \return Returns zero if there was not an underflow, and non-zero if there//! was.////*****************************************************************************longADCSequenceUnderflow(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Determine if there was an underflow on this sequence.//return(HWREG(ulBase + ADC_O_USTAT) & (1 << ulSequenceNum));}//*****************************************************************************////! Clears the underflow condition on a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This will clear an underflow condition on one of the sample sequences. The//! underflow condition must be cleared in order to detect a subsequent//! underflow condition (it otherwise causes no harm).//!//! \return None.////*****************************************************************************voidADCSequenceUnderflowClear(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Clear the underflow condition for this sequence.//HWREG(ulBase + ADC_O_USTAT) = 1 << ulSequenceNum;}//*****************************************************************************////! Gets the captured data for a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param pulBuffer is the address where the data is stored.//!//! This function copies data from the specified sample sequence output FIFO to//! a memory resident buffer. The number of samples available in the hardware//! FIFO are copied into the buffer, which is assumed to be large enough to//! hold that many samples. This will only return the samples that are//! presently available, which may not be the entire sample sequence if it is//! in the process of being executed.//!//! \return Returns the number of samples copied to the buffer.////*****************************************************************************longADCSequenceDataGet(unsigned long ulBase, unsigned long ulSequenceNum,unsigned long *pulBuffer){unsigned long ulCount;//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Get the offset of the sequence to be read.//ulBase += ADC_SEQ + (ADC_SEQ_STEP * ulSequenceNum);//// Read samples from the FIFO until it is empty.//ulCount = 0;while(!(HWREG(ulBase + ADC_SSFSTAT) & ADC_SSFSTAT0_EMPTY) && (ulCount < 8)){//// Read the FIFO and copy it to the destination.//*pulBuffer++ = HWREG(ulBase + ADC_SSFIFO);//// Increment the count of samples read.//ulCount++;}//// Return the number of samples read.//return(ulCount);}//*****************************************************************************////! Causes a processor trigger for a sample sequence.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//!//! This function triggers a processor-initiated sample sequence if the sample//! sequence trigger is configured to \b ADC_TRIGGER_PROCESSOR.//!//! \return None.////*****************************************************************************voidADCProcessorTrigger(unsigned long ulBase, unsigned long ulSequenceNum){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 4);//// Generate a processor trigger for this sample sequence.//HWREG(ulBase + ADC_O_PSSI) = 1 << ulSequenceNum;}//*****************************************************************************////! Configures the software oversampling factor of the ADC.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param ulFactor is the number of samples to be averaged.//!//! This function configures the software oversampling for the ADC, which can//! be used to provide better resolution on the sampled data. Oversampling is//! accomplished by averaging multiple samples from the same analog input.//! Three different oversampling rates are supported; 2x, 4x, and 8x.//!//! Oversampling is only supported on the sample sequencers that are more than//! one sample in depth (that is, the fourth sample sequencer is not//! supported). Oversampling by 2x (for example) divides the depth of the//! sample sequencer by two; so 2x oversampling on the first sample sequencer//! can only provide four samples per trigger. This also means that 8x//! oversampling is only available on the first sample sequencer.//!//! \return None.////*****************************************************************************voidADCSoftwareOversampleConfigure(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long ulFactor){unsigned long ulValue;//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 3);ASSERT(((ulFactor == 2) || (ulFactor == 4) || (ulFactor == 8)) &&((ulSequenceNum == 0) || (ulFactor != 8)));//// Convert the oversampling factor to a shift factor.//for(ulValue = 0, ulFactor >>= 1; ulFactor; ulValue++, ulFactor >>= 1){}//// Save the sfiht factor.//g_pucOversampleFactor[ulSequenceNum] = ulValue;}//*****************************************************************************////! Configures a step of the software oversampled sequencer.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param ulStep is the step to be configured.//! \param ulConfig is the configuration of this step.//!//! This function configures a step of the sample sequencer when using the//! software oversampling feature. The number of steps available depends on//! the oversampling factor set by ADCSoftwareOversampleConfigure(). The value//! of \e ulConfig is the same as defined for ADCSequenceStepConfigure().//!//! \return None.////*****************************************************************************voidADCSoftwareOversampleStepConfigure(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long ulStep,unsigned long ulConfig){//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 3);ASSERT(((ulSequenceNum == 0) &&(ulStep < (8 >> g_pucOversampleFactor[ulSequenceNum]))) ||(ulStep < (4 >> g_pucOversampleFactor[ulSequenceNum])));//// Get the offset of the sequence to be configured.//ulBase += ADC_SEQ + (ADC_SEQ_STEP * ulSequenceNum);//// Compute the shift for the bits that control this step.//ulStep *= 4 << g_pucOversampleFactor[ulSequenceNum];//// Loop through the hardware steps that make up this step of the software// oversampled sequence.//for(ulSequenceNum = 1 << g_pucOversampleFactor[ulSequenceNum];ulSequenceNum; ulSequenceNum--){//// Set the analog mux value for this step.//HWREG(ulBase + ADC_SSMUX) = ((HWREG(ulBase + ADC_SSMUX) &~(0x0000000f << ulStep)) |((ulConfig & 0x0f) << ulStep));//// Set the control value for this step.//HWREG(ulBase + ADC_SSCTL) = ((HWREG(ulBase + ADC_SSCTL) &~(0x0000000f << ulStep)) |(((ulConfig & 0xf0) >> 4) << ulStep));if(ulSequenceNum != 1){HWREG(ulBase + ADC_SSCTL) &= ~((ADC_SSCTL0_IE0 |ADC_SSCTL0_END0) << ulStep);}//// Go to the next hardware step.//ulStep += 4;}}//*****************************************************************************////! Gets the captured data for a sample sequence using software oversampling.//!//! \param ulBase is the base address of the ADC module.//! \param ulSequenceNum is the sample sequence number.//! \param pulBuffer is the address where the data is stored.//! \param ulCount is the number of samples to be read.//!//! This function copies data from the specified sample sequence output FIFO to//! a memory resident buffer with software oversampling applied. The requested//! number of samples are copied into the data buffer; if there are not enough//! samples in the hardware FIFO to satisfy this many oversampled data items//! then incorrect results will be returned. It is the caller's responsibility//! to read only the samples that are available and wait until enough data is//! available, for example as a result of receiving an interrupt.//!//! \return None.////*****************************************************************************voidADCSoftwareOversampleDataGet(unsigned long ulBase, unsigned long ulSequenceNum,unsigned long *pulBuffer, unsigned long ulCount){unsigned long ulIdx, ulAccum;//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(ulSequenceNum < 3);ASSERT(((ulSequenceNum == 0) &&(ulCount < (8 >> g_pucOversampleFactor[ulSequenceNum]))) ||(ulCount < (4 >> g_pucOversampleFactor[ulSequenceNum])));//// Get the offset of the sequence to be read.//ulBase += ADC_SEQ + (ADC_SEQ_STEP * ulSequenceNum);//// Read the samples from the FIFO until it is empty.//while(ulCount--){//// Compute the sum of the samples.//ulAccum = 0;for(ulIdx = 1 << g_pucOversampleFactor[ulSequenceNum]; ulIdx; ulIdx--){//// Read the FIFO and add it to the accumulator.//ulAccum += HWREG(ulBase + ADC_SSFIFO);}//// Write the averaged sample to the output buffer.//*pulBuffer++ = ulAccum >> g_pucOversampleFactor[ulSequenceNum];}}//*****************************************************************************////! Configures the hardware oversampling factor of the ADC.//!//! \param ulBase is the base address of the ADC module.//! \param ulFactor is the number of samples to be averaged.//!//! This function configures the hardware oversampling for the ADC, which can//! be used to provide better resolution on the sampled data. Oversampling is//! accomplished by averaging multiple samples from the same analog input. Six//! different oversampling rates are supported; 2x, 4x, 8x, 16x, 32x, and 64x.//! Specifying an oversampling factor of zero will disable hardware//! oversampling.//!//! Hardware oversampling applies uniformly to all sample sequencers. It does//! not reduce the depth of the sample sequencers like the software//! oversampling APIs; each sample written into the sample sequence FIFO is a//! fully oversampled analog input reading.//!//! Enabling hardware averaging increases the precision of the ADC at the cost//! of throughput. For example, enabling 4x oversampling reduces the//! throughput of a 250 Ksps ADC to 62.5 Ksps.//!//! \note Hardware oversampling is available beginning with Rev C0 of the//! Stellaris microcontroller.//!//! \return None.////*****************************************************************************voidADCHardwareOversampleConfigure(unsigned long ulBase, unsigned long ulFactor){unsigned long ulValue;//// Check the arguments.//ASSERT((ulBase == ADC0_BASE) || (ulBase == ADC1_BASE));ASSERT(((ulFactor == 0) || (ulFactor == 2) || (ulFactor == 4) ||(ulFactor == 8) || (ulFactor == 16) || (ulFactor == 32) ||(ulFactor == 64)));//// Convert the oversampling factor to a shift factor.//for(ulValue = 0, ulFactor >>= 1; ulFactor; ulValue++, ulFactor >>= 1){}//// Write the shift factor to the ADC to configure the hardware oversampler.//HWREG(ulBase + ADC_O_SAC) = ulValue;}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:58fa1379b06889985440d22d4062ee37f5eebdacda514935f4f0b610fe1035a6size 7771123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149//*****************************************************************************//// adc.h - ADC headers for using the ADC driver functions.//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __ADC_H__#define __ADC_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Values that can be passed to ADCSequenceConfigure as the ulTrigger// parameter.////*****************************************************************************#define ADC_TRIGGER_PROCESSOR 0x00000000 // Processor event#define ADC_TRIGGER_COMP0 0x00000001 // Analog comparator 0 event#define ADC_TRIGGER_COMP1 0x00000002 // Analog comparator 1 event#define ADC_TRIGGER_COMP2 0x00000003 // Analog comparator 2 event#define ADC_TRIGGER_EXTERNAL 0x00000004 // External event#define ADC_TRIGGER_TIMER 0x00000005 // Timer event#define ADC_TRIGGER_PWM0 0x00000006 // PWM0 event#define ADC_TRIGGER_PWM1 0x00000007 // PWM1 event#define ADC_TRIGGER_PWM2 0x00000008 // PWM2 event#define ADC_TRIGGER_ALWAYS 0x0000000F // Always event//*****************************************************************************//// Values that can be passed to ADCSequenceStepConfigure as the ulConfig// parameter.////*****************************************************************************#define ADC_CTL_TS 0x00000080 // Temperature sensor select#define ADC_CTL_IE 0x00000040 // Interrupt enable#define ADC_CTL_END 0x00000020 // Sequence end select#define ADC_CTL_D 0x00000010 // Differential select#define ADC_CTL_CH0 0x00000000 // Input channel 0#define ADC_CTL_CH1 0x00000001 // Input channel 1#define ADC_CTL_CH2 0x00000002 // Input channel 2#define ADC_CTL_CH3 0x00000003 // Input channel 3#define ADC_CTL_CH4 0x00000004 // Input channel 4#define ADC_CTL_CH5 0x00000005 // Input channel 5#define ADC_CTL_CH6 0x00000006 // Input channel 6#define ADC_CTL_CH7 0x00000007 // Input channel 7#define ADC_CTL_CH8 0x00000008 // Input channel 8#define ADC_CTL_CH9 0x00000009 // Input channel 9#define ADC_CTL_CH10 0x0000000A // Input channel 10#define ADC_CTL_CH11 0x0000000B // Input channel 11#define ADC_CTL_CH12 0x0000000C // Input channel 12#define ADC_CTL_CH13 0x0000000D // Input channel 13#define ADC_CTL_CH14 0x0000000E // Input channel 14#define ADC_CTL_CH15 0x0000000F // Input channel 15//*****************************************************************************//// Prototypes for the APIs.////*****************************************************************************extern void ADCIntRegister(unsigned long ulBase, unsigned long ulSequenceNum,void (*pfnHandler)(void));extern void ADCIntUnregister(unsigned long ulBase,unsigned long ulSequenceNum);extern void ADCIntDisable(unsigned long ulBase, unsigned long ulSequenceNum);extern void ADCIntEnable(unsigned long ulBase, unsigned long ulSequenceNum);extern unsigned long ADCIntStatus(unsigned long ulBase,unsigned long ulSequenceNum,tBoolean bMasked);extern void ADCIntClear(unsigned long ulBase, unsigned long ulSequenceNum);extern void ADCSequenceEnable(unsigned long ulBase,unsigned long ulSequenceNum);extern void ADCSequenceDisable(unsigned long ulBase,unsigned long ulSequenceNum);extern void ADCSequenceConfigure(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long ulTrigger,unsigned long ulPriority);extern void ADCSequenceStepConfigure(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long ulStep,unsigned long ulConfig);extern long ADCSequenceOverflow(unsigned long ulBase,unsigned long ulSequenceNum);extern void ADCSequenceOverflowClear(unsigned long ulBase,unsigned long ulSequenceNum);extern long ADCSequenceUnderflow(unsigned long ulBase,unsigned long ulSequenceNum);extern void ADCSequenceUnderflowClear(unsigned long ulBase,unsigned long ulSequenceNum);extern long ADCSequenceDataGet(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long *pulBuffer);extern void ADCProcessorTrigger(unsigned long ulBase,unsigned long ulSequenceNum);extern void ADCSoftwareOversampleConfigure(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long ulFactor);extern void ADCSoftwareOversampleStepConfigure(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long ulStep,unsigned long ulConfig);extern void ADCSoftwareOversampleDataGet(unsigned long ulBase,unsigned long ulSequenceNum,unsigned long *pulBuffer,unsigned long ulCount);extern void ADCHardwareOversampleConfigure(unsigned long ulBase,unsigned long ulFactor);//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __ADC_H__
123version https://git-lfs.github.com/spec/v1oid sha256:26c2dd03db69af5be5173243ab5a056be1c002d618690cc5c91fbfb6d06def56size 728961234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203//*****************************************************************************//// can.c - Driver for the CAN module.//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup can_api//! @{////*****************************************************************************#include "inc/hw_can.h"#include "inc/hw_ints.h"#include "inc/hw_nvic.h"#include "inc/hw_memmap.h"#include "inc/hw_types.h"#include "driverlib/can.h"#include "driverlib/debug.h"#include "driverlib/interrupt.h"//*****************************************************************************//// This is the maximum number that can be stored as an 11bit Message// identifier.////*****************************************************************************#define CAN_MAX_11BIT_MSG_ID (0x7ff)//*****************************************************************************//// This is used as the loop delay for accessing the CAN controller registers.////*****************************************************************************#define CAN_RW_DELAY (5)//// The maximum CAN bit timing divisor is 13.//#define CAN_MAX_BIT_DIVISOR (13)//// The minimum CAN bit timing divisor is 5.//#define CAN_MIN_BIT_DIVISOR (5)//// The maximum CAN pre-divisor is 1024.//#define CAN_MAX_PRE_DIVISOR (1024)//// The minimum CAN pre-divisor is 1024.//#define CAN_MIN_PRE_DIVISOR (1024)//*****************************************************************************//// This table is used by the CANBitRateSet() API as the register defaults for// the bit timing values.////*****************************************************************************static const unsigned short g_usCANBitValues[] ={0x1100, // TSEG2 2, TSEG1 2, SJW 1, Divide 50x1200, // TSEG2 2, TSEG1 3, SJW 1, Divide 60x2240, // TSEG2 3, TSEG1 3, SJW 2, Divide 70x2340, // TSEG2 3, TSEG1 4, SJW 2, Divide 80x3340, // TSEG2 4, TSEG1 4, SJW 2, Divide 90x3440, // TSEG2 4, TSEG1 5, SJW 2, Divide 100x3540, // TSEG2 4, TSEG1 6, SJW 2, Divide 110x3640, // TSEG2 4, TSEG1 7, SJW 2, Divide 120x3740 // TSEG2 4, TSEG1 8, SJW 2, Divide 13};//*****************************************************************************////! \internal//! Checks a CAN base address.//!//! \param ulBase is the base address of the CAN controller.//!//! This function determines if a CAN controller base address is valid.//!//! \return Returns \b true if the base address is valid and \b false//! otherwise.////*****************************************************************************#ifdef DEBUGstatic tBooleanCANBaseValid(unsigned long ulBase){return((ulBase == CAN0_BASE) || (ulBase == CAN1_BASE) ||(ulBase == CAN2_BASE));}#endif//*****************************************************************************////! \internal//!//! Returns the CAN controller interrupt number.//!//! \param ulBase is the base address of the selected CAN controller//!//! Given a CAN controller base address, returns the corresponding interrupt//! number.//!//! This function replaces the original CANGetIntNumber() API and performs the//! same actions. A macro is provided in <tt>can.h</tt> to map the original//! API to this API.//!//! \return Returns a CAN interrupt number, or -1 if \e ulPort is invalid.////*****************************************************************************static longCANIntNumberGet(unsigned long ulBase){long lIntNumber;//// Return the interrupt number for the given CAN controller.//switch(ulBase){//// Return the interrupt number for CAN 0//case CAN0_BASE:{lIntNumber = INT_CAN0;break;}//// Return the interrupt number for CAN 1//case CAN1_BASE:{lIntNumber = INT_CAN1;break;}//// Return the interrupt number for CAN 2//case CAN2_BASE:{lIntNumber = INT_CAN2;break;}//// Return -1 to indicate a bad address was passed in.//default:{lIntNumber = -1;}}return(lIntNumber);}//*****************************************************************************////! \internal//!//! Reads a CAN controller register.//!//! \param ulRegAddress is the full address of the CAN register to be read.//!//! This function performs the necessary synchronization to read from a CAN//! controller register.//!//! This function replaces the original CANReadReg() API and performs the same//! actions. A macro is provided in <tt>can.h</tt> to map the original API to//! this API.//!//! \note This function provides the delay required to access CAN registers.//! This delay is required when accessing CAN registers directly.//!//! \return Returns the value read from the register.////*****************************************************************************static unsigned longCANRegRead(unsigned long ulRegAddress){volatile int iDelay;unsigned long ulRetVal;unsigned long ulIntNumber;unsigned long ulReenableInts;//// Get the CAN interrupt number from the register base address.//ulIntNumber = CANIntNumberGet(ulRegAddress & 0xfffff000);//// Make sure that the CAN base address was valid.//ASSERT(ulIntNumber != (unsigned long)-1);//// Remember current state so that CAN interrupts are only re-enabled if// they were already enabled.//ulReenableInts = HWREG(NVIC_EN1) & (1 << (ulIntNumber - 48));//// If the CAN interrupt was enabled then disable it.//if(ulReenableInts){IntDisable(ulIntNumber);}//// Trigger the inital read to the CAN controller. The value returned at// this point is not valid.//HWREG(ulRegAddress);//// This delay is necessary for the CAN have the correct data on the bus.//for(iDelay = 0; iDelay < CAN_RW_DELAY; iDelay++){}//// Do the final read that has the valid value of the register.//ulRetVal = HWREG(ulRegAddress);//// Reenable CAN interrupts if they were enabled before this call.//if(ulReenableInts){IntEnable(ulIntNumber);}return(ulRetVal);}//*****************************************************************************////! \internal//!//! Writes a CAN controller register.//!//! \param ulRegAddress is the full address of the CAN register to be written.//! \param ulRegValue is the value to write into the register specified by//! \e ulRegAddress.//!//! This function takes care of the synchronization necessary to write to a//! CAN controller register.//!//! This function replaces the original CANWriteReg() API and performs the same//! actions. A macro is provided in <tt>can.h</tt> to map the original API to//! this API.//!//! \note The delays in this function are required when accessing CAN registers//! directly.//!//! \return None.////*****************************************************************************static voidCANRegWrite(unsigned long ulRegAddress, unsigned long ulRegValue){volatile int iDelay;//// Trigger the inital write to the CAN controller. The value will not make// it out to the CAN controller for CAN_RW_DELAY cycles.//HWREG(ulRegAddress) = ulRegValue;//// Delay to allow the CAN controller to receive the new data.//for(iDelay = 0; iDelay < CAN_RW_DELAY; iDelay++){}}//*****************************************************************************////! \internal//!//! Copies data from a buffer to the CAN Data registers.//!//! \param pucData is a pointer to the data to be written out to the CAN//! controller's data registers.//! \param pulRegister is an unsigned long pointer to the first register of the//! CAN controller's data registers. For example, in order to use the IF1//! register set on CAN controller 0, the value would be: \b CAN0_BASE \b +//! \b CAN_O_IF1DA1.//! \param iSize is the number of bytes to copy into the CAN controller.//!//! This function takes the steps necessary to copy data from a contiguous//! buffer in memory into the non-contiguous data registers used by the CAN//! controller. This function is rarely used outside of the CANMessageSet()//! function.//!//! This function replaces the original CANWriteDataReg() API and performs the//! same actions. A macro is provided in <tt>can.h</tt> to map the original//! API to this API.//!//! \return None.////*****************************************************************************static voidCANDataRegWrite(unsigned char *pucData, unsigned long *pulRegister, int iSize){int iIdx;unsigned long ulValue;//// Loop always copies 1 or 2 bytes per iteration.//for(iIdx = 0; iIdx < iSize; ){//// Write out the data 16 bits at a time since this is how the registers// are aligned in memory.//ulValue = pucData[iIdx++];//// Only write the second byte if needed otherwise it will be zero.//if(iIdx < iSize){ulValue |= (pucData[iIdx++] << 8);}CANRegWrite((unsigned long)(pulRegister++), ulValue);}}//*****************************************************************************////! \internal//!//! Copies data from a buffer to the CAN Data registers.//!//! \param pucData is a pointer to the location to store the data read from the//! CAN controller's data registers.//! \param pulRegister is an unsigned long pointer to the first register of the//! CAN controller's data registers. For example, in order to use the IF1//! register set on CAN controller 1, the value would be: \b CAN0_BASE \b +//! \b CAN_O_IF1DA1.//! \param iSize is the number of bytes to copy from the CAN controller.//!//! This function takes the steps necessary to copy data to a contiguous buffer//! in memory from the non-contiguous data registers used by the CAN//! controller. This function is rarely used outside of the CANMessageGet()//! function.//!//! This function replaces the original CANReadDataReg() API and performs the//! same actions. A macro is provided in <tt>can.h</tt> to map the original//! API to this API.//!//! \return None.////*****************************************************************************static voidCANDataRegRead(unsigned char *pucData, unsigned long *pulRegister, int iSize){int iIdx;unsigned long ulValue;//// Loop always copies 1 or 2 bytes per iteration.//for(iIdx = 0; iIdx < iSize; ){//// Read out the data 16 bits at a time since this is how the registers// are aligned in memory.//ulValue = CANRegRead((unsigned long)(pulRegister++));//// Store the first byte.//pucData[iIdx++] = (unsigned char)ulValue;//// Only read the second byte if needed.//if(iIdx < iSize){pucData[iIdx++] = (unsigned char)(ulValue >> 8);}}}//*****************************************************************************////! Initializes the CAN controller after reset.//!//! \param ulBase is the base address of the CAN controller.//!//! After reset, the CAN controller is left in the disabled state. However,//! the memory used for message objects contains undefined values and must be//! cleared prior to enabling the CAN controller the first time. This prevents//! unwanted transmission or reception of data before the message objects are//! configured. This function must be called before enabling the controller//! the first time.//!//! \return None.////*****************************************************************************voidCANInit(unsigned long ulBase){int iMsg;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Place CAN controller in init state, regardless of previous state. This// will put controller in idle, and allow the message object RAM to be// programmed.//CANRegWrite(ulBase + CAN_O_CTL, CAN_CTL_INIT);//// Wait for busy bit to clear//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}//// Clear the message value bit in the arbitration register. This indicates// the message is not valid and is a "safe" condition to leave the message// object. The same arb reg is used to program all the message objects.//CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_ARB |CAN_IF1CMSK_CONTROL);CANRegWrite(ulBase + CAN_O_IF1ARB2, 0);CANRegWrite(ulBase + CAN_O_IF1MCTL, 0);//// Loop through to program all 32 message objects//for(iMsg = 1; iMsg <= 32; iMsg++){//// Wait for busy bit to clear//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}//// Initiate programming the message object//CANRegWrite(ulBase + CAN_O_IF1CRQ, iMsg);}//// Make sure that the interrupt and new data flags are updated for the// message objects.//CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_NEWDAT |CAN_IF1CMSK_CLRINTPND);//// Loop through to program all 32 message objects//for(iMsg = 1; iMsg <= 32; iMsg++){//// Wait for busy bit to clear.//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}//// Initiate programming the message object//CANRegWrite(ulBase + CAN_O_IF1CRQ, iMsg);}//// Acknowledge any pending status interrupts.//CANRegRead(ulBase + CAN_O_STS);}//*****************************************************************************////! Enables the CAN controller.//!//! \param ulBase is the base address of the CAN controller to enable.//!//! Enables the CAN controller for message processing. Once enabled, the//! controller will automatically transmit any pending frames, and process any//! received frames. The controller can be stopped by calling CANDisable().//! Prior to calling CANEnable(), CANInit() should have been called to//! initialize the controller and the CAN bus clock should be configured by//! calling CANBitTimingSet().//!//! \return None.////*****************************************************************************voidCANEnable(unsigned long ulBase){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Clear the init bit in the control register.//CANRegWrite(ulBase + CAN_O_CTL,CANRegRead(ulBase + CAN_O_CTL) & ~CAN_CTL_INIT);}//*****************************************************************************////! Disables the CAN controller.//!//! \param ulBase is the base address of the CAN controller to disable.//!//! Disables the CAN controller for message processing. When disabled, the//! controller will no longer automatically process data on the CAN bus. The//! controller can be restarted by calling CANEnable(). The state of the CAN//! controller and the message objects in the controller are left as they were//! before this call was made.//!//! \return None.////*****************************************************************************voidCANDisable(unsigned long ulBase){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Set the init bit in the control register.//CANRegWrite(ulBase + CAN_O_CTL,CANRegRead(ulBase + CAN_O_CTL) | CAN_CTL_INIT);}//*****************************************************************************////! Reads the current settings for the CAN controller bit timing.//!//! \param ulBase is the base address of the CAN controller.//! \param pClkParms is a pointer to a structure to hold the timing parameters.//!//! This function reads the current configuration of the CAN controller bit//! clock timing, and stores the resulting information in the structure//! supplied by the caller. Refer to CANBitTimingSet() for the meaning of the//! values that are returned in the structure pointed to by \e pClkParms.//!//! This function replaces the original CANGetBitTiming() API and performs the//! same actions. A macro is provided in <tt>can.h</tt> to map the original//! API to this API.//!//! \return None.////*****************************************************************************voidCANBitTimingGet(unsigned long ulBase, tCANBitClkParms *pClkParms){unsigned int uBitReg;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT(pClkParms != 0);//// Read out all the bit timing values from the CAN controller registers.//uBitReg = CANRegRead(ulBase + CAN_O_BIT);//// Set the phase 2 segment.//pClkParms->uPhase2Seg = ((uBitReg & CAN_BIT_TSEG2_M) >> 12) + 1;//// Set the phase 1 segment.//pClkParms->uSyncPropPhase1Seg = ((uBitReg & CAN_BIT_TSEG1_M) >> 8) + 1;//// Set the sychronous jump width.//pClkParms->uSJW = ((uBitReg & CAN_BIT_SJW_M) >> 6) + 1;//// Set the pre-divider for the CAN bus bit clock.//pClkParms->uQuantumPrescaler =((uBitReg & CAN_BIT_BRP_M) |((CANRegRead(ulBase + CAN_O_BRPE) & CAN_BRPE_BRPE_M) << 6)) + 1;}//*****************************************************************************////! This function is used to set the CAN bit timing values to a nominal setting//! based on a desired bit rate.//!//! \param ulBase is the base address of the CAN controller.//! \param ulSourceClock is the system clock for the device in Hz.//! \param ulBitRate is the desired bit rate.//!//! This function will set the CAN bit timing for the bit rate passed in the//! \e ulBitRate parameter based on the \e ulSourceClock parameter. Since the//! CAN clock is based off of the system clock the calling function should pass//! in the source clock rate either by retrieving it from SysCtlClockGet() or//! using a specific value in Hz. The CAN bit clock is calculated to be an//! average timing value that should work for most systems. If tighter timing//! requirements are needed, then the CANBitTimingSet() function is available//! for full customization of all of the CAN bit timing values. Since not all//! bit rates can be matched exactly, the bit rate is set to the value closest//! to the desired bit rate without being higher than the \e ulBitRate value.//!//! \note On some devices the source clock is fixed at 8MHz so the//! \e ulSourceClock should be set to 8000000.//!//! \return This function returns the bit rate that the CAN controller was//! configured to use or it returns 0 to indicate that the bit rate was not//! changed because the requested bit rate was not valid.//!//*****************************************************************************unsigned longCANBitRateSet(unsigned long ulBase, unsigned long ulSourceClock,unsigned long ulBitRate){unsigned long ulDesiredRatio;unsigned long ulCANBits;unsigned long ulPreDivide;unsigned long ulRegValue;unsigned short usCANCTL;ASSERT(ulBitRate != 0);//// Caclulate the desired clock rate.//ulDesiredRatio = ulSourceClock / ulBitRate;//// If the ratio of CAN bit rate to processor clock is too small or too// large then return 0 indicating that no bit rate was set.//if((ulDesiredRatio > (CAN_MIN_PRE_DIVISOR * CAN_MIN_BIT_DIVISOR)) ||(ulDesiredRatio < CAN_MIN_BIT_DIVISOR)){return(0);}//// Make sure that the Desired Ratio is not too large. This enforces the// requirement that the bit rate is larger than requested.//if((ulSourceClock / ulDesiredRatio) > ulBitRate){ulDesiredRatio += 1;}//// Check all possible values to find a matching value.//while(ulDesiredRatio <= CAN_MAX_PRE_DIVISOR * CAN_MAX_BIT_DIVISOR){//// Loop through all possible CAN bit divisors.//for(ulCANBits = CAN_MAX_BIT_DIVISOR; ulCANBits >= CAN_MIN_BIT_DIVISOR;ulCANBits--){//// For a given CAN bit divisor save the pre divisor.//ulPreDivide = ulDesiredRatio / ulCANBits;//// If the caculated divisors match the desired clock ratio then// return these bit rate and set the CAN bit timing.//if((ulPreDivide * ulCANBits) == ulDesiredRatio){//// Start building the bit timing value by adding the bit timing// in time quanta.//ulRegValue = g_usCANBitValues[ulCANBits - CAN_MIN_BIT_DIVISOR];//// To set the bit timing register, the controller must be placed// in init mode (if not already), and also configuration change// bit enabled. The stat of the register should be saved// so it can be restored.//usCANCTL = CANRegRead(ulBase + CAN_O_CTL);CANRegWrite(ulBase + CAN_O_CTL, usCANCTL | CAN_CTL_INIT |CAN_CTL_CCE);//// Now add in the pre-scalar on the bit rate.//ulRegValue |= ((ulPreDivide - 1)& CAN_BIT_BRP_M);//// Set the clock bits in the and the lower bits of the// pre-scalar.//CANRegWrite(ulBase + CAN_O_BIT, ulRegValue);//// Set the divider upper bits in the extension register.//CANRegWrite(ulBase + CAN_O_BRPE,((ulPreDivide - 1) >> 6) & CAN_BRPE_BRPE_M);//// Restore the saved CAN Control register.//CANRegWrite(ulBase + CAN_O_CTL, usCANCTL);//// Return the computed bit rate.//return(ulSourceClock / ( ulPreDivide * ulCANBits));}}//// Move the divisor up one and look again. Only in rare cases are// more than 2 loops required to find the value.//ulDesiredRatio++;}return(0);}//*****************************************************************************////! Configures the CAN controller bit timing.//!//! \param ulBase is the base address of the CAN controller.//! \param pClkParms points to the structure with the clock parameters.//!//! Configures the various timing parameters for the CAN bus bit timing://! Propagation segment, Phase Buffer 1 segment, Phase Buffer 2 segment, and//! the Synchronization Jump Width. The values for Propagation and Phase//! Buffer 1 segments are derived from the combination//! \e pClkParms->uSyncPropPhase1Seg parameter. Phase Buffer 2 is determined//! from the \e pClkParms->uPhase2Seg parameter. These two parameters, along//! with \e pClkParms->uSJW are based in units of bit time quanta. The actual//! quantum time is determined by the \e pClkParms->uQuantumPrescaler value,//! which specifies the divisor for the CAN module clock.//!//! The total bit time, in quanta, will be the sum of the two Seg parameters,//! as follows://!//! bit_time_q = uSyncPropPhase1Seg + uPhase2Seg + 1//!//! Note that the Sync_Seg is always one quantum in duration, and will be added//! to derive the correct duration of Prop_Seg and Phase1_Seg.//!//! The equation to determine the actual bit rate is as follows://!//! CAN Clock ///! ((\e uSyncPropPhase1Seg + \e uPhase2Seg + 1) * (\e uQuantumPrescaler))//!//! This means that with \e uSyncPropPhase1Seg = 4, \e uPhase2Seg = 1,//! \e uQuantumPrescaler = 2 and an 8 MHz CAN clock, that the bit rate will be//! (8 MHz) / ((5 + 2 + 1) * 2) or 500 Kbit/sec.//!//! This function replaces the original CANSetBitTiming() API and performs the//! same actions. A macro is provided in <tt>can.h</tt> to map the original//! API to this API.//!//! \return None.////*****************************************************************************voidCANBitTimingSet(unsigned long ulBase, tCANBitClkParms *pClkParms){unsigned int uBitReg;unsigned int uSavedInit;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT(pClkParms != 0);//// The phase 1 segment must be in the range from 2 to 16.//ASSERT((pClkParms->uSyncPropPhase1Seg >= 2) &&(pClkParms->uSyncPropPhase1Seg <= 16));//// The phase 2 segment must be in the range from 1 to 8.//ASSERT((pClkParms->uPhase2Seg >= 1) && (pClkParms->uPhase2Seg <= 8));//// The synchronous jump windows must be in the range from 1 to 4.//ASSERT((pClkParms->uSJW >= 1) && (pClkParms->uSJW <= 4));//// The CAN clock pre-divider must be in the range from 1 to 1024.//ASSERT((pClkParms->uQuantumPrescaler <= 1024) &&(pClkParms->uQuantumPrescaler >= 1));//// To set the bit timing register, the controller must be placed in init// mode (if not already), and also configuration change bit enabled. State// of the init bit should be saved so it can be restored at the end.//uSavedInit = CANRegRead(ulBase + CAN_O_CTL);CANRegWrite(ulBase + CAN_O_CTL, uSavedInit | CAN_CTL_INIT | CAN_CTL_CCE);//// Set the bit fields of the bit timing register according to the parms.//uBitReg = ((pClkParms->uPhase2Seg - 1) << 12) & CAN_BIT_TSEG2_M;uBitReg |= ((pClkParms->uSyncPropPhase1Seg - 1) << 8) & CAN_BIT_TSEG1_M;uBitReg |= ((pClkParms->uSJW - 1) << 6) & CAN_BIT_SJW_M;uBitReg |= (pClkParms->uQuantumPrescaler - 1) & CAN_BIT_BRP_M;CANRegWrite(ulBase + CAN_O_BIT, uBitReg);//// Set the divider upper bits in the extension register.//CANRegWrite(ulBase + CAN_O_BRPE,((pClkParms->uQuantumPrescaler - 1) >> 6) & CAN_BRPE_BRPE_M);//// Clear the config change bit, and restore the init bit.//uSavedInit &= ~CAN_CTL_CCE;//// If Init was not set before, then clear it.//if(uSavedInit & CAN_CTL_INIT){uSavedInit &= ~CAN_CTL_INIT;}CANRegWrite(ulBase + CAN_O_CTL, uSavedInit);}//*****************************************************************************////! Registers an interrupt handler for the CAN controller.//!//! \param ulBase is the base address of the CAN controller.//! \param pfnHandler is a pointer to the function to be called when the//! enabled CAN interrupts occur.//!//! This function registers the interrupt handler in the interrupt vector//! table, and enables CAN interrupts on the interrupt controller; specific CAN//! interrupt sources must be enabled using CANIntEnable(). The interrupt//! handler being registered must clear the source of the interrupt using//! CANIntClear().//!//! If the application is using a static interrupt vector table stored in//! flash, then it is not necessary to register the interrupt handler this way.//! Instead, IntEnable() should be used to enable CAN interrupts on the//! interrupt controller.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidCANIntRegister(unsigned long ulBase, void (*pfnHandler)(void)){unsigned long ulIntNumber;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Get the actual interrupt number for this CAN controller.//ulIntNumber = CANIntNumberGet(ulBase);//// Register the interrupt handler.//IntRegister(ulIntNumber, pfnHandler);//// Enable the Ethernet interrupt.//IntEnable(ulIntNumber);}//*****************************************************************************////! Unregisters an interrupt handler for the CAN controller.//!//! \param ulBase is the base address of the controller.//!//! This function unregisters the previously registered interrupt handler and//! disables the interrupt on the interrupt controller.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidCANIntUnregister(unsigned long ulBase){unsigned long ulIntNumber;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Get the actual interrupt number for this CAN controller.//ulIntNumber = CANIntNumberGet(ulBase);//// Register the interrupt handler.//IntUnregister(ulIntNumber);//// Disable the CAN interrupt.//IntDisable(ulIntNumber);}//*****************************************************************************////! Enables individual CAN controller interrupt sources.//!//! \param ulBase is the base address of the CAN controller.//! \param ulIntFlags is the bit mask of the interrupt sources to be enabled.//!//! Enables specific interrupt sources of the CAN controller. Only enabled//! sources will cause a processor interrupt.//!//! The \e ulIntFlags parameter is the logical OR of any of the following://!//! - \b CAN_INT_ERROR - a controller error condition has occurred//! - \b CAN_INT_STATUS - a message transfer has completed, or a bus error has//! been detected//! - \b CAN_INT_MASTER - allow CAN controller to generate interrupts//!//! In order to generate any interrupts, \b CAN_INT_MASTER must be enabled.//! Further, for any particular transaction from a message object to generate//! an interrupt, that message object must have interrupts enabled (see//! CANMessageSet()). \b CAN_INT_ERROR will generate an interrupt if the//! controller enters the ``bus off'' condition, or if the error counters reach//! a limit. \b CAN_INT_STATUS will generate an interrupt under quite a few//! status conditions and may provide more interrupts than the application//! needs to handle. When an interrupt occurs, use CANIntStatus() to determine//! the cause.//!//! \return None.////*****************************************************************************voidCANIntEnable(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT((ulIntFlags & ~(CAN_CTL_EIE | CAN_CTL_SIE | CAN_CTL_IE)) == 0);//// Enable the specified interrupts.//CANRegWrite(ulBase + CAN_O_CTL,CANRegRead(ulBase + CAN_O_CTL) | ulIntFlags);}//*****************************************************************************////! Disables individual CAN controller interrupt sources.//!//! \param ulBase is the base address of the CAN controller.//! \param ulIntFlags is the bit mask of the interrupt sources to be disabled.//!//! Disables the specified CAN controller interrupt sources. Only enabled//! interrupt sources can cause a processor interrupt.//!//! The \e ulIntFlags parameter has the same definition as in the//! CANIntEnable() function.//!//! \return None.////*****************************************************************************voidCANIntDisable(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT((ulIntFlags & ~(CAN_CTL_EIE | CAN_CTL_SIE | CAN_CTL_IE)) == 0);//// Disable the specified interrupts.//CANRegWrite(ulBase + CAN_O_CTL,CANRegRead(ulBase + CAN_O_CTL) & ~(ulIntFlags));}//*****************************************************************************////! Returns the current CAN controller interrupt status.//!//! \param ulBase is the base address of the CAN controller.//! \param eIntStsReg indicates which interrupt status register to read//!//! Returns the value of one of two interrupt status registers. The interrupt//! status register read is determined by the \e eIntStsReg parameter, which//! can have one of the following values://!//! - \b CAN_INT_STS_CAUSE - indicates the cause of the interrupt//! - \b CAN_INT_STS_OBJECT - indicates pending interrupts of all message//! objects//!//! \b CAN_INT_STS_CAUSE returns the value of the controller interrupt register//! and indicates the cause of the interrupt. It will be a value of//! \b CAN_INT_INTID_STATUS if the cause is a status interrupt. In this case,//! the status register should be read with the CANStatusGet() function.//! Calling this function to read the status will also clear the status//! interrupt. If the value of the interrupt register is in the range 1-32,//! then this indicates the number of the highest priority message object that//! has an interrupt pending. The message object interrupt can be cleared by//! using the CANIntClear() function, or by reading the message using//! CANMessageGet() in the case of a received message. The interrupt handler//! can read the interrupt status again to make sure all pending interrupts are//! cleared before returning from the interrupt.//!//! \b CAN_INT_STS_OBJECT returns a bit mask indicating which message objects//! have pending interrupts. This can be used to discover all of the pending//! interrupts at once, as opposed to repeatedly reading the interrupt register//! by using \b CAN_INT_STS_CAUSE.//!//! \return Returns the value of one of the interrupt status registers.////*****************************************************************************unsigned longCANIntStatus(unsigned long ulBase, tCANIntStsReg eIntStsReg){unsigned long ulStatus;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// See which status the caller is looking for.//switch(eIntStsReg){//// The caller wants the global interrupt status for the CAN controller// specified by ulBase.//case CAN_INT_STS_CAUSE:{ulStatus = CANRegRead(ulBase + CAN_O_INT);break;}//// The caller wants the current message status interrupt for all// messages.//case CAN_INT_STS_OBJECT:{//// Read and combine both 16 bit values into one 32bit status.//ulStatus = (CANRegRead(ulBase + CAN_O_MSG1INT) &CAN_MSG1INT_INTPND_M);ulStatus |= (CANRegRead(ulBase + CAN_O_MSG2INT) << 16);break;}//// Request was for unknown status so just return 0.//default:{ulStatus = 0;break;}}//// Return the interrupt status value//return(ulStatus);}//*****************************************************************************////! Clears a CAN interrupt source.//!//! \param ulBase is the base address of the CAN controller.//! \param ulIntClr is a value indicating which interrupt source to clear.//!//! This function can be used to clear a specific interrupt source. The//! \e ulIntClr parameter should be one of the following values://!//! - \b CAN_INT_INTID_STATUS - Clears a status interrupt.//! - 1-32 - Clears the specified message object interrupt//!//! It is not necessary to use this function to clear an interrupt. This//! should only be used if the application wants to clear an interrupt source//! without taking the normal interrupt action.//!//! Normally, the status interrupt is cleared by reading the controller status//! using CANStatusGet(). A specific message object interrupt is normally//! cleared by reading the message object using CANMessageGet().//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidCANIntClear(unsigned long ulBase, unsigned long ulIntClr){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT((ulIntClr == CAN_INT_INTID_STATUS) ||((ulIntClr>=1) && (ulIntClr <=32)));if(ulIntClr == CAN_INT_INTID_STATUS){//// Simply read and discard the status to clear the interrupt.//CANRegRead(ulBase + CAN_O_STS);}else{//// Wait to be sure that this interface is not busy.//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}//// Only change the interrupt pending state by setting only the// CAN_IF1CMSK_CLRINTPND bit.//CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_CLRINTPND);//// Send the clear pending interrupt command to the CAN controller.//CANRegWrite(ulBase + CAN_O_IF1CRQ, ulIntClr & CAN_IF1CRQ_MNUM_M);//// Wait to be sure that this interface is not busy.//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}}}//*****************************************************************************////! Sets the CAN controller automatic retransmission behavior.//!//! \param ulBase is the base address of the CAN controller.//! \param bAutoRetry enables automatic retransmission.//!//! Enables or disables automatic retransmission of messages with detected//! errors. If \e bAutoRetry is \b true, then automatic retransmission is//! enabled, otherwise it is disabled.//!//! \return None.////*****************************************************************************voidCANRetrySet(unsigned long ulBase, tBoolean bAutoRetry){unsigned long ulCtlReg;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ulCtlReg = CANRegRead(ulBase + CAN_O_CTL);//// Conditionally set the DAR bit to enable/disable auto-retry.//if(bAutoRetry){//// Clearing the DAR bit tells the controller to not disable the// auto-retry of messages which were not transmitted or received// correctly.//ulCtlReg &= ~CAN_CTL_DAR;}else{//// Setting the DAR bit tells the controller to disable the auto-retry// of messages which were not transmitted or received correctly.//ulCtlReg |= CAN_CTL_DAR;}CANRegWrite(ulBase + CAN_O_CTL, ulCtlReg);}//*****************************************************************************////! Returns the current setting for automatic retransmission.//!//! \param ulBase is the base address of the CAN controller.//!//! Reads the current setting for the automatic retransmission in the CAN//! controller and returns it to the caller.//!//! \return Returns \b true if automatic retransmission is enabled, \b false//! otherwise.////*****************************************************************************tBooleanCANRetryGet(unsigned long ulBase){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Read the disable automatic retry setting from the CAN controller.//if(CANRegRead(ulBase + CAN_O_CTL) & CAN_CTL_DAR){//// Automatic data retransmission is not enabled.//return(false);}//// Automatic data retransmission is enabled.//return(true);}//*****************************************************************************////! Reads one of the controller status registers.//!//! \param ulBase is the base address of the CAN controller.//! \param eStatusReg is the status register to read.//!//! Reads a status register of the CAN controller and returns it to the caller.//! The different status registers are://!//! - \b CAN_STS_CONTROL - the main controller status//! - \b CAN_STS_TXREQUEST - bit mask of objects pending transmission//! - \b CAN_STS_NEWDAT - bit mask of objects with new data//! - \b CAN_STS_MSGVAL - bit mask of objects with valid configuration//!//! When reading the main controller status register, a pending status//! interrupt will be cleared. This should be used in the interrupt handler//! for the CAN controller if the cause is a status interrupt. The controller//! status register fields are as follows://!//! - \b CAN_STATUS_BUS_OFF - controller is in bus-off condition//! - \b CAN_STATUS_EWARN - an error counter has reached a limit of at least 96//! - \b CAN_STATUS_EPASS - CAN controller is in the error passive state//! - \b CAN_STATUS_RXOK - a message was received successfully (independent of//! any message filtering).//! - \b CAN_STATUS_TXOK - a message was successfully transmitted//! - \b CAN_STATUS_LEC_MSK - mask of last error code bits (3 bits)//! - \b CAN_STATUS_LEC_NONE - no error//! - \b CAN_STATUS_LEC_STUFF - stuffing error detected//! - \b CAN_STATUS_LEC_FORM - a format error occurred in the fixed format part//! of a message//! - \b CAN_STATUS_LEC_ACK - a transmitted message was not acknowledged//! - \b CAN_STATUS_LEC_BIT1 - dominant level detected when trying to send in//! recessive mode//! - \b CAN_STATUS_LEC_BIT0 - recessive level detected when trying to send in//! dominant mode//! - \b CAN_STATUS_LEC_CRC - CRC error in received message//!//! The remaining status registers are 32-bit bit maps to the message objects.//! They can be used to quickly obtain information about the status of all the//! message objects without needing to query each one. They contain the//! following information://!//! - \b CAN_STS_TXREQUEST - if a message object's TxRequest bit is set, that//! means that a transmission is pending on that object. The application can//! use this to determine which objects are still waiting to send a message.//! - \b CAN_STS_NEWDAT - if a message object's NewDat bit is set, that means//! that a new message has been received in that object, and has not yet been//! picked up by the host application//! - \b CAN_STS_MSGVAL - if a message object's MsgVal bit is set, that means//! it has a valid configuration programmed. The host application can use this//! to determine which message objects are empty/unused.//!//! \return Returns the value of the status register.////*****************************************************************************unsigned longCANStatusGet(unsigned long ulBase, tCANStsReg eStatusReg){unsigned long ulStatus;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));switch(eStatusReg){//// Just return the global CAN status register since that is what was// requested.//case CAN_STS_CONTROL:{ulStatus = CANRegRead(ulBase + CAN_O_STS);CANRegWrite(ulBase + CAN_O_STS,~(CAN_STS_RXOK | CAN_STS_TXOK | CAN_STS_LEC_M));break;}//// Combine the Transmit status bits into one 32bit value.//case CAN_STS_TXREQUEST:{ulStatus = CANRegRead(ulBase + CAN_O_TXRQ1);ulStatus |= CANRegRead(ulBase + CAN_O_TXRQ2) << 16;break;}//// Combine the New Data status bits into one 32bit value.//case CAN_STS_NEWDAT:{ulStatus = CANRegRead(ulBase + CAN_O_NWDA1);ulStatus |= CANRegRead(ulBase + CAN_O_NWDA2) << 16;break;}//// Combine the Message valid status bits into one 32bit value.//case CAN_STS_MSGVAL:{ulStatus = CANRegRead(ulBase + CAN_O_MSG1VAL);ulStatus |= CANRegRead(ulBase + CAN_O_MSG2VAL) << 16;break;}//// Unknown CAN status requested so return 0.//default:{ulStatus = 0;break;}}return(ulStatus);}//*****************************************************************************////! Reads the CAN controller error counter register.//!//! \param ulBase is the base address of the CAN controller.//! \param pulRxCount is a pointer to storage for the receive error counter.//! \param pulTxCount is a pointer to storage for the transmit error counter.//!//! Reads the error counter register and returns the transmit and receive error//! counts to the caller along with a flag indicating if the controller receive//! counter has reached the error passive limit. The values of the receive and//! transmit error counters are returned through the pointers provided as//! parameters.//!//! After this call, \e *pulRxCount will hold the current receive error count//! and \e *pulTxCount will hold the current transmit error count.//!//! \return Returns \b true if the receive error count has reached the error//! passive limit, and \b false if the error count is below the error passive//! limit.////*****************************************************************************tBooleanCANErrCntrGet(unsigned long ulBase, unsigned long *pulRxCount,unsigned long *pulTxCount){unsigned long ulCANError;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));//// Read the current count of transmit/receive errors.//ulCANError = CANRegRead(ulBase + CAN_O_ERR);//// Extract the error numbers from the register value.//*pulRxCount = (ulCANError & CAN_ERR_REC_M) >> CAN_ERR_REC_S;*pulTxCount = (ulCANError & CAN_ERR_TEC_M) >> CAN_ERR_TEC_S;if(ulCANError & CAN_ERR_RP){return(true);}return(false);}//*****************************************************************************////! Configures a message object in the CAN controller.//!//! \param ulBase is the base address of the CAN controller.//! \param ulObjID is the object number to configure (1-32).//! \param pMsgObject is a pointer to a structure containing message object//! settings.//! \param eMsgType indicates the type of message for this object.//!//! This function is used to configure any one of the 32 message objects in the//! CAN controller. A message object can be configured as any type of CAN//! message object as well as several options for automatic transmission and//! reception. This call also allows the message object to be configured to//! generate interrupts on completion of message receipt or transmission. The//! message object can also be configured with a filter/mask so that actions//! are only taken when a message that meets certain parameters is seen on the//! CAN bus.//!//! The \e eMsgType parameter must be one of the following values://!//! - \b MSG_OBJ_TYPE_TX - CAN transmit message object.//! - \b MSG_OBJ_TYPE_TX_REMOTE - CAN transmit remote request message object.//! - \b MSG_OBJ_TYPE_RX - CAN receive message object.//! - \b MSG_OBJ_TYPE_RX_REMOTE - CAN receive remote request message object.//! - \b MSG_OBJ_TYPE_RXTX_REMOTE - CAN remote frame receive remote, then//! transmit message object.//!//! The message object pointed to by \e pMsgObject must be populated by the//! caller, as follows://!//! - \e ulMsgID - contains the message ID, either 11 or 29 bits.//! - \e ulMsgIDMask - mask of bits from \e ulMsgID that must match if//! identifier filtering is enabled.//! - \e ulFlags//! - Set \b MSG_OBJ_TX_INT_ENABLE flag to enable interrupt on transmission.//! - Set \b MSG_OBJ_RX_INT_ENABLE flag to enable interrupt on receipt.//! - Set \b MSG_OBJ_USE_ID_FILTER flag to enable filtering based on the//! identifier mask specified by \e ulMsgIDMask.//! - \e ulMsgLen - the number of bytes in the message data. This should be//! non-zero even for a remote frame; it should match the expected bytes of the//! data responding data frame.//! - \e pucMsgData - points to a buffer containing up to 8 bytes of data for a//! data frame.//!//! \b Example: To send a data frame or remote frame(in response to a remote//! request), take the following steps://!//! -# Set \e eMsgType to \b MSG_OBJ_TYPE_TX.//! -# Set \e pMsgObject->ulMsgID to the message ID.//! -# Set \e pMsgObject->ulFlags. Make sure to set \b MSG_OBJ_TX_INT_ENABLE to//! allow an interrupt to be generated when the message is sent.//! -# Set \e pMsgObject->ulMsgLen to the number of bytes in the data frame.//! -# Set \e pMsgObject->pucMsgData to point to an array containing the bytes//! to send in the message.//! -# Call this function with \e ulObjID set to one of the 32 object buffers.//!//! \b Example: To receive a specific data frame, take the following steps://!//! -# Set \e eMsgObjType to \b MSG_OBJ_TYPE_RX.//! -# Set \e pMsgObject->ulMsgID to the full message ID, or a partial mask to//! use partial ID matching.//! -# Set \e pMsgObject->ulMsgIDMask bits that should be used for masking//! during comparison.//! -# Set \e pMsgObject->ulFlags as follows://! - Set \b MSG_OBJ_TX_INT_ENABLE flag to be interrupted when the data frame//! is received.//! - Set \b MSG_OBJ_USE_ID_FILTER flag to enable identifier based filtering.//! -# Set \e pMsgObject->ulMsgLen to the number of bytes in the expected data//! frame.//! -# The buffer pointed to by \e pMsgObject->pucMsgData and//! \e pMsgObject->ulMsgLen are not used by this call as no data is present at//! the time of the call.//! -# Call this function with \e ulObjID set to one of the 32 object buffers.//!//! If you specify a message object buffer that already contains a message//! definition, it will be overwritten.//!//! \return None.////*****************************************************************************voidCANMessageSet(unsigned long ulBase, unsigned long ulObjID,tCANMsgObject *pMsgObject, tMsgObjType eMsgType){unsigned short usCmdMaskReg;unsigned short usMaskReg[2];unsigned short usArbReg[2];unsigned short usMsgCtrl;tBoolean bTransferData;tBoolean bUseExtendedID;bTransferData = 0;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT((ulObjID <= 32) && (ulObjID != 0));ASSERT((eMsgType == MSG_OBJ_TYPE_TX) ||(eMsgType == MSG_OBJ_TYPE_TX_REMOTE) ||(eMsgType == MSG_OBJ_TYPE_RX) ||(eMsgType == MSG_OBJ_TYPE_RX_REMOTE) ||(eMsgType == MSG_OBJ_TYPE_TX_REMOTE) ||(eMsgType == MSG_OBJ_TYPE_RXTX_REMOTE));//// Wait for busy bit to clear//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}//// See if we need to use an extended identifier or not.//if((pMsgObject->ulMsgID > CAN_MAX_11BIT_MSG_ID) ||(pMsgObject->ulFlags & MSG_OBJ_EXTENDED_ID)){bUseExtendedID = 1;}else{bUseExtendedID = 0;}//// This is always a write to the Message object as this call is setting a// message object. This call will also always set all size bits so it sets// both data bits. The call will use the CONTROL register to set control// bits so this bit needs to be set as well.//usCmdMaskReg = (CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_DATAA | CAN_IF1CMSK_DATAB |CAN_IF1CMSK_CONTROL);//// Initialize the values to a known state before filling them in based on// the type of message object that is being configured.//usArbReg[0] = 0;usMsgCtrl = 0;usMaskReg[0] = 0;usMaskReg[1] = 0;switch(eMsgType){//// Transmit message object.//case MSG_OBJ_TYPE_TX:{//// Set the TXRQST bit and the reset the rest of the register.//usMsgCtrl |= CAN_IF1MCTL_TXRQST;usArbReg[1] = CAN_IF1ARB2_DIR;bTransferData = 1;break;}//// Transmit remote request message object//case MSG_OBJ_TYPE_TX_REMOTE:{//// Set the TXRQST bit and the reset the rest of the register.//usMsgCtrl |= CAN_IF1MCTL_TXRQST;usArbReg[1] = 0;break;}//// Receive message object.//case MSG_OBJ_TYPE_RX:{//// This clears the DIR bit along with everthing else. The TXRQST// bit was cleard by defaulting usMsgCtrl to 0.//usArbReg[1] = 0;break;}//// Receive remote request message object.//case MSG_OBJ_TYPE_RX_REMOTE:{//// The DIR bit is set to one for remote receivers. The TXRQST bit// was cleard by defaulting usMsgCtrl to 0.//usArbReg[1] = CAN_IF1ARB2_DIR;//// Set this object so that it only indicates that a remote frame// was received and allow for software to handle it by sending back// a data frame.//usMsgCtrl = CAN_IF1MCTL_UMASK;//// Use the full Identifier by default.//usMaskReg[0] = 0xffff;usMaskReg[1] = 0x1fff;//// Make sure to send the mask to the message object.//usCmdMaskReg |= CAN_IF1CMSK_MASK;break;}//// Remote frame receive remote, with auto-transmit message object.//case MSG_OBJ_TYPE_RXTX_REMOTE:{//// Oddly the DIR bit is set to one for remote receivers.//usArbReg[1] = CAN_IF1ARB2_DIR;//// Set this object to auto answer if a matching identifier is seen.//usMsgCtrl = CAN_IF1MCTL_RMTEN | CAN_IF1MCTL_UMASK;//// The data to be returned needs to be filled in.//bTransferData = 1;break;}//// This case should never happen due to the ASSERT statement at the// beginning of this function.//default:{return;}}//// Configure the Mask Registers.//if(pMsgObject->ulFlags & MSG_OBJ_USE_ID_FILTER){if(bUseExtendedID){//// Set the 29 bits of Identifier mask that were requested.//usMaskReg[0] = pMsgObject->ulMsgIDMask & CAN_IF1MSK1_IDMSK_M;usMaskReg[1] = ((pMsgObject->ulMsgIDMask >> 16) &CAN_IF1MSK2_IDMSK_M);}else{//// Lower 16 bit are unused so set them to zero.//usMaskReg[0] = 0;//// Put the 11 bit Mask Identifier into the upper bits of the field// in the register.//usMaskReg[1] = ((pMsgObject->ulMsgIDMask << 2) &CAN_IF1MSK2_IDMSK_M);}}//// If the caller wants to filter on the extended ID bit then set it.//if((pMsgObject->ulFlags & MSG_OBJ_USE_EXT_FILTER) ==MSG_OBJ_USE_EXT_FILTER){usMaskReg[1] |= CAN_IF1MSK2_MXTD;}//// The caller wants to filter on the message direction field.//if((pMsgObject->ulFlags & MSG_OBJ_USE_DIR_FILTER) ==MSG_OBJ_USE_DIR_FILTER){usMaskReg[1] |= CAN_IF1MSK2_MDIR;}if(pMsgObject->ulFlags & (MSG_OBJ_USE_ID_FILTER | MSG_OBJ_USE_DIR_FILTER |MSG_OBJ_USE_EXT_FILTER)){//// Set the UMASK bit to enable using the mask register.//usMsgCtrl |= CAN_IF1MCTL_UMASK;//// Set the MASK bit so that this gets trasferred to the Message Object.//usCmdMaskReg |= CAN_IF1CMSK_MASK;}//// Set the Arb bit so that this gets transferred to the Message object.//usCmdMaskReg |= CAN_IF1CMSK_ARB;//// Configure the Arbitration registers.//if(bUseExtendedID){//// Set the 29 bit version of the Identifier for this message object.//usArbReg[0] |= pMsgObject->ulMsgID & CAN_IF1ARB1_ID_M;usArbReg[1] |= (pMsgObject->ulMsgID >> 16) & CAN_IF1ARB2_ID_M;//// Mark the message as valid and set the extended ID bit.//usArbReg[1] |= CAN_IF1ARB2_MSGVAL | CAN_IF1ARB2_XTD;}else{//// Set the 11 bit version of the Identifier for this message object.// The lower 18 bits are set to zero.//usArbReg[1] |= (pMsgObject->ulMsgID << 2) & CAN_IF1ARB2_ID_M;//// Mark the message as valid.//usArbReg[1] |= CAN_IF1ARB2_MSGVAL;}//// Set the data length since this is set for all transfers. This is also a// single transfer and not a FIFO transfer so set EOB bit.//usMsgCtrl |= (pMsgObject->ulMsgLen & CAN_IF1MCTL_DLC_M) | CAN_IF1MCTL_EOB;//// Enable transmit interrupts if they should be enabled.//if(pMsgObject->ulFlags & MSG_OBJ_TX_INT_ENABLE){usMsgCtrl |= CAN_IF1MCTL_TXIE;}//// Enable receive interrupts if they should be enabled.//if(pMsgObject->ulFlags & MSG_OBJ_RX_INT_ENABLE){usMsgCtrl |= CAN_IF1MCTL_RXIE;}//// Write the data out to the CAN Data registers if needed.//if(bTransferData){CANDataRegWrite(pMsgObject->pucMsgData,(unsigned long *)(ulBase + CAN_O_IF1DA1),pMsgObject->ulMsgLen);}//// Write out the registers to program the message object.//CANRegWrite(ulBase + CAN_O_IF1CMSK, usCmdMaskReg);CANRegWrite(ulBase + CAN_O_IF1MSK1, usMaskReg[0]);CANRegWrite(ulBase + CAN_O_IF1MSK2, usMaskReg[1]);CANRegWrite(ulBase + CAN_O_IF1ARB1, usArbReg[0]);CANRegWrite(ulBase + CAN_O_IF1ARB2, usArbReg[1]);CANRegWrite(ulBase + CAN_O_IF1MCTL, usMsgCtrl);//// Transfer the message object to the message object specifiec by ulObjID.//CANRegWrite(ulBase + CAN_O_IF1CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);return;}//*****************************************************************************////! Reads a CAN message from one of the message object buffers.//!//! \param ulBase is the base address of the CAN controller.//! \param ulObjID is the object number to read (1-32).//! \param pMsgObject points to a structure containing message object fields.//! \param bClrPendingInt indicates whether an associated interrupt should be//! cleared.//!//! This function is used to read the contents of one of the 32 message objects//! in the CAN controller, and return it to the caller. The data returned is//! stored in the fields of the caller-supplied structure pointed to by//! \e pMsgObject. The data consists of all of the parts of a CAN message,//! plus some control and status information.//!//! Normally this is used to read a message object that has received and stored//! a CAN message with a certain identifier. However, this could also be used//! to read the contents of a message object in order to load the fields of the//! structure in case only part of the structure needs to be changed from a//! previous setting.//!//! When using CANMessageGet, all of the same fields of the structure are//! populated in the same way as when the CANMessageSet() function is used,//! with the following exceptions://!//! \e pMsgObject->ulFlags://!//! - \b MSG_OBJ_NEW_DATA indicates if this is new data since the last time it//! was read//! - \b MSG_OBJ_DATA_LOST indicates that at least one message was received on//! this message object, and not read by the host before being overwritten.//!//! \return None.////*****************************************************************************voidCANMessageGet(unsigned long ulBase, unsigned long ulObjID,tCANMsgObject *pMsgObject, tBoolean bClrPendingInt){unsigned short usCmdMaskReg;unsigned short usMaskReg[2];unsigned short usArbReg[2];unsigned short usMsgCtrl;//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT((ulObjID <= 32) && (ulObjID != 0));//// This is always a read to the Message object as this call is setting a// message object.//usCmdMaskReg = (CAN_IF1CMSK_DATAA | CAN_IF1CMSK_DATAB |CAN_IF1CMSK_CONTROL | CAN_IF1CMSK_MASK | CAN_IF1CMSK_ARB);//// Clear a pending interrupt and new data in a message object.//if(bClrPendingInt){usCmdMaskReg |= CAN_IF1CMSK_CLRINTPND;}//// Set up the request for data from the message object.//CANRegWrite(ulBase + CAN_O_IF2CMSK, usCmdMaskReg);//// Transfer the message object to the message object specifiec by ulObjID.//CANRegWrite(ulBase + CAN_O_IF2CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);//// Wait for busy bit to clear//while(CANRegRead(ulBase + CAN_O_IF2CRQ) & CAN_IF1CRQ_BUSY){}//// Read out the IF Registers.//usMaskReg[0] = CANRegRead(ulBase + CAN_O_IF2MSK1);usMaskReg[1] = CANRegRead(ulBase + CAN_O_IF2MSK2);usArbReg[0] = CANRegRead(ulBase + CAN_O_IF2ARB1);usArbReg[1] = CANRegRead(ulBase + CAN_O_IF2ARB2);usMsgCtrl = CANRegRead(ulBase + CAN_O_IF2MCTL);pMsgObject->ulFlags = MSG_OBJ_NO_FLAGS;//// Determine if this is a remote frame by checking the TXRQST and DIR bits.//if((!(usMsgCtrl & CAN_IF1MCTL_TXRQST) &&(usArbReg[1] & CAN_IF1ARB2_DIR)) ||((usMsgCtrl & CAN_IF1MCTL_TXRQST) &&(!(usArbReg[1] & CAN_IF1ARB2_DIR)))){pMsgObject->ulFlags |= MSG_OBJ_REMOTE_FRAME;}//// Get the identifier out of the register, the format depends on size of// the mask.//if(usArbReg[1] & CAN_IF1ARB2_XTD){//// Set the 29 bit version of the Identifier for this message object.//pMsgObject->ulMsgID = ((usArbReg[1] & CAN_IF1ARB2_ID_M) << 16) |usArbReg[0];pMsgObject->ulFlags |= MSG_OBJ_EXTENDED_ID;}else{//// The Identifier is an 11 bit value.//pMsgObject->ulMsgID = (usArbReg[1] & CAN_IF1ARB2_ID_M) >> 2;}//// Indicate that we lost some data.//if(usMsgCtrl & CAN_IF1MCTL_MSGLST){pMsgObject->ulFlags |= MSG_OBJ_DATA_LOST;}//// Set the flag to indicate if ID masking was used.//if(usMsgCtrl & CAN_IF1MCTL_UMASK){if(usArbReg[1] & CAN_IF1ARB2_XTD){//// The Identifier Mask is assumed to also be a 29 bit value.//pMsgObject->ulMsgIDMask =((usMaskReg[1] & CAN_IF1MSK2_IDMSK_M) << 16) | usMaskReg[0];//// If this is a fully specified Mask and a remote frame then don't// set the MSG_OBJ_USE_ID_FILTER because the ID was not really// filtered.//if((pMsgObject->ulMsgIDMask != 0x1fffffff) ||((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0)){pMsgObject->ulFlags |= MSG_OBJ_USE_ID_FILTER;}}else{//// The Identifier Mask is assumed to also be an 11 bit value.//pMsgObject->ulMsgIDMask = ((usMaskReg[1] & CAN_IF1MSK2_IDMSK_M) >>2);//// If this is a fully specified Mask and a remote frame then don't// set the MSG_OBJ_USE_ID_FILTER because the ID was not really// filtered.//if((pMsgObject->ulMsgIDMask != 0x7ff) ||((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0)){pMsgObject->ulFlags |= MSG_OBJ_USE_ID_FILTER;}}//// Indicate if the extended bit was used in filtering.//if(usMaskReg[1] & CAN_IF1MSK2_MXTD){pMsgObject->ulFlags |= MSG_OBJ_USE_EXT_FILTER;}//// Indicate if direction filtering was enabled.//if(usMaskReg[1] & CAN_IF1MSK2_MDIR){pMsgObject->ulFlags |= MSG_OBJ_USE_DIR_FILTER;}}//// Set the interupt flags.//if(usMsgCtrl & CAN_IF1MCTL_TXIE){pMsgObject->ulFlags |= MSG_OBJ_TX_INT_ENABLE;}if(usMsgCtrl & CAN_IF1MCTL_RXIE){pMsgObject->ulFlags |= MSG_OBJ_RX_INT_ENABLE;}//// See if there is new data available.//if(usMsgCtrl & CAN_IF1MCTL_NEWDAT){//// Get the amount of data needed to be read.//pMsgObject->ulMsgLen = (usMsgCtrl & CAN_IF1MCTL_DLC_M);//// Don't read any data for a remote frame, there is nothing valid in// that buffer anyway.//if((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0){//// Read out the data from the CAN registers.//CANDataRegRead(pMsgObject->pucMsgData,(unsigned long *)(ulBase + CAN_O_IF2DA1),pMsgObject->ulMsgLen);}//// Now clear out the new data flag.//CANRegWrite(ulBase + CAN_O_IF2CMSK, CAN_IF1CMSK_NEWDAT);//// Transfer the message object to the message object specifiec by// ulObjID.//CANRegWrite(ulBase + CAN_O_IF2CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);//// Wait for busy bit to clear//while(CANRegRead(ulBase + CAN_O_IF2CRQ) & CAN_IF1CRQ_BUSY){}//// Indicate that there is new data in this message.//pMsgObject->ulFlags |= MSG_OBJ_NEW_DATA;}else{//// Along with the MSG_OBJ_NEW_DATA not being set the amount of data// needs to be set to zero if none was available.//pMsgObject->ulMsgLen = 0;}}//*****************************************************************************////! Clears a message object so that it is no longer used.//!//! \param ulBase is the base address of the CAN controller.//! \param ulObjID is the message object number to disable (1-32).//!//! This function frees the specified message object from use. Once a message//! object has been ``cleared,'' it will no longer automatically send or//! receive messages, or generate interrupts.//!//! \return None.////*****************************************************************************voidCANMessageClear(unsigned long ulBase, unsigned long ulObjID){//// Check the arguments.//ASSERT(CANBaseValid(ulBase));ASSERT((ulObjID >= 1) && (ulObjID <= 32));//// Wait for busy bit to clear//while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY){}//// Clear the message value bit in the arbitration register. This indicates// the message is not valid.//CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_ARB);CANRegWrite(ulBase + CAN_O_IF1ARB1, 0);CANRegWrite(ulBase + CAN_O_IF1ARB2, 0);//// Initiate programming the message object//CANRegWrite(ulBase + CAN_O_IF1CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:facabf8c64c584f037701b3229889700b8a68dc4cbd85324efd85ed609128212size 14732123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459//*****************************************************************************//// can.h - Defines and Macros for the CAN controller.//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __CAN_H__#define __CAN_H__//*****************************************************************************////! \addtogroup can_api//! @{////*****************************************************************************//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Miscellaneous defines for Message ID Types////*****************************************************************************//*****************************************************************************////! These are the flags used by the tCANMsgObject variable when calling the//! CANMessageSet() and CANMessageGet() functions.////*****************************************************************************typedef enum{////! This indicates that transmit interrupts should be enabled, or are//! enabled.//MSG_OBJ_TX_INT_ENABLE = 0x00000001,////! This indicates that receive interrupts should be enabled, or are//! enabled.//MSG_OBJ_RX_INT_ENABLE = 0x00000002,////! This indicates that a message object will use or is using an extended//! identifier.//MSG_OBJ_EXTENDED_ID = 0x00000004,////! This indicates that a message object will use or is using filtering//! based on the object's message identifier.//MSG_OBJ_USE_ID_FILTER = 0x00000008,////! This indicates that new data was available in the message object.//MSG_OBJ_NEW_DATA = 0x00000080,////! This indicates that data was lost since this message object was last//! read.//MSG_OBJ_DATA_LOST = 0x00000100,////! This indicates that a message object will use or is using filtering//! based on the direction of the transfer. If the direction filtering is//! used, then ID filtering must also be enabled.//MSG_OBJ_USE_DIR_FILTER = (0x00000010 | MSG_OBJ_USE_ID_FILTER),////! This indicates that a message object will use or is using message//! identifier filtering based on the extended identifier. If the extended//! identifier filtering is used, then ID filtering must also be enabled.//MSG_OBJ_USE_EXT_FILTER = (0x00000020 | MSG_OBJ_USE_ID_FILTER),////! This indicates that a message object is a remote frame.//MSG_OBJ_REMOTE_FRAME = 0x00000040,////! This indicates that a message object has no flags set.//MSG_OBJ_NO_FLAGS = 0x00000000}tCANObjFlags;//*****************************************************************************////! This define is used with the #tCANObjFlags enumerated values to allow//! checking only status flags and not configuration flags.////*****************************************************************************#define MSG_OBJ_STATUS_MASK (MSG_OBJ_NEW_DATA | MSG_OBJ_DATA_LOST)//*****************************************************************************////! The structure used for encapsulating all the items associated with a CAN//! message object in the CAN controller.////*****************************************************************************typedef struct{////! The CAN message identifier used for 11 or 29 bit identifiers.//unsigned long ulMsgID;////! The message identifier mask used when identifier filtering is enabled.//unsigned long ulMsgIDMask;////! This value holds various status flags and settings specified by//! tCANObjFlags.//unsigned long ulFlags;////! This value is the number of bytes of data in the message object.//unsigned long ulMsgLen;////! This is a pointer to the message object's data.//unsigned char *pucMsgData;}tCANMsgObject;//*****************************************************************************////! This structure is used for encapsulating the values associated with setting//! up the bit timing for a CAN controller. The structure is used when calling//! the CANGetBitTiming and CANSetBitTiming functions.////*****************************************************************************typedef struct{////! This value holds the sum of the Synchronization, Propagation, and Phase//! Buffer 1 segments, measured in time quanta. The valid values for this//! setting range from 2 to 16.//unsigned int uSyncPropPhase1Seg;////! This value holds the Phase Buffer 2 segment in time quanta. The valid//! values for this setting range from 1 to 8.//unsigned int uPhase2Seg;////! This value holds the Resynchronization Jump Width in time quanta. The//! valid values for this setting range from 1 to 4.//unsigned int uSJW;////! This value holds the CAN_CLK divider used to determine time quanta.//! The valid values for this setting range from 1 to 1023.//unsigned int uQuantumPrescaler;}tCANBitClkParms;//*****************************************************************************////! This data type is used to identify the interrupt status register. This is//! used when calling the CANIntStatus() function.////*****************************************************************************typedef enum{////! Read the CAN interrupt status information.//CAN_INT_STS_CAUSE,////! Read a message object's interrupt status.//CAN_INT_STS_OBJECT}tCANIntStsReg;//*****************************************************************************////! This data type is used to identify which of several status registers to//! read when calling the CANStatusGet() function.////*****************************************************************************typedef enum{////! Read the full CAN controller status.//CAN_STS_CONTROL,////! Read the full 32-bit mask of message objects with a transmit request//! set.//CAN_STS_TXREQUEST,////! Read the full 32-bit mask of message objects with new data available.//CAN_STS_NEWDAT,////! Read the full 32-bit mask of message objects that are enabled.//CAN_STS_MSGVAL}tCANStsReg;//*****************************************************************************////! These definitions are used to specify interrupt sources to CANIntEnable()//! and CANIntDisable().////*****************************************************************************typedef enum{////! This flag is used to allow a CAN controller to generate error//! interrupts.//CAN_INT_ERROR = 0x00000008,////! This flag is used to allow a CAN controller to generate status//! interrupts.//CAN_INT_STATUS = 0x00000004,////! This flag is used to allow a CAN controller to generate any CAN//! interrupts. If this is not set, then no interrupts will be generated//! by the CAN controller.//CAN_INT_MASTER = 0x00000002}tCANIntFlags;//*****************************************************************************////! This definition is used to determine the type of message object that will//! be set up via a call to the CANMessageSet() API.////*****************************************************************************typedef enum{////! Transmit message object.//MSG_OBJ_TYPE_TX,////! Transmit remote request message object//MSG_OBJ_TYPE_TX_REMOTE,////! Receive message object.//MSG_OBJ_TYPE_RX,////! Receive remote request message object.//MSG_OBJ_TYPE_RX_REMOTE,////! Remote frame receive remote, with auto-transmit message object.//MSG_OBJ_TYPE_RXTX_REMOTE}tMsgObjType;//*****************************************************************************////! The following enumeration contains all error or status indicators that can//! be returned when calling the CANStatusGet() function.////*****************************************************************************typedef enum{////! CAN controller has entered a Bus Off state.//CAN_STATUS_BUS_OFF = 0x00000080,////! CAN controller error level has reached warning level.//CAN_STATUS_EWARN = 0x00000040,////! CAN controller error level has reached error passive level.//CAN_STATUS_EPASS = 0x00000020,////! A message was received successfully since the last read of this status.//CAN_STATUS_RXOK = 0x00000010,////! A message was transmitted successfully since the last read of this//! status.//CAN_STATUS_TXOK = 0x00000008,////! This is the mask for the last error code field.//CAN_STATUS_LEC_MSK = 0x00000007,////! There was no error.//CAN_STATUS_LEC_NONE = 0x00000000,////! A bit stuffing error has occurred.//CAN_STATUS_LEC_STUFF = 0x00000001,////! A formatting error has occurred.//CAN_STATUS_LEC_FORM = 0x00000002,////! An acknowledge error has occurred.//CAN_STATUS_LEC_ACK = 0x00000003,////! The bus remained a bit level of 1 for longer than is allowed.//CAN_STATUS_LEC_BIT1 = 0x00000004,////! The bus remained a bit level of 0 for longer than is allowed.//CAN_STATUS_LEC_BIT0 = 0x00000005,////! A CRC error has occurred.//CAN_STATUS_LEC_CRC = 0x00000006,////! This is the mask for the CAN Last Error Code (LEC).//CAN_STATUS_LEC_MASK = 0x00000007}tCANStatusCtrl;//*****************************************************************************//// API Function prototypes////*****************************************************************************extern void CANBitTimingGet(unsigned long ulBase, tCANBitClkParms *pClkParms);extern void CANBitTimingSet(unsigned long ulBase, tCANBitClkParms *pClkParms);extern unsigned long CANBitRateSet(unsigned long ulBase,unsigned long ulSourceClock,unsigned long ulBitRate);extern void CANDisable(unsigned long ulBase);extern void CANEnable(unsigned long ulBase);extern tBoolean CANErrCntrGet(unsigned long ulBase, unsigned long *pulRxCount,unsigned long *pulTxCount);extern void CANInit(unsigned long ulBase);extern void CANIntClear(unsigned long ulBase, unsigned long ulIntClr);extern void CANIntDisable(unsigned long ulBase, unsigned long ulIntFlags);extern void CANIntEnable(unsigned long ulBase, unsigned long ulIntFlags);extern void CANIntRegister(unsigned long ulBase, void (*pfnHandler)(void));extern unsigned long CANIntStatus(unsigned long ulBase,tCANIntStsReg eIntStsReg);extern void CANIntUnregister(unsigned long ulBase);extern void CANMessageClear(unsigned long ulBase, unsigned long ulObjID);extern void CANMessageGet(unsigned long ulBase, unsigned long ulObjID,tCANMsgObject *pMsgObject, tBoolean bClrPendingInt);extern void CANMessageSet(unsigned long ulBase, unsigned long ulObjID,tCANMsgObject *pMsgObject, tMsgObjType eMsgType);extern tBoolean CANRetryGet(unsigned long ulBase);extern void CANRetrySet(unsigned long ulBase, tBoolean bAutoRetry);extern unsigned long CANStatusGet(unsigned long ulBase, tCANStsReg eStatusReg);//*****************************************************************************//// Several CAN APIs have been renamed, with the original function name being// deprecated. These defines provide backward compatibility.////*****************************************************************************#ifndef DEPRECATED#define CANSetBitTiming(a, b) CANBitTimingSet(a, b)#define CANGetBitTiming(a, b) CANBitTimingGet(a, b)#endif//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************#endif // __CAN_H__
123version https://git-lfs.github.com/spec/v1oid sha256:46ca065b50af9f71383f4a6aafa05cc6d3776888027a20c25c42eb0a489d9976size 15635123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439//*****************************************************************************//// comp.c - Driver for the analog comparator.//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup comp_api//! @{////*****************************************************************************#include "inc/hw_comp.h"#include "inc/hw_ints.h"#include "inc/hw_memmap.h"#include "inc/hw_types.h"#include "driverlib/comp.h"#include "driverlib/debug.h"#include "driverlib/interrupt.h"//*****************************************************************************////! Configures a comparator.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator to configure.//! \param ulConfig is the configuration of the comparator.//!//! This function will configure a comparator. The \e ulConfig parameter is//! the result of a logical OR operation between the \b COMP_TRIG_xxx,//! \b COMP_INT_xxx, \b COMP_ASRCP_xxx, and \b COMP_OUTPUT_xxx values.//!//! The \b COMP_TRIG_xxx term can take on the following values://!//! - \b COMP_TRIG_NONE to have no trigger to the ADC.//! - \b COMP_TRIG_HIGH to trigger the ADC when the comparator output is high.//! - \b COMP_TRIG_LOW to trigger the ADC when the comparator output is low.//! - \b COMP_TRIG_FALL to trigger the ADC when the comparator output goes low.//! - \b COMP_TRIG_RISE to trigger the ADC when the comparator output goes//! high.//! - \b COMP_TRIG_BOTH to trigger the ADC when the comparator output goes low//! or high.//!//! The \b COMP_INT_xxx term can take on the following values://!//! - \b COMP_INT_HIGH to generate an interrupt when the comparator output is//! high.//! - \b COMP_INT_LOW to generate an interrupt when the comparator output is//! low.//! - \b COMP_INT_FALL to generate an interrupt when the comparator output goes//! low.//! - \b COMP_INT_RISE to generate an interrupt when the comparator output goes//! high.//! - \b COMP_INT_BOTH to generate an interrupt when the comparator output goes//! low or high.//!//! The \b COMP_ASRCP_xxx term can take on the following values://!//! - \b COMP_ASRCP_PIN to use the dedicated Comp+ pin as the reference//! voltage.//! - \b COMP_ASRCP_PIN0 to use the Comp0+ pin as the reference voltage (this//! the same as \b COMP_ASRCP_PIN for the comparator 0).//! - \b COMP_ASRCP_REF to use the internally generated voltage as the//! reference voltage.//!//! The \b COMP_OUTPUT_xxx term can take on the following values://!//! - \b COMP_OUTPUT_NORMAL to enable a non-inverted output from the comparator//! to a device pin.//! - \b COMP_OUTPUT_INVERT to enable an inverted output from the comparator to//! a device pin.//! - \b COMP_OUTPUT_NONE is deprecated and behaves the same as//! \b COMP_OUTPUT_NORMAL.//!//! \return None.////*****************************************************************************voidComparatorConfigure(unsigned long ulBase, unsigned long ulComp,unsigned long ulConfig){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Configure this comparator.//HWREG(ulBase + (ulComp * 0x20) + COMP_O_ACCTL0) = ulConfig;}//*****************************************************************************////! Sets the internal reference voltage.//!//! \param ulBase is the base address of the comparator module.//! \param ulRef is the desired reference voltage.//!//! This function will set the internal reference voltage value. The voltage//! is specified as one of the following values://!//! - \b COMP_REF_OFF to turn off the reference voltage//! - \b COMP_REF_0V to set the reference voltage to 0 V//! - \b COMP_REF_0_1375V to set the reference voltage to 0.1375 V//! - \b COMP_REF_0_275V to set the reference voltage to 0.275 V//! - \b COMP_REF_0_4125V to set the reference voltage to 0.4125 V//! - \b COMP_REF_0_55V to set the reference voltage to 0.55 V//! - \b COMP_REF_0_6875V to set the reference voltage to 0.6875 V//! - \b COMP_REF_0_825V to set the reference voltage to 0.825 V//! - \b COMP_REF_0_928125V to set the reference voltage to 0.928125 V//! - \b COMP_REF_0_9625V to set the reference voltage to 0.9625 V//! - \b COMP_REF_1_03125V to set the reference voltage to 1.03125 V//! - \b COMP_REF_1_134375V to set the reference voltage to 1.134375 V//! - \b COMP_REF_1_1V to set the reference voltage to 1.1 V//! - \b COMP_REF_1_2375V to set the reference voltage to 1.2375 V//! - \b COMP_REF_1_340625V to set the reference voltage to 1.340625 V//! - \b COMP_REF_1_375V to set the reference voltage to 1.375 V//! - \b COMP_REF_1_44375V to set the reference voltage to 1.44375 V//! - \b COMP_REF_1_5125V to set the reference voltage to 1.5125 V//! - \b COMP_REF_1_546875V to set the reference voltage to 1.546875 V//! - \b COMP_REF_1_65V to set the reference voltage to 1.65 V//! - \b COMP_REF_1_753125V to set the reference voltage to 1.753125 V//! - \b COMP_REF_1_7875V to set the reference voltage to 1.7875 V//! - \b COMP_REF_1_85625V to set the reference voltage to 1.85625 V//! - \b COMP_REF_1_925V to set the reference voltage to 1.925 V//! - \b COMP_REF_1_959375V to set the reference voltage to 1.959375 V//! - \b COMP_REF_2_0625V to set the reference voltage to 2.0625 V//! - \b COMP_REF_2_165625V to set the reference voltage to 2.165625 V//! - \b COMP_REF_2_26875V to set the reference voltage to 2.26875 V//! - \b COMP_REF_2_371875V to set the reference voltage to 2.371875 V//!//! \return None.////*****************************************************************************voidComparatorRefSet(unsigned long ulBase, unsigned long ulRef){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);//// Set the voltage reference voltage as requested.//HWREG(ulBase + COMP_O_ACREFCTL) = ulRef;}//*****************************************************************************////! Gets the current comparator output value.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//!//! This function retrieves the current value of the comparator output.//!//! \return Returns \b true if the comparator output is high and \b false if//! the comparator output is low.////*****************************************************************************tBooleanComparatorValueGet(unsigned long ulBase, unsigned long ulComp){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Return the appropriate value based on the comparator's present output// value.//if(HWREG(ulBase + (ulComp * 0x20) + COMP_O_ACSTAT0) & COMP_ACSTAT0_OVAL){return(true);}else{return(false);}}//*****************************************************************************////! Registers an interrupt handler for the comparator interrupt.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//! \param pfnHandler is a pointer to the function to be called when the//! comparator interrupt occurs.//!//! This sets the handler to be called when the comparator interrupt occurs.//! This will enable the interrupt in the interrupt controller; it is the//! interrupt-handler's responsibility to clear the interrupt source via//! ComparatorIntClear().//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidComparatorIntRegister(unsigned long ulBase, unsigned long ulComp,void (*pfnHandler)(void)){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Register the interrupt handler, returning an error if an error occurs.//IntRegister(INT_COMP0 + ulComp, pfnHandler);//// Enable the interrupt in the interrupt controller.//IntEnable(INT_COMP0 + ulComp);//// Enable the comparator interrupt.//HWREG(ulBase + COMP_O_ACINTEN) |= 1 << ulComp;}//*****************************************************************************////! Unregisters an interrupt handler for a comparator interrupt.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//!//! This function will clear the handler to be called when a comparator//! interrupt occurs. This will also mask off the interrupt in the interrupt//! controller so that the interrupt handler no longer is called.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidComparatorIntUnregister(unsigned long ulBase, unsigned long ulComp){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Disable the comparator interrupt.//HWREG(ulBase + COMP_O_ACINTEN) &= ~(1 << ulComp);//// Disable the interrupt in the interrupt controller.//IntDisable(INT_COMP0 + ulComp);//// Unregister the interrupt handler.//IntUnregister(INT_COMP0 + ulComp);}//*****************************************************************************////! Enables the comparator interrupt.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//!//! This function enables generation of an interrupt from the specified//! comparator. Only comparators whose interrupts are enabled can be reflected//! to the processor.//!//! \return None.////*****************************************************************************voidComparatorIntEnable(unsigned long ulBase, unsigned long ulComp){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Enable the comparator interrupt.//HWREG(ulBase + COMP_O_ACINTEN) |= 1 << ulComp;}//*****************************************************************************////! Disables the comparator interrupt.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//!//! This function disables generation of an interrupt from the specified//! comparator. Only comparators whose interrupts are enabled can be reflected//! to the processor.//!//! \return None.////*****************************************************************************voidComparatorIntDisable(unsigned long ulBase, unsigned long ulComp){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Disable the comparator interrupt.//HWREG(ulBase + COMP_O_ACINTEN) &= ~(1 << ulComp);}//*****************************************************************************////! Gets the current interrupt status.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//! \param bMasked is \b false if the raw interrupt status is required and//! \b true if the masked interrupt status is required.//!//! This returns the interrupt status for the comparator. Either the raw or//! the masked interrupt status can be returned.//!//! \return \b true if the interrupt is asserted and \b false if it is not//! asserted.////*****************************************************************************tBooleanComparatorIntStatus(unsigned long ulBase, unsigned long ulComp,tBoolean bMasked){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Return either the interrupt status or the raw interrupt status as// requested.//if(bMasked){return(((HWREG(ulBase + COMP_O_ACMIS) >> ulComp) & 1) ? true : false);}else{return(((HWREG(ulBase + COMP_O_ACRIS) >> ulComp) & 1) ? true : false);}}//*****************************************************************************////! Clears a comparator interrupt.//!//! \param ulBase is the base address of the comparator module.//! \param ulComp is the index of the comparator.//!//! The comparator interrupt is cleared, so that it no longer asserts. This//! must be done in the interrupt handler to keep it from being called again//! immediately upon exit. Note that for a level triggered interrupt, the//! interrupt cannot be cleared until it stops asserting.//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidComparatorIntClear(unsigned long ulBase, unsigned long ulComp){//// Check the arguments.//ASSERT(ulBase == COMP_BASE);ASSERT(ulComp < 3);//// Clear the interrupt.//HWREG(ulBase + COMP_O_ACMIS) = 1 << ulComp;}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:d5a6bc8bf812e1af5cff6166b2840dc48ccf3454dc5f456e6ffcfee6fbe57963size 7314123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133//*****************************************************************************//// comp.h - Prototypes for the analog comparator driver.//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __COMP_H__#define __COMP_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Values that can be passed to ComparatorConfigure() as the ulConfig// parameter. For each group (i.e. COMP_TRIG_xxx, COMP_INT_xxx, etc.), one of// the values may be selected and combined together with values from the other// groups via a logical OR.////*****************************************************************************#define COMP_TRIG_NONE 0x00000000 // No ADC trigger#define COMP_TRIG_HIGH 0x00000880 // Trigger when high#define COMP_TRIG_LOW 0x00000800 // Trigger when low#define COMP_TRIG_FALL 0x00000820 // Trigger on falling edge#define COMP_TRIG_RISE 0x00000840 // Trigger on rising edge#define COMP_TRIG_BOTH 0x00000860 // Trigger on both edges#define COMP_INT_HIGH 0x00000010 // Interrupt when high#define COMP_INT_LOW 0x00000000 // Interrupt when low#define COMP_INT_FALL 0x00000004 // Interrupt on falling edge#define COMP_INT_RISE 0x00000008 // Interrupt on rising edge#define COMP_INT_BOTH 0x0000000C // Interrupt on both edges#define COMP_ASRCP_PIN 0x00000000 // Dedicated Comp+ pin#define COMP_ASRCP_PIN0 0x00000200 // Comp0+ pin#define COMP_ASRCP_REF 0x00000400 // Internal voltage reference#ifndef DEPRECATED#define COMP_OUTPUT_NONE 0x00000000 // No comparator output#endif#define COMP_OUTPUT_NORMAL 0x00000000 // Comparator output normal#define COMP_OUTPUT_INVERT 0x00000002 // Comparator output inverted//*****************************************************************************//// Values that can be passed to ComparatorSetRef() as the ulRef parameter.////*****************************************************************************#define COMP_REF_OFF 0x00000000 // Turn off the internal reference#define COMP_REF_0V 0x00000300 // Internal reference of 0V#define COMP_REF_0_1375V 0x00000301 // Internal reference of 0.1375V#define COMP_REF_0_275V 0x00000302 // Internal reference of 0.275V#define COMP_REF_0_4125V 0x00000303 // Internal reference of 0.4125V#define COMP_REF_0_55V 0x00000304 // Internal reference of 0.55V#define COMP_REF_0_6875V 0x00000305 // Internal reference of 0.6875V#define COMP_REF_0_825V 0x00000306 // Internal reference of 0.825V#define COMP_REF_0_928125V 0x00000201 // Internal reference of 0.928125V#define COMP_REF_0_9625V 0x00000307 // Internal reference of 0.9625V#define COMP_REF_1_03125V 0x00000202 // Internal reference of 1.03125V#define COMP_REF_1_134375V 0x00000203 // Internal reference of 1.134375V#define COMP_REF_1_1V 0x00000308 // Internal reference of 1.1V#define COMP_REF_1_2375V 0x00000309 // Internal reference of 1.2375V#define COMP_REF_1_340625V 0x00000205 // Internal reference of 1.340625V#define COMP_REF_1_375V 0x0000030A // Internal reference of 1.375V#define COMP_REF_1_44375V 0x00000206 // Internal reference of 1.44375V#define COMP_REF_1_5125V 0x0000030B // Internal reference of 1.5125V#define COMP_REF_1_546875V 0x00000207 // Internal reference of 1.546875V#define COMP_REF_1_65V 0x0000030C // Internal reference of 1.65V#define COMP_REF_1_753125V 0x00000209 // Internal reference of 1.753125V#define COMP_REF_1_7875V 0x0000030D // Internal reference of 1.7875V#define COMP_REF_1_85625V 0x0000020A // Internal reference of 1.85625V#define COMP_REF_1_925V 0x0000030E // Internal reference of 1.925V#define COMP_REF_1_959375V 0x0000020B // Internal reference of 1.959375V#define COMP_REF_2_0625V 0x0000030F // Internal reference of 2.0625V#define COMP_REF_2_165625V 0x0000020D // Internal reference of 2.165625V#define COMP_REF_2_26875V 0x0000020E // Internal reference of 2.26875V#define COMP_REF_2_371875V 0x0000020F // Internal reference of 2.371875V//*****************************************************************************//// Prototypes for the APIs.////*****************************************************************************extern void ComparatorConfigure(unsigned long ulBase, unsigned long ulComp,unsigned long ulConfig);extern void ComparatorRefSet(unsigned long ulBase, unsigned long ulRef);extern tBoolean ComparatorValueGet(unsigned long ulBase, unsigned long ulComp);extern void ComparatorIntRegister(unsigned long ulBase, unsigned long ulComp,void (*pfnHandler)(void));extern void ComparatorIntUnregister(unsigned long ulBase,unsigned long ulComp);extern void ComparatorIntEnable(unsigned long ulBase, unsigned long ulComp);extern void ComparatorIntDisable(unsigned long ulBase, unsigned long ulComp);extern tBoolean ComparatorIntStatus(unsigned long ulBase, unsigned long ulComp,tBoolean bMasked);extern void ComparatorIntClear(unsigned long ulBase, unsigned long ulComp);//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __COMP_H__
123version https://git-lfs.github.com/spec/v1oid sha256:f567bcd36f64fa0d7a8910039a7b8f536fe80f68fcb3d9152a6ff26eb748752csize 5413123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189//*****************************************************************************//// cpu.c - Instruction wrappers for special CPU instructions needed by the// drivers.//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#include "../driverlib/cpu.h"//*****************************************************************************//// Wrapper function for the CPSID instruction. Returns the state of PRIMASK// on entry.////*****************************************************************************#if defined(codered) || defined(gcc) || defined(sourcerygxx)unsigned long __attribute__((naked))CPUcpsid(void){unsigned long ulRet;//// Read PRIMASK and disable interrupts.//__asm(" mrs %0, PRIMASK\n"" cpsid i\n"" bx lr\n": "=r" (ulRet));//// The return is handled in the inline assembly, but the compiler will// still complain if there is not an explicit return here (despite the fact// that this does not result in any code being produced because of the// naked attribute).//return(ulRet);}#endif#if defined(ewarm)unsigned longCPUcpsid(void){//// Read PRIMASK and disable interrupts.//__asm(" mrs r0, PRIMASK\n"" cpsid i\n");//// "Warning[Pe940]: missing return statement at end of non-void function"// is suppressed here to avoid putting a "bx lr" in the inline assembly// above and a superfluous return statement here.//#pragma diag_suppress=Pe940}#pragma diag_default=Pe940#endif#if defined(rvmdk) || defined(__ARMCC_VERSION)__asm unsigned longCPUcpsid(void){//// Read PRIMASK and disable interrupts.//mrs r0, PRIMASK;cpsid i;bx lr}#endif//*****************************************************************************//// Wrapper function for the CPSIE instruction. Returns the state of PRIMASK// on entry.////*****************************************************************************#if defined(codered) || defined(gcc) || defined(sourcerygxx)unsigned long __attribute__((naked))CPUcpsie(void){unsigned long ulRet;//// Read PRIMASK and enable interrupts.//__asm(" mrs %0, PRIMASK\n"" cpsie i\n"" bx lr\n": "=r" (ulRet));//// The return is handled in the inline assembly, but the compiler will// still complain if there is not an explicit return here (despite the fact// that this does not result in any code being produced because of the// naked attribute).//return(ulRet);}#endif#if defined(ewarm)unsigned longCPUcpsie(void){//// Read PRIMASK and enable interrupts.//__asm(" mrs r0, PRIMASK\n"" cpsie i\n");//// "Warning[Pe940]: missing return statement at end of non-void function"// is suppressed here to avoid putting a "bx lr" in the inline assembly// above and a superfluous return statement here.//#pragma diag_suppress=Pe940}#pragma diag_default=Pe940#endif#if defined(rvmdk) || defined(__ARMCC_VERSION)__asm unsigned longCPUcpsie(void){//// Read PRIMASK and enable interrupts.//mrs r0, PRIMASK;cpsie i;bx lr}#endif//*****************************************************************************//// Wrapper function for the WFI instruction.////*****************************************************************************#if defined(codered) || defined(gcc) || defined(sourcerygxx)void __attribute__((naked))CPUwfi(void){//// Wait for the next interrupt.//__asm(" wfi\n"" bx lr\n");}#endif#if defined(ewarm)voidCPUwfi(void){//// Wait for the next interrupt.//__asm(" wfi\n");}#endif#if defined(rvmdk) || defined(__ARMCC_VERSION)__asm voidCPUwfi(void){//// Wait for the next interrupt.//wfi;bx lr}#endif
123version https://git-lfs.github.com/spec/v1oid sha256:4cf77a5bddc5ebb33bb0db44e68b0064d6e5233df685c5ff789b8dbd9d5e05d5size 2332123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960//*****************************************************************************//// cpu.h - Prototypes for the CPU instruction wrapper functions.//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __CPU_H__#define __CPU_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Prototypes.////*****************************************************************************extern unsigned long CPUcpsid(void);extern unsigned long CPUcpsie(void);extern void CPUwfi(void);//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __CPU_H__
123version https://git-lfs.github.com/spec/v1oid sha256:b7fbb091f5f1b6dfa658ceb3bab8962b08c52e518199ee11c5a307884c3ec659size 25201234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556//*****************************************************************************//// debug.h - Macros for assisting debug of the driver library.//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __DEBUG_H__#define __DEBUG_H__//*****************************************************************************//// Prototype for the function that is called when an invalid argument is passed// to an API. This is only used when doing a DEBUG build.////*****************************************************************************extern void __error__(char *pcFilename, unsigned long ulLine);//*****************************************************************************//// The ASSERT macro, which does the actual assertion checking. Typically, this// will be for procedure arguments.////*****************************************************************************#ifdef DEBUG#define ASSERT(expr) { \if(!(expr)) \{ \__error__(__FILE__, __LINE__); \} \}#else#define ASSERT(expr)#endif#endif // __DEBUG_H__
123version https://git-lfs.github.com/spec/v1oid sha256:267a4afc8f3e9412dd89d04a1c7f4ab79521d49151201164f28265a48ba12fcfsize 23218123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867<?xml version="1.0" encoding="iso-8859-1"?><project><fileVersion>2</fileVersion><configuration><name>Debug</name><toolchain><name>ARM</name></toolchain><debug>1</debug><settings><name>General</name><archiveVersion>3</archiveVersion><data><version>17</version><wantNonLocal>1</wantNonLocal><debug>1</debug><option><name>ExePath</name><state>ewarm\Exe</state></option><option><name>ObjPath</name><state>ewarm\Obj</state></option><option><name>ListPath</name><state>ewarm\List</state></option><option><name>Variant</name><version>11</version><state>35</state></option><option><name>GEndianMode</name><state>0</state></option><option><name>Input variant</name><version>1</version><state>0</state></option><option><name>Input description</name><state>Full formatting.</state></option><option><name>Output variant</name><version>0</version><state>0</state></option><option><name>Output description</name><state>Full formatting.</state></option><option><name>GOutputBinary</name><state>1</state></option><option><name>FPU</name><version>0</version><state>0</state></option><option><name>OGCoreOrChip</name><state>1</state></option><option><name>GRuntimeLibSelect</name><version>0</version><state>1</state></option><option><name>GRuntimeLibSelectSlave</name><version>0</version><state>1</state></option><option><name>RTDescription</name><state>To be used with the normal configuration of the C/C++ runtime library. No locale interface, C locale, no file descriptor support, no multibytes in printf and scanf, and no hex floats in strtod.</state></option><option><name>RTConfigPath</name><state>$TOOLKIT_DIR$\INC\DLib_Config_Normal.h</state></option><option><name>OGProductVersion</name><state>5.11.0.50579</state></option><option><name>OGLastSavedByProductVersion</name><state>5.40.0.51464</state></option><option><name>GeneralEnableMisra</name><state>0</state></option><option><name>GeneralMisraVerbose</name><state>0</state></option><option><name>OGChipSelectEditMenu</name><state>LM3S101 TexasInstruments LM3S101</state></option><option><name>GenLowLevelInterface</name><state>1</state></option><option><name>GEndianModeBE</name><state>1</state></option><option><name>OGBufferedTerminalOutput</name><state>0</state></option><option><name>GenStdoutInterface</name><state>0</state></option><option><name>GeneralMisraRules98</name><version>0</version><state>1000111110110101101110011100111111101110011011000101110111101101100111111111111100110011111001110111001111111111111111111111111</state></option><option><name>GeneralMisraVer</name><state>0</state></option><option><name>GeneralMisraRules04</name><version>0</version><state>111101110010111111111000110111111111111111111111111110010111101111010101111111111111111111111111101111111011111001111011111011111111111111111</state></option></data></settings><settings><name>ICCARM</name><archiveVersion>2</archiveVersion><data><version>21</version><wantNonLocal>1</wantNonLocal><debug>1</debug><option><name>CCDefines</name><state>ewarm</state></option><option><name>CCPreprocFile</name><state>0</state></option><option><name>CCPreprocComments</name><state>0</state></option><option><name>CCPreprocLine</name><state>0</state></option><option><name>CCListCFile</name><state>0</state></option><option><name>CCListCMnemonics</name><state>0</state></option><option><name>CCListCMessages</name><state>0</state></option><option><name>CCListAssFile</name><state>0</state></option><option><name>CCListAssSource</name><state>0</state></option><option><name>CCEnableRemarks</name><state>0</state></option><option><name>CCDiagSuppress</name><state>Pa050</state></option><option><name>CCDiagRemark</name><state></state></option><option><name>CCDiagWarning</name><state></state></option><option><name>CCDiagError</name><state></state></option><option><name>CCObjPrefix</name><state>1</state></option><option><name>CCAllowList</name><version>1</version><state>1111111</state></option><option><name>CCDebugInfo</name><state>1</state></option><option><name>IEndianMode</name><state>1</state></option><option><name>IProcessor</name><state>1</state></option><option><name>IExtraOptionsCheck</name><state>0</state></option><option><name>IExtraOptions</name><state></state></option><option><name>CCLangConformance</name><state>0</state></option><option><name>CCSignedPlainChar</name><state>1</state></option><option><name>CCRequirePrototypes</name><state>0</state></option><option><name>CCMultibyteSupport</name><state>0</state></option><option><name>CCDiagWarnAreErr</name><state>0</state></option><option><name>CCCompilerRuntimeInfo</name><state>0</state></option><option><name>IFpuProcessor</name><state>1</state></option><option><name>OutputFile</name><state>$FILE_BNAME$.o</state></option><option><name>CCLangSelect</name><state>0</state></option><option><name>CCLibConfigHeader</name><state>1</state></option><option><name>PreInclude</name><state></state></option><option><name>CompilerMisraOverride</name><state>0</state></option><option><name>CCIncludePath2</name><state>$PROJ_DIR$\..</state></option><option><name>CCStdIncCheck</name><state>0</state></option><option><name>CCStdIncludePath</name><state>$TOOLKIT_DIR$\INC\</state></option><option><name>CCCodeSection</name><state>.text</state></option><option><name>IInterwork2</name><state>0</state></option><option><name>IProcessorMode2</name><state>1</state></option><option><name>CCOptLevel</name><state>3</state></option><option><name>CCOptStrategy</name><version>0</version><state>1</state></option><option><name>CCOptLevelSlave</name><state>3</state></option><option><name>CompilerMisraRules98</name><version>0</version><state>1000111110110101101110011100111111101110011011000101110111101101100111111111111100110011111001110111001111111111111111111111111</state></option><option><name>CompilerMisraRules04</name><version>0</version><state>111101110010111111111000110111111111111111111111111110010111101111010101111111111111111111111111101111111011111001111011111011111111111111111</state></option></data></settings><settings><name>AARM</name><archiveVersion>2</archiveVersion><data><version>7</version><wantNonLocal>1</wantNonLocal><debug>1</debug><option><name>AObjPrefix</name><state>1</state></option><option><name>AEndian</name><state>1</state></option><option><name>ACaseSensitivity</name><state>1</state></option><option><name>MacroChars</name><version>0</version><state>0</state></option><option><name>AWarnEnable</name><state>0</state></option><option><name>AWarnWhat</name><state>0</state></option><option><name>AWarnOne</name><state></state></option><option><name>AWarnRange1</name><state></state></option><option><name>AWarnRange2</name><state></state></option><option><name>ADebug</name><state>1</state></option><option><name>AltRegisterNames</name><state>0</state></option><option><name>ADefines</name><state>ewarm</state></option><option><name>AList</name><state>0</state></option><option><name>AListHeader</name><state>1</state></option><option><name>AListing</name><state>1</state></option><option><name>Includes</name><state>0</state></option><option><name>MacDefs</name><state>0</state></option><option><name>MacExps</name><state>1</state></option><option><name>MacExec</name><state>0</state></option><option><name>OnlyAssed</name><state>0</state></option><option><name>MultiLine</name><state>0</state></option><option><name>PageLengthCheck</name><state>0</state></option><option><name>PageLength</name><state>80</state></option><option><name>TabSpacing</name><state>8</state></option><option><name>AXRef</name><state>0</state></option><option><name>AXRefDefines</name><state>0</state></option><option><name>AXRefInternal</name><state>0</state></option><option><name>AXRefDual</name><state>0</state></option><option><name>AProcessor</name><state>1</state></option><option><name>AFpuProcessor</name><state>1</state></option><option><name>AOutputFile</name><state>$FILE_BNAME$.o</state></option><option><name>AMultibyteSupport</name><state>0</state></option><option><name>ALimitErrorsCheck</name><state>0</state></option><option><name>ALimitErrorsEdit</name><state>100</state></option><option><name>AIgnoreStdInclude</name><state>0</state></option><option><name>AStdIncludes</name><state>$TOOLKIT_DIR$\INC\</state></option><option><name>AUserIncludes</name><state></state></option><option><name>AExtraOptionsCheckV2</name><state>0</state></option><option><name>AExtraOptionsV2</name><state></state></option></data></settings><settings><name>OBJCOPY</name><archiveVersion>0</archiveVersion><data><version>1</version><wantNonLocal>1</wantNonLocal><debug>1</debug><option><name>OOCOutputFormat</name><version>2</version><state>0</state></option><option><name>OCOutputOverride</name><state>0</state></option><option><name>OOCOutputFile</name><state>driverlib.srec</state></option><option><name>OOCCommandLineProducer</name><state>1</state></option><option><name>OOCObjCopyEnable</name><state>0</state></option></data></settings><settings><name>CUSTOM</name><archiveVersion>3</archiveVersion><data><extensions></extensions><cmdline></cmdline></data></settings><settings><name>BICOMP</name><archiveVersion>0</archiveVersion><data/></settings><settings><name>BUILDACTION</name><archiveVersion>1</archiveVersion><data><prebuild></prebuild><postbuild></postbuild></data></settings><settings><name>ILINK</name><archiveVersion>0</archiveVersion><data><version>8</version><wantNonLocal>1</wantNonLocal><debug>1</debug><option><name>IlinkLibIOConfig</name><state>1</state></option><option><name>XLinkMisraHandler</name><state>0</state></option><option><name>IlinkInputFileSlave</name><state>0</state></option><option><name>IlinkOutputFile</name><state>driverlib.out</state></option><option><name>IlinkDebugInfoEnable</name><state>1</state></option><option><name>IlinkKeepSymbols</name><state></state></option><option><name>IlinkRawBinaryFile</name><state></state></option><option><name>IlinkRawBinarySymbol</name><state></state></option><option><name>IlinkRawBinarySegment</name><state></state></option><option><name>IlinkRawBinaryAlign</name><state></state></option><option><name>IlinkDefines</name><state></state></option><option><name>IlinkConfigDefines</name><state></state></option><option><name>IlinkMapFile</name><state>0</state></option><option><name>IlinkLogFile</name><state>0</state></option><option><name>IlinkLogInitialization</name><state>0</state></option><option><name>IlinkLogModule</name><state>0</state></option><option><name>IlinkLogSection</name><state>0</state></option><option><name>IlinkLogVeneer</name><state>0</state></option><option><name>IlinkIcfOverride</name><state>0</state></option><option><name>IlinkIcfFile</name><state>lnk0t.icf</state></option><option><name>IlinkIcfFileSlave</name><state></state></option><option><name>IlinkEnableRemarks</name><state>0</state></option><option><name>IlinkSuppressDiags</name><state></state></option><option><name>IlinkTreatAsRem</name><state></state></option><option><name>IlinkTreatAsWarn</name><state></state></option><option><name>IlinkTreatAsErr</name><state></state></option><option><name>IlinkWarningsAreErrors</name><state>0</state></option><option><name>IlinkUseExtraOptions</name><state>0</state></option><option><name>IlinkExtraOptions</name><state></state></option><option><name>IlinkLowLevelInterfaceSlave</name><state>1</state></option><option><name>IlinkAutoLibEnable</name><state>1</state></option><option><name>IlinkAdditionalLibs</name><state></state></option><option><name>IlinkOverrideProgramEntryLabel</name><state>0</state></option><option><name>IlinkProgramEntryLabelSelect</name><state>0</state></option><option><name>IlinkProgramEntryLabel</name><state></state></option><option><name>DoFill</name><state>0</state></option><option><name>FillerByte</name><state>0xFF</state></option><option><name>FillerStart</name><state>0x0</state></option><option><name>FillerEnd</name><state>0x0</state></option><option><name>CrcSize</name><version>0</version><state>1</state></option><option><name>CrcAlign</name><state>1</state></option><option><name>CrcAlgo</name><state>1</state></option><option><name>CrcPoly</name><state>0x11021</state></option><option><name>CrcCompl</name><version>0</version><state>0</state></option><option><name>CrcBitOrder</name><version>0</version><state>0</state></option><option><name>CrcInitialValue</name><state>0x0</state></option><option><name>DoCrc</name><state>0</state></option><option><name>IlinkBE8Slave</name><state>1</state></option><option><name>IlinkBufferedTerminalOutput</name><state>1</state></option><option><name>IlinkStdoutInterfaceSlave</name><state>1</state></option><option><name>CrcFullSize</name><state>0</state></option><option><name>IlinkIElfToolPostProcess</name><state>0</state></option></data></settings><settings><name>IARCHIVE</name><archiveVersion>0</archiveVersion><data><version>0</version><wantNonLocal>1</wantNonLocal><debug>1</debug><option><name>IarchiveInputs</name><state></state></option><option><name>IarchiveOverride</name><state>0</state></option><option><name>IarchiveOutput</name><state>C:\Work\IAR\arm2_5_xx\auxLuminary\send\examples\TexasInstruments\Stellaris\driverlib\ewarm\Exe\driverlib.a</state></option></data></settings><settings><name>BILINK</name><archiveVersion>0</archiveVersion><data/></settings></configuration><group><name>Source</name><file><name>$PROJ_DIR$\adc.c</name></file><file><name>$PROJ_DIR$\can.c</name></file><file><name>$PROJ_DIR$\comp.c</name></file><file><name>$PROJ_DIR$\cpu.c</name></file><file><name>$PROJ_DIR$\epi.c</name></file><file><name>$PROJ_DIR$\ethernet.c</name></file><file><name>$PROJ_DIR$\flash.c</name></file><file><name>$PROJ_DIR$\gpio.c</name></file><file><name>$PROJ_DIR$\hibernate.c</name></file><file><name>$PROJ_DIR$\i2c.c</name></file><file><name>$PROJ_DIR$\i2s.c</name></file><file><name>$PROJ_DIR$\interrupt.c</name></file><file><name>$PROJ_DIR$\mpu.c</name></file><file><name>$PROJ_DIR$\pwm.c</name></file><file><name>$PROJ_DIR$\qei.c</name></file><file><name>$PROJ_DIR$\ssi.c</name></file><file><name>$PROJ_DIR$\sysctl.c</name></file><file><name>$PROJ_DIR$\systick.c</name></file><file><name>$PROJ_DIR$\timer.c</name></file><file><name>$PROJ_DIR$\uart.c</name></file><file><name>$PROJ_DIR$\udma.c</name></file><file><name>$PROJ_DIR$\usb.c</name></file><file><name>$PROJ_DIR$\watchdog.c</name></file></group></project>
123version https://git-lfs.github.com/spec/v1oid sha256:feffd18ca88d9b9113c91bb3dbe76b1eb24d52fde25c339cdb2b594ca2beec97size 357711234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039//*****************************************************************************//// epi.c - Driver for the EPI module.//// Copyright (c) 2008-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#include "inc/hw_epi.h"#include "inc/hw_ints.h"#include "inc/hw_memmap.h"#include "inc/hw_types.h"#include "driverlib/debug.h"#include "driverlib/epi.h"#include "driverlib/interrupt.h"//*****************************************************************************////! \addtogroup epi_api//! @{////*****************************************************************************//*****************************************************************************////! Sets the usage mode of the EPI module.//!//! \param ulBase is the EPI module base address.//! \param ulMode is the usage mode of the EPI module.//!//! This functions sets the operating mode of the EPI module. The parameter//! \e ulMode must be one of the following://!//! - \b EPI_MODE_NONE - non-moded operation//! - \b EPI_MODE_SDRAM - use with SDRAM device//! - \b EPI_MODE_HB8 - use with host-bus 8-bit interface//! - \b EPI_MODE_DISABLE - disable the EPI module//!//! Selection of any of the above modes will enable the EPI module, except//! for \b EPI_MODE_DISABLE which should be used to disable the module.//!//! \return None.////*****************************************************************************voidEPIModeSet(unsigned long ulBase, unsigned long ulMode){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT((ulMode == EPI_MODE_NONE) ||(ulMode == EPI_MODE_SDRAM) ||(ulMode == EPI_MODE_HB8) ||(ulMode == EPI_MODE_DISABLE));//// Write the mode word to the register.//HWREG(ulBase + EPI_O_CFG) = ulMode;}//*****************************************************************************////! Sets the clock divider for the EPI module.//!//! \param ulBase is the EPI module base address.//! \param ulDivider is the value of the clock divider to be applied to//! the external interface (0-65535).//!//! This functions sets the clock divider that will be used to determine the//! clock rate of the external interface. The value is the number of high//! and low ticks of the system clock per external bus clock. A value of 0//! means that the system clock is used without any reduction. The system//! clock will be divided by the value of \e ulDivider multiplied by 2. A//! value of 1 gives a divider of 2, and value of 2 gives a divider of 4, a//! value of 3 gives a divider of 6, and so on.//!//! \return None.////*****************************************************************************voidEPIDividerSet(unsigned long ulBase, unsigned long ulDivider){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);//// Write the divider value to the register.//HWREG(ulBase + EPI_O_BAUD) = ulDivider;}//*****************************************************************************////! Configures the SDRAM mode of operation.//!//! \param ulBase is the EPI module base address.//! \param ulConfig is the SDRAM interface configuration.//! \param ulRefresh is the refresh count in core clocks (0-2047).//!//! This function is used to configure the SDRAM interface, when the SDRAM//! mode is chosen with the function EPIModeSet(). The parameter \e ulConfig//! is the logical OR of several sets of choices://!//! The processor core frequency must be specified with one of the following://!//! - \b EPI_SDRAM_CORE_FREQ_0_15 - core clock is 0 MHz < clk <= 15 MHz//! - \b EPI_SDRAM_CORE_FREQ_15_30 - core clock is 15 MHz < clk <= 30 MHz//! - \b EPI_SDRAM_CORE_FREQ_30_50 - core clock is 30 MHz < clk <= 50 MHz//! - \b EPI_SDRAM_CORE_FREQ_50_100 - core clock is 50 MHz < clk <= 100 MHz//!//! The low power mode is specified with one of the following://!//! - \b EPI_SDRAM_LOW_POWER - enter low power, self-refresh state//! - \b EPI_SDRAM_FULL_POWER - normal operating state//!//! The SDRAM device size is specified with one of the following://!//! - \b EPI_SDRAM_SIZE_64MBIT - 64 Mbit device (8 MB)//! - \b EPI_SDRAM_SIZE_128MBIT - 128 Mbit device (16 MB)//! - \b EPI_SDRAM_SIZE_256MBIT - 256 Mbit device (32 MB)//! - \b EPI_SDRAM_SIZE_512MBIT - 512 Mbit device (64 MB)//!//! The parameter \e ulRefresh sets the refresh counter in units of core//! clock ticks. It is an 11-bit value with a range of 0 - 2047 counts.//!//! \return None.////*****************************************************************************voidEPIConfigSDRAMSet(unsigned long ulBase, unsigned long ulConfig,unsigned long ulRefresh){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulRefresh < 2048);//// Fill in the refresh count field of the configuration word.//ulConfig &= ~EPI_SDRAMCFG_RFSH_M;ulConfig |= ulRefresh << EPI_SDRAMCFG_RFSH_S;//// Write the SDRAM configuration register.//HWREG(ulBase + EPI_O_SDRAMCFG) = ulConfig;}//*****************************************************************************////! Configures the interface for Host-bus 8 operation.//!//! \param ulBase is the EPI module base address.//! \param ulConfig is the interface configuration.//! \param ulMaxWait is the maximum number of external clocks to wait//! if a FIFO ready signal is holding off the transaction.//!//! This function is used to configure the interface when used in Host-bus 8//! operation as chosen with the function EPIModeSet(). The parameter//! \e ulConfig is the logical OR of any of the following://!//! - one of \b EPI_HB8_MODE_ADMUX, \b EPI_HB8_MODE_ADDEMUX,//! \b EPI_HB8_MODE_SRAM, or \b EPI_HB8_MODE_FIFO to select the HB8 mode//! - \b EPI_HB8_USE_TXEMPTY - enable TXEMPTY signal with FIFO//! - \b EPI_HB8_USE_RXFULL - enable RXFULL signal with FIFO//! - \b EPI_HB8_WRHIGH - use active high write strobe, otherwise it is//! active low//! - \b EPI_HB8_RDHIGH - use active high read strobe, otherwise it is//! active low//! - one of \b EPI_HB8_WRWAIT_0, \b EPI_HB8_WRWAIT_1, \b EPI_HB8_WRWAIT_2,//! or \b EPI_HB8_WRWAIT_3 to select the number of write wait states (default//! is 0 wait states)//! - one of \b EPI_HB8_RDWAIT_0, \b EPI_HB8_RDWAIT_1, \b EPI_HB8_RDWAIT_2,//! or \b EPI_HB8_RDWAIT_3 to select the number of read wait states (default//! is 0 wait states)//!//! The parameter \e ulMaxWait is used if the FIFO mode is chosen. If a//! FIFO is used along with RXFULL or TXEMPTY ready signals, then this//! parameter determines the maximum number of clocks to wait when the//! transaction is being held off by by the FIFO using one of these ready//! signals. A value of 0 means to wait forever.//!//! \return None.////*****************************************************************************voidEPIConfigHB8Set(unsigned long ulBase, unsigned long ulConfig,unsigned long ulMaxWait){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulMaxWait < 256);//// Fill in the max wait field of the configuration word.//ulConfig &= ~EPI_HB8CFG_MAXWAIT_M;ulConfig |= ulMaxWait << EPI_HB8CFG_MAXWAIT_S;//// Write the non-moded configuration register.//HWREG(ulBase + EPI_O_HB8CFG) = ulConfig;}//*****************************************************************************////! Configures the interface for non-moded operation.//!//! \param ulBase is the EPI module base address.//! \param ulConfig is the interface configuration.//! \param ulFrameCount is the frame size in clocks, if the frame signal//! is used (0-15).//! \param ulMaxWait is the maximum number of external clocks to wait//! when the external clock enable is holding off the transaction (0-255).//!//! This function is used to configure the interface when used in non-moded//! operation as chosen with the function EPIModeSet(). The parameter//! \e ulConfig is the logical OR of any of the following://!//! - \b EPI_NONMODE_CLKPIN - interface clock is output on a pin//! - \b EPI_NONMODE_CLKSTOP - clock is stopped when there is no transaction,//! otherwise it is free-running//! - \b EPI_NONMODE_CLKENA - enable the clock enable input from the device//! - \b EPI_NONMODE_FRAMEPIN - framing signal is emitted on a pin//! - \b EPI_NONMODE_FRAME50 - framing signal is 50/50 duty cycle, otherwise it//! is a pulse//! - \b EPI_NONMODE_READWRITE - read and write strobes are emitted on pins//! - \b EPI_NONMODE_WRITE2CYCLE - a two cycle write is used, otherwise a//! single-cycle write is used//! - \b EPI_NONMODE_READ2CYCLE - a two cycle read is used, otherwise a//! single-cycle read is used//! - \b EPI_NONMODE_ASIZE_NONE, \b EPI_NONMODE_ASIZE_4,//! \b EPI_NONMODE_ASIZE_12, or \b EPI_NONMODE_ASIZE_20 to choose no address//! bus, or and address bus size of 4, 12, or 20 bits//! - \b EPI_NONMODE_DSIZE_8, \b EPI_NONMODE_DSIZE_16,//! \b EPI_NONMODE_DSIZE_24, or \b EPI_NONMODE_DSIZE_32 to select a data bus//! size of 8, 16, 24, or 32 bits//!//! The parameter \e ulFrameCount is the number of clocks used to form the//! framing signal, if the framing signal is used. The behavior depends on//! whether the frame signal is a pulse or a 50/50 duty cycle. This value//! is not used if the framing signal is not enabled with the option//! \b EPI_NONMMODE_FRAMEPIN.//!//! The parameter \e ulMaxWait is used if the external clock enable is turned//! on with the \b EPI_NONMODE_CLKENA option is used. In the case that//! external clock enable is used, this parameter determines the maximum//! number of clocks to wait when the external clock enable signal is holding//! off a transaction. A value of 0 means to wait forever. If a non-zero//! value is used and exceeded, an interrupt will occur and the transaction//! aborted.//!//! \return None.////*****************************************************************************voidEPIConfigNoModeSet(unsigned long ulBase, unsigned long ulConfig,unsigned long ulFrameCount, unsigned long ulMaxWait){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulFrameCount < 16);ASSERT(ulMaxWait < 256);//// Fill in the frame count field of the configuration word.//ulConfig &= ~EPI_GPCFG_FRMCNT_M;ulConfig |= ulFrameCount << EPI_GPCFG_FRMCNT_S;//// Fill in the max wait field of the configuration word.//ulConfig &= ~EPI_GPCFG_MAXWAIT_M;ulConfig |= ulMaxWait << EPI_GPCFG_MAXWAIT_S;//// Write the non-moded configuration register.//HWREG(ulBase + EPI_O_GPCFG) = ulConfig;}//*****************************************************************************////! Configures the address map for the external interface.//!//! \param ulBase is the EPI module base address.//! \param ulMap is the address mapping configuration.//!//! This function is used to configure the address mapping for the external//! interface. This determines the base address of the external memory or//! device within the processor peripheral and/or memory space.//!//! The parameter \e ulMap is the logical OR of the following://!//! - \b EPI_ADDR_PER_SIZE_256B, \b EPI_ADDR_PER_SIZE_64KB,//! \b EPI_ADDR_PER_SIZE_16MB, or \b EPI_ADDR_PER_SIZE_512MB to choose a//! peripheral address space of 256 bytes, 64 Kbytes, 16 Mbytes or 512 Mbytes//! - \b EPI_ADDR_PER_BASE_NONE, \b EPI_ADDR_PER_BASE_A, or//! \b EPI_ADDR_PER_BASE_C to choose the base address of the peripheral//! space as none, 0xA0000000, or 0xC0000000//! - \b EPI_ADDR_RAM_SIZE_256B, \b EPI_ADDR_RAM_SIZE_64KB,//! \b EPI_ADDR_RAM_SIZE_16MB, or \b EPI_ADDR_RAM_SIZE_512MB to choose a//! RAM address space of 256 bytes, 64 Kbytes, 16 Mbytes or 512 Mbytes//! - \b EPI_ADDR_RAM_BASE_NONE, \b EPI_ADDR_RAM_BASE_6, or//! \b EPI_ADDR_RAM_BASE_8 to choose the base address of the RAM space//! as none, 0x60000000, or 0x80000000//!//! \return None.////*****************************************************************************voidEPIAddressMapSet(unsigned long ulBase, unsigned long ulMap){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulMap < 0x100);//// Set the value of the address mapping register.//HWREG(ulBase + EPI_O_ADDRMAP) = ulMap;}//*****************************************************************************////! Configures a non-blocking read transaction.//!//! \param ulBase is the EPI module base address.//! \param ulChannel is the read channel (0 or 1).//! \param ulDataSize is the size of the data items to read.//! \param ulAddress is the starting address to read.//!//! This function is used to configure a non-blocking read channel for a//! transaction. Two channels are available which can be used in a ping-pong//! method for continuous reading. It is not necessary to use both channels//! to perform a non-blocking read.//!//! The parameter \e ulDataSize is one of \b EPI_NBCONFIG_SIZE_8,//! \b EPI_NBCONFIG_SIZE_16, or \b EPI_NBCONFIG_SIZE_32 for 8-bit, 16-bit,//! or 32-bit sized data transfers.//!//! The parameter \e ulAddress is the starting address for the read, relative//! to the external device. The start of the device is address 0.//!//! Once configured, the non-blocking read is started by calling//! EPINonBlockingReadStart(). If the addresses to be read from the device//! are in a sequence, it is not necessary to call this function multiple//! times. Until it is changed, the EPI module will remember the last address//! that was used for a non-blocking read (per channel).//!//! \return None.////*****************************************************************************voidEPINonBlockingReadConfigure(unsigned long ulBase, unsigned long ulChannel,unsigned long ulDataSize, unsigned long ulAddress){unsigned long ulOffset;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulChannel < 2);ASSERT(ulDataSize < 4);ASSERT(ulAddress < 0x20000000);//// Compute the offset needed to select the correct channel regs.//ulOffset = ulChannel * (EPI_O_RSIZE1 - EPI_O_RSIZE0);//// Write the data size register for the channel.//HWREG(ulBase + EPI_O_RSIZE0 + ulOffset) = ulDataSize;//// Write the starting address register for the channel.//HWREG(ulBase + EPI_O_RADDR0 + ulOffset) = ulAddress;}//*****************************************************************************////! Starts a non-blocking read transaction.//!//! \param ulBase is the EPI module base address.//! \param ulChannel is the read channel (0 or 1).//! \param ulCount is the number of items to read (1-4095).//!//! This function starts a non-blocking read that was previously configured//! with the function EPINonBlockingReadConfigure(). Once this function is//! called, the EPI module will begin reading data from the external device//! into the read FIFO. The EPI will stop reading when the FIFO fills up//! and resume reading when the application drains the FIFO, until the//! total specified count of data items has been read.//!//! Once a read transaction is completed and the FIFO drained, another//! transaction can be started from the next address by calling this//! function again.//!//! \return None.////*****************************************************************************voidEPINonBlockingReadStart(unsigned long ulBase, unsigned long ulChannel,unsigned long ulCount){unsigned long ulOffset;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulChannel < 2);ASSERT(ulCount < 4096);//// Compute the offset needed to select the correct channel regs.//ulOffset = ulChannel * (EPI_O_RPSTD1 - EPI_O_RPSTD0);//// Write to the read count register.//HWREG(ulBase + EPI_O_RPSTD0 + ulOffset) = ulCount;}//*****************************************************************************////! Stops a non-blocking read transaction.//!//! \param ulBase is the EPI module base address.//! \param ulChannel is the read channel (0 or 1).//!//! This function cancels a non-blocking read transaction that is already//! in progress.//!//! \return None.////*****************************************************************************voidEPINonBlockingReadStop(unsigned long ulBase, unsigned long ulChannel){unsigned long ulOffset;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulChannel < 2);//// Compute the offset needed to select the correct channel regs.//ulOffset = ulChannel * (EPI_O_RPSTD1 - EPI_O_RPSTD0);//// Write a 0 to the read count register, which will cancel the transaction.//HWREG(ulBase + EPI_O_RPSTD0 + ulOffset) = 0;}//*****************************************************************************////! Get the count remaining for a non-blocking transaction.//!//! \param ulBase is the EPI module base address.//! \param ulChannel is the read channel (0 or 1).//!//! This function gets the remaining count of items for a non-blocking read//! transaction.//!//! \return The number of items remaining in the non-blocking read transaction.////*****************************************************************************unsigned longEPINonBlockingReadCount(unsigned long ulBase, unsigned long ulChannel){unsigned long ulOffset;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulChannel < 2);//// Compute the offset needed to select the correct channel regs.//ulOffset = ulChannel * (EPI_O_RPSTD1 - EPI_O_RPSTD0);//// Read the count remaining and return the value to the caller.//return(HWREG(ulBase + EPI_O_RPSTD0 + ulOffset));}//*****************************************************************************////! Get the count of items available in the read FIFO.//!//! \param ulBase is the EPI module base address.//!//! This function gets the number of items that are available to read in//! the read FIFO. The read FIFO is filled by a non-blocking read transaction//! which is configured by the functions EPINonBlockingReadConfigure() and//! EPINonBlockingReadStart().//!//! \return The number of items available to read in the read FIFO.////*****************************************************************************unsigned longEPINonBlockingReadAvail(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);//// Read the FIFO count and return it to the caller.//return(HWREG(ulBase + EPI_O_RFIFOCNT));}//*****************************************************************************////! Read available data from the read FIFO, as 32-bit data items.//!//! \param ulBase is the EPI module base address.//! \param ulCount is the maximum count of items to read.//! \param pulBuf is the caller supplied buffer where the read data should//! be stored.//!//! This function reads 32-bit data items from the read FIFO and stores//! the values in a caller supplied buffer. The function will read and store//! data from the FIFO until there is no more data in the FIFO or the maximum//! count is reached as specified in the parameter \e ulCount. The actual//! count of items will be returned.//!//! \return The number of items read from the FIFO.////*****************************************************************************unsigned longEPINonBlockingReadGet32(unsigned long ulBase, unsigned long ulCount,unsigned long *pulBuf){unsigned long ulCountRead = 0;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulCount < 4096);ASSERT(pulBuf);//// Read from the FIFO while there are any items to read, and// the callers specified count is not exceeded.//while(HWREG(ulBase + EPI_O_RFIFOCNT) && ulCount--){//// Read from the FIFO and store in the caller supplied buffer.//*pulBuf = HWREG(ulBase + EPI_O_READFIFO);//// Update the caller's buffer pointer and the count of items read.//pulBuf++;ulCountRead++;}//// Return the count of items read to the caller.//return(ulCountRead);}//*****************************************************************************////! Read available data from the read FIFO, as 16-bit data items.//!//! \param ulBase is the EPI module base address.//! \param ulCount is the maximum count of items to read.//! \param pusBuf is the caller supplied buffer where the read data should//! be stored.//!//! This function reads 16-bit data items from the read FIFO and stores//! the values in a caller supplied buffer. The function will read and store//! data from the FIFO until there is no more data in the FIFO or the maximum//! count is reached as specified in the parameter \e ulCount. The actual//! count of items will be returned.//!//! \return The number of items read from the FIFO.////*****************************************************************************unsigned longEPINonBlockingReadGet16(unsigned long ulBase, unsigned long ulCount,unsigned short *pusBuf){unsigned long ulCountRead = 0;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulCount < 4096);ASSERT(pusBuf);//// Read from the FIFO while there are any items to read, and// the callers specified count is not exceeded.//while(HWREG(ulBase + EPI_O_RFIFOCNT) && ulCount--){//// Read from the FIFO and store in the caller supplied buffer.//*pusBuf = (unsigned short)HWREG(ulBase + EPI_O_READFIFO);//// Update the caller's buffer pointer and the count of items read.//pusBuf++;ulCountRead++;}//// Return the count of items read to the caller.//return(ulCountRead);}//*****************************************************************************////! Read available data from the read FIFO, as 8-bit data items.//!//! \param ulBase is the EPI module base address.//! \param ulCount is the maximum count of items to read.//! \param pucBuf is the caller supplied buffer where the read data should//! be stored.//!//! This function reads 8-bit data items from the read FIFO and stores//! the values in a caller supplied buffer. The function will read and store//! data from the FIFO until there is no more data in the FIFO or the maximum//! count is reached as specified in the parameter \e ulCount. The actual//! count of items will be returned.//!//! \return The number of items read from the FIFO.////*****************************************************************************unsigned longEPINonBlockingReadGet8(unsigned long ulBase, unsigned long ulCount,unsigned char *pucBuf){unsigned long ulCountRead = 0;//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulCount < 4096);ASSERT(pucBuf);//// Read from the FIFO while there are any items to read, and// the callers specified count is not exceeded.//while(HWREG(ulBase + EPI_O_RFIFOCNT) && ulCount--){//// Read from the FIFO and store in the caller supplied buffer.//*pucBuf = (unsigned char)HWREG(ulBase + EPI_O_READFIFO);//// Update the caller's buffer pointer and the count of items read.//pucBuf++;ulCountRead++;}//// Return the count of items read to the caller.//return(ulCountRead);}//*****************************************************************************////! Configures the read FIFO.//!//! \param ulBase is the EPI module base address.//! \param ulConfig is the FIFO configuration.//!//! This function configures the FIFO trigger levels and error//! generation. The parameter \e ulConfig is the logical OR of the//! following://!//! - \b EPI_FIFO_CONFIG_WTFULLERR - enables an error interrupt when a write is//! attempted and the write FIFO is full//! - \b EPI_FIFO_CONFIG_RSTALLERR - enables an error interrupt when a read is//! stalled due to an interleaved write or other reason//! - \b EPI_FIFO_CONFIG_TX_EMPTY, \b EPI_FIFO_CONFIG_TX_1_4,//! \b EPI_FIFO_CONFIG_TX_1_2, or \b EPI_FIFO_CONFIG_TX_3_4 to set the//! TX FIFO trigger level to empty, 1/4, 1/2, or 3/4 level//! - \b EPI_FIFO_CONFIG_RX_1_8, \b EPI_FIFO_CONFIG_RX_1_4,//! \b EPI_FIFO_CONFIG_RX_1_2, \b EPI_FIFO_CONFIG_RX_3_4,//! \b EPI_FIFO_CONFIG_RX_7_8, or \b EPI_FIFO_CONFIG_RX_FULL to set the//! RX FIFO trigger level to 1/8, 1/4, 1/2, 3/4, 7/8 or full level//!//! \return None.////*****************************************************************************voidEPIFIFOConfig(unsigned long ulBase, unsigned long ulConfig){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulConfig == (ulConfig & 0x00030077));//// Load the configuration into the FIFO config reg.//HWREG(ulBase + EPI_O_FIFOLVL) = ulConfig;}//*****************************************************************************////! Reads the number of empty slots in the write transaction FIFO.//!//! \param ulBase is the EPI module base address.//!//! This function returns the number of slots available in the transaction//! FIFO. It can be used in a polling method to avoid attempting a write//! that would stall.//!//! \return The number of empty slots in the transaction FIFO.////*****************************************************************************unsigned longEPINonBlockingWriteCount(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);//// Read the FIFO count and return it to the caller.//return(HWREG(ulBase + EPI_O_WFIFOCNT));}//*****************************************************************************////! Enables EPI interrupt sources.//!//! \param ulBase is the EPI module base address.//! \param ulIntFlags is a bit mask of the interrupt sources to be enabled.//!//! This function enables the specified EPI sources to generate interrupts.//! The \e ulIntFlags parameter can be the logical OR of any of the following//! values://!//! - \b EPI_INT_TXREQ - transmit FIFO is below the trigger level//! - \b EPI_INT_RXREQ - read FIFO is above the trigger level//! - \b EPI_INT_ERR - an error condition occurred//!//! \return Returns None.////*****************************************************************************voidEPIIntEnable(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulIntFlags < 16);//// Write the interrupt flags mask to the mask register.//HWREG(ulBase + EPI_O_IM) |= ulIntFlags;}//*****************************************************************************////! Disables EPI interrupt sources.//!//! \param ulBase is the EPI module base address.//! \param ulIntFlags is a bit mask of the interrupt sources to be disabled.//!//! This function disables the specified EPI sources for interrupt//! generation. The \e ulIntFlags parameter can be the logical OR//! of any of the following values: \b EPI_INT_RXREQ, \b EPI_INT_TXREQ, or//! \b I2S_INT_ERR.//!//! \return Returns None.////*****************************************************************************voidEPIIntDisable(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulIntFlags < 16);//// Write the interrupt flags mask to the mask register.//HWREG(ulBase + EPI_O_IM) &= ~ulIntFlags;}//*****************************************************************************////! Gets the EPI interrupt status.//!//! \param ulBase is the EPI module base address.//! \param bMasked is set \b true to get the masked interrupt status, or//! \b false to get the raw interrupt status.//!//! This function returns the EPI interrupt status. It can return either//! the raw or masked interrupt status.//!//! \return Returns the masked or raw EPI interrupt status, as a bit field//! of any of the following values: \b EPI_INT_TXREQ, \b EPI_INT_RXREQ,//! or \b EPI_INT_ERR////*****************************************************************************unsigned longEPIIntStatus(unsigned long ulBase, tBoolean bMasked){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);//// Return either the interrupt status or the raw interrupt status as// requested.//if(bMasked){return(HWREG(ulBase + EPI_O_MIS));}else{return(HWREG(ulBase + EPI_O_RIS));}}//*****************************************************************************////! Gets the EPI error interrupt status.//!//! \param ulBase is the EPI module base address.//!//! This function returns the error status of the EPI. If the return value of//! the function EPIIntStatus() has the flag \b EPI_INT_ERR set, then this//! function can be used to determine the cause of the error.//!//! This function returns a bit mask of error flags, which can be the logical//! OR of any of the following://!//! - \b EPI_INT_ERR_WTFULL - occurs when a write stalled when the transaction//! FIFO was full//! - \b EPI_INT_ERR_RSTALL - occurs when a read stalled//! - \b EPI_INT_ERR_TIMEOUT - occurs when the external clock enable held//! off a transaction longer than the configured maximum wait time//!//! \return Returns the interrupt error flags as the logical OR of any of//! the following: \b EPI_INT_ERR_WTFULL, \b EPI_INT_ERR_RSTALL, or//! \b EPI_INT_ERR_TIMEOUT.////*****************************************************************************unsigned longEPIIntErrorStatus(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);//// Read the error status and return to caller.//return(HWREG(ulBase + EPI_O_EISC));}//*****************************************************************************////! Clears pending EPI error sources.//!//! \param ulBase is the EPI module base address.//! \param ulErrFlags is a bit mask of the error sources to be cleared.//!//! This function clears the specified pending EPI errors. The \e ulErrFlags//! parameter can be the logical OR of any of the following values://! \b EPI_INT_ERR_WTFULL, \b EPI_INT_ERR_RSTALL, or \b EPI_INT_ERR_TIMEOUT.//!//! \return Returns None.////*****************************************************************************voidEPIIntErrorClear(unsigned long ulBase, unsigned long ulErrFlags){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(ulErrFlags < 16);//// Write the error flags to the register to clear the pending errors.//HWREG(ulBase + EPI_O_EISC) = ulErrFlags;}//*****************************************************************************////! Registers an interrupt handler for the EPI module.//!//! \param ulBase is the EPI module base address.//! \param pfnHandler is a pointer to the function to be called when the//! interrupt is activated.//!//! This sets and enables the handler to be called when the EPI module//! generates an interrupt. Specific EPI interrupts must still be enabled//! with the EPIIntEnable() function.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidEPIIntRegister(unsigned long ulBase, void (*pfnHandler)(void)){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);ASSERT(pfnHandler);//// Register the interrupt handler.//IntRegister(INT_EPI0, pfnHandler);//// Enable the EPI interface interrupt.//IntEnable(INT_EPI0);}//*****************************************************************************////! Unregisters an interrupt handler for the EPI module.//!//! \param ulBase is the EPI module base address.//!//! This function will disable and clear the handler to be called when the//! EPI interrupt occurs.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidEPIIntUnregister(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == EPI0_BASE);//// Disable the EPI interface interrupt.//IntDisable(INT_EPI0);//// Unregister the interrupt handler.//IntUnregister(INT_EPI0);}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:df27c17b300ef9bd4709a5adb7019c2b1ca27c1583acfd53649481076672a750size 10827123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229//*****************************************************************************//// epi.h - Prototypes and macros for the EPI module.//// Copyright (c) 2008-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __EPI_H__#define __EPI_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Values that can be passed to EPIModeSet()////*****************************************************************************#define EPI_MODE_NONE 0x00000010#define EPI_MODE_SDRAM 0x00000011#define EPI_MODE_HB8 0x00000012#define EPI_MODE_DISABLE 0x00000000//*****************************************************************************//// Values that can be passed to EPIConfigSDRAMSet()////*****************************************************************************#define EPI_SDRAM_CORE_FREQ_0_15 0x00000000#define EPI_SDRAM_CORE_FREQ_15_30 0x40000000#define EPI_SDRAM_CORE_FREQ_30_50 0x80000000#define EPI_SDRAM_CORE_FREQ_50_100 0xC0000000#define EPI_SDRAM_LOW_POWER 0x00000200#define EPI_SDRAM_FULL_POWER 0x00000000#define EPI_SDRAM_SIZE_64MBIT 0x00000000#define EPI_SDRAM_SIZE_128MBIT 0x00000001#define EPI_SDRAM_SIZE_256MBIT 0x00000002#define EPI_SDRAM_SIZE_512MBIT 0x00000003//*****************************************************************************//// Values that can be passed to EPIConfigNoModeSet()////*****************************************************************************#define EPI_NONMODE_CLKPIN 0x80000000#define EPI_NONMODE_CLKSTOP 0x40000000#define EPI_NONMODE_CLKENA 0x10000000#define EPI_NONMODE_FRAMEPIN 0x08000000#define EPI_NONMODE_FRAME50 0x04000000#define EPI_NONMODE_READWRITE 0x00200000#define EPI_NONMODE_WRITE2CYCLE 0x00080000#define EPI_NONMODE_READ2CYCLE 0x00040000#define EPI_NONMODE_ASIZE_NONE 0x00000000#define EPI_NONMODE_ASIZE_4 0x00000010#define EPI_NONMODE_ASIZE_12 0x00000020#define EPI_NONMODE_ASIZE_20 0x00000030#define EPI_NONMODE_DSIZE_8 0x00000000#define EPI_NONMODE_DSIZE_16 0x00000001#define EPI_NONMODE_DSIZE_24 0x00000002#define EPI_NONMODE_DSIZE_32 0x00000003//*****************************************************************************//// Values that can be passed to EPIConfigHB8ModeSet()////*****************************************************************************#define EPI_HB8_USE_TXEMPTY 0x00800000#define EPI_HB8_USE_RXFULL 0x00400000#define EPI_HB8_WRHIGH 0x00200000#define EPI_HB8_RDHIGH 0x00100000#define EPI_HB8_WRWAIT_0 0x00000000#define EPI_HB8_WRWAIT_1 0x00000040#define EPI_HB8_WRWAIT_2 0x00000080#define EPI_HB8_WRWAIT_3 0x000000C0#define EPI_HB8_RDWAIT_0 0x00000000#define EPI_HB8_RDWAIT_1 0x00000010#define EPI_HB8_RDWAIT_2 0x00000020#define EPI_HB8_RDWAIT_3 0x00000030#define EPI_HB8_MODE_ADMUX 0x00000000#define EPI_HB8_MODE_ADDEMUX 0x00000001#define EPI_HB8_MODE_SRAM 0x00000002#define EPI_HB8_MODE_FIFO 0x00000003//*****************************************************************************//// Values that can be passed to EPIConfigSDRAMSet()////*****************************************************************************#define EPI_ADDR_PER_SIZE_256B 0x00000000#define EPI_ADDR_PER_SIZE_64KB 0x00000040#define EPI_ADDR_PER_SIZE_16MB 0x00000080#define EPI_ADDR_PER_SIZE_512MB 0x000000C0#define EPI_ADDR_PER_BASE_NONE 0x00000000#define EPI_ADDR_PER_BASE_A 0x00000010#define EPI_ADDR_PER_BASE_C 0x00000020#define EPI_ADDR_RAM_SIZE_256B 0x00000000#define EPI_ADDR_RAM_SIZE_64KB 0x00000004#define EPI_ADDR_RAM_SIZE_16MB 0x00000008#define EPI_ADDR_RAM_SIZE_512MB 0x0000000C#define EPI_ADDR_RAM_BASE_NONE 0x00000000#define EPI_ADDR_RAM_BASE_6 0x00000001#define EPI_ADDR_RAM_BASE_8 0x00000002//*****************************************************************************//// Values that can be passed to EPINonBlockingReadConfigure()////*****************************************************************************#define EPI_NBCONFIG_SIZE_8 1#define EPI_NBCONFIG_SIZE_16 2#define EPI_NBCONFIG_SIZE_32 3//*****************************************************************************//// Values that can be passed to EPIFIFOConfig()////*****************************************************************************#define EPI_FIFO_CONFIG_WTFULLERR 0x00020000#define EPI_FIFO_CONFIG_RSTALLERR 0x00010000#define EPI_FIFO_CONFIG_TX_EMPTY 0x00000000#define EPI_FIFO_CONFIG_TX_1_4 0x00000020#define EPI_FIFO_CONFIG_TX_1_2 0x00000030#define EPI_FIFO_CONFIG_TX_3_4 0x00000040#define EPI_FIFO_CONFIG_RX_1_8 0x00000001#define EPI_FIFO_CONFIG_RX_1_4 0x00000002#define EPI_FIFO_CONFIG_RX_1_2 0x00000003#define EPI_FIFO_CONFIG_RX_3_4 0x00000004#define EPI_FIFO_CONFIG_RX_7_8 0x00000005#define EPI_FIFO_CONFIG_RX_FULL 0x00000006//*****************************************************************************//// Values that can be passed to EPIIntEnable(), EPIIntDisable(), or returned// as flags from EPIIntStatus()////*****************************************************************************#define EPI_INT_TXREQ 0x00000004#define EPI_INT_RXREQ 0x00000002#define EPI_INT_ERR 0x00000001//*****************************************************************************//// Values that can be passed to EPIIntErrorClear(), or returned as flags from// EPIIntErrorStatus()////*****************************************************************************#define EPI_INT_ERR_WTFULL 0x00000004#define EPI_INT_ERR_RSTALL 0x00000002#define EPI_INT_ERR_TIMEOUT 0x00000001//*****************************************************************************//// API Function prototypes////*****************************************************************************void EPIModeSet(unsigned long ulBase, unsigned long ulMode);void EPIDividerSet(unsigned long ulBase, unsigned long ulDivider);void EPIConfigSDRAMSet(unsigned long ulBase, unsigned long ulConfig,unsigned long ulRefresh);void EPIConfigNoModeSet(unsigned long ulBase, unsigned long ulConfig,unsigned long ulFrameCount, unsigned long ulMaxWait);void EPIConfigHB8Set(unsigned long ulBase, unsigned long ulConfig,unsigned long ulMaxWait);void EPIAddressMapSet(unsigned long ulBase, unsigned long ulMap);void EPINonBlockingReadConfigure(unsigned long ulBase, unsigned long ulChannel,unsigned long ulDataSize, unsigned long ulAddress);void EPINonBlockingReadStart(unsigned long ulBase, unsigned long ulChannel,unsigned long ulCount);void EPINonBlockingReadStop(unsigned long ulBase, unsigned long ulChannel);unsigned long EPINonBlockingReadCount(unsigned long ulBase,unsigned long ulChannel);unsigned long EPINonBlockingReadAvail(unsigned long ulBase);unsigned long EPINonBlockingReadGet32(unsigned long ulBase,unsigned long ulCount,unsigned long *pulBuf);unsigned long EPINonBlockingReadGet16(unsigned long ulBase,unsigned long ulCount,unsigned short *pusBuf);unsigned long EPINonBlockingReadGet8(unsigned long ulBase,unsigned long ulCount,unsigned char *pucBuf);void EPIFIFOConfig(unsigned long ulBase, unsigned long ulConfig);unsigned long EPINonBlockingWriteCount(unsigned long ulBase);void EPIIntEnable(unsigned long ulBase, unsigned long ulIntFlags);void EPIIntDisable(unsigned long ulBase, unsigned long ulIntFlags);unsigned long EPIIntStatus(unsigned long ulBase, tBoolean bMasked);unsigned long EPIIntErrorStatus(unsigned long ulBase);void EPIIntErrorClear(unsigned long ulBase, unsigned long ulErrFlags);void EPIIntRegister(unsigned long ulBase, void (*pfnHandler)(void));void EPIIntUnregister(unsigned long ulBase);//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __EPI_H__
123version https://git-lfs.github.com/spec/v1oid sha256:d09d94078945f778517672ab455279d3bae1d58fb4b371cf7e78507989292810size 4555012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280//*****************************************************************************//// ethernet.c - Driver for the Integrated Ethernet Controller//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup ethernet_api//! @{////*****************************************************************************#include "inc/hw_ethernet.h"#include "inc/hw_ints.h"#include "inc/hw_memmap.h"#include "inc/hw_types.h"#include "driverlib/debug.h"#include "driverlib/ethernet.h"#include "driverlib/interrupt.h"//*****************************************************************************////! Initializes the Ethernet controller for operation.//!//! \param ulBase is the base address of the controller.//! \param ulEthClk is the rate of the clock supplied to the Ethernet module.//!//! This function will prepare the Ethernet controller for first time use in//! a given hardware/software configuration. This function should be called//! before any other Ethernet API functions are called.//!//! The peripheral clock will be the same as the processor clock. This will be//! the value returned by SysCtlClockGet(), or it can be explicitly hard-coded//! if it is constant and known (to save the code/execution overhead of a call//! to SysCtlClockGet()).//!//! This function replaces the original EthernetInit() API and performs the//! same actions. A macro is provided in <tt>ethernet.h</tt> to map the//! original API to this API.//!//! \note If the device configuration is changed (for example, the system clock//! is reprogrammed to a different speed), then the Ethernet controller must be//! disabled by calling the EthernetDisable() function and the controller must//! be reinitialized by calling the EthernetInitExpClk() function again. After//! the controller has been reinitialized, the controller should be//! reconfigured using the appropriate Ethernet API calls.//!//! \return None.////*****************************************************************************voidEthernetInitExpClk(unsigned long ulBase, unsigned long ulEthClk){unsigned long ulDiv;//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Set the Management Clock Divider register for access to the PHY// register set (via EthernetPHYRead/Write).//// The MDC clock divided down from the system clock using the following// formula. A maximum of 2.5MHz is allowed for F(mdc).//// F(mdc) = F(sys) / (2 * (div + 1))// div = (F(sys) / (2 * F(mdc))) - 1// div = (F(sys) / 2 / F(mdc)) - 1//// Note: Because we should round up, to ensure we don't violate the// maximum clock speed, we can simplify this as follows://// div = F(sys) / 2 / F(mdc)//// For example, given a system clock of 6.0MHz, and a div value of 1,// the mdc clock would be programmed as 1.5 MHz.//ulDiv = (ulEthClk / 2) / 2500000;HWREG(ulBase + MAC_O_MDV) = (ulDiv & MAC_MDV_DIV_M);}//*****************************************************************************////! Sets the configuration of the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param ulConfig is the configuration for the controller.//!//! After the EthernetInitExpClk() function has been called, this API function//! can be used to configure the various features of the Ethernet controller.//!//! The Ethernet controller provides three control registers that are used//! to configure the controller's operation. The transmit control register//! provides settings to enable full duplex operation, to auto-generate the//! frame check sequence, and to pad the transmit packets to the minimum//! length as required by the IEEE standard. The receive control register//! provides settings to enable reception of packets with bad frame check//! sequence values and to enable multi-cast or promiscuous modes. The//! timestamp control register provides settings that enable support logic in//! the controller that allow the use of the General Purpose Timer 3 to capture//! timestamps for the transmitted and received packets.//!//! The \e ulConfig parameter is the logical OR of the following values://!//! - \b ETH_CFG_TS_TSEN - Enable TX and RX interrupt status as CCP timer//! inputs//! - \b ETH_CFG_RX_BADCRCDIS - Disable reception of packets with a bad CRC//! - \b ETH_CFG_RX_PRMSEN - Enable promiscuous mode reception (all packets)//! - \b ETH_CFG_RX_AMULEN - Enable reception of multicast packets//! - \b ETH_CFG_TX_DPLXEN - Enable full duplex transmit mode//! - \b ETH_CFG_TX_CRCEN - Enable transmit with auto CRC generation//! - \b ETH_CFG_TX_PADEN - Enable padding of transmit data to minimum size//!//! These bit-mapped values are programmed into the transmit, receive, and/or//! timestamp control register.//!//! \return None.////*****************************************************************************voidEthernetConfigSet(unsigned long ulBase, unsigned long ulConfig){unsigned long ulTemp;//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT((ulConfig & ~(ETH_CFG_TX_DPLXEN | ETH_CFG_TX_CRCEN |ETH_CFG_TX_PADEN | ETH_CFG_RX_BADCRCDIS |ETH_CFG_RX_PRMSEN | ETH_CFG_RX_AMULEN |ETH_CFG_TS_TSEN)) == 0);//// Setup the Transmit Control Register.//ulTemp = HWREG(ulBase + MAC_O_TCTL);ulTemp &= ~(MAC_TCTL_DUPLEX | MAC_TCTL_CRC | MAC_TCTL_PADEN);ulTemp |= ulConfig & 0x0FF;HWREG(ulBase + MAC_O_TCTL) = ulTemp;//// Setup the Receive Control Register.//ulTemp = HWREG(ulBase + MAC_O_RCTL);ulTemp &= ~(MAC_RCTL_BADCRC | MAC_RCTL_PRMS | MAC_RCTL_AMUL);ulTemp |= (ulConfig >> 8) & 0x0FF;HWREG(ulBase + MAC_O_RCTL) = ulTemp;//// Setup the Time Stamp Configuration register.//ulTemp = HWREG(ulBase + MAC_O_TS);ulTemp &= ~(MAC_TS_TSEN);ulTemp |= (ulConfig >> 16) & 0x0FF;HWREG(ulBase + MAC_O_TS) = ulTemp;}//*****************************************************************************////! Gets the current configuration of the Ethernet controller.//!//! \param ulBase is the base address of the controller.//!//! This function will query the control registers of the Ethernet controller//! and return a bit-mapped configuration value.//!//! \sa The description of the EthernetConfigSet() function provides detailed//! information for the bit-mapped configuration values that will be returned.//!//! \return Returns the bit-mapped Ethernet controller configuration value.////*****************************************************************************unsigned longEthernetConfigGet(unsigned long ulBase){unsigned long ulConfig;//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Read and return the Ethernet controller configuration parameters,// properly shifted into the appropriate bit field positions.//ulConfig = HWREG(ulBase + MAC_O_TS) << 16;ulConfig |= (HWREG(ulBase + MAC_O_RCTL) & ~(MAC_RCTL_RXEN)) << 8;ulConfig |= HWREG(ulBase + MAC_O_TCTL) & ~(MAC_TCTL_TXEN);return(ulConfig);}//*****************************************************************************////! Sets the MAC address of the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucMACAddr is the pointer to the array of MAC-48 address octets.//!//! This function will program the IEEE-defined MAC-48 address specified in//! \e pucMACAddr into the Ethernet controller. This address is used by the//! Ethernet controller for hardware-level filtering of incoming Ethernet//! packets (when promiscuous mode is not enabled).//!//! The MAC-48 address is defined as 6 octets, illustrated by the following//! example address. The numbers are shown in hexadecimal format.//!//! AC-DE-48-00-00-80//!//! In this representation, the first three octets (AC-DE-48) are the//! Organizationally Unique Identifier (OUI). This is a number assigned by//! the IEEE to an organization that requests a block of MAC addresses. The//! last three octets (00-00-80) are a 24-bit number managed by the OUI owner//! to uniquely identify a piece of hardware within that organization that is//! to be connected to the Ethernet.//!//! In this representation, the octets are transmitted from left to right,//! with the ``AC'' octet being transmitted first and the ``80'' octet being//! transmitted last. Within an octet, the bits are transmitted LSB to MSB.//! For this address, the first bit to be transmitted would be ``0'', the LSB//! of ``AC'', and the last bit to be transmitted would be ``1'', the MSB of//! ``80''.//!//! \return None.////*****************************************************************************voidEthernetMACAddrSet(unsigned long ulBase, unsigned char *pucMACAddr){unsigned long ulTemp;unsigned char *pucTemp = (unsigned char *)&ulTemp;//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pucMACAddr != 0);//// Program the MAC Address into the device. The first four bytes of the// MAC Address are placed into the IA0 register. The remaining two bytes// of the MAC address are placed into the IA1 register.//pucTemp[0] = pucMACAddr[0];pucTemp[1] = pucMACAddr[1];pucTemp[2] = pucMACAddr[2];pucTemp[3] = pucMACAddr[3];HWREG(ulBase + MAC_O_IA0) = ulTemp;ulTemp = 0;pucTemp[0] = pucMACAddr[4];pucTemp[1] = pucMACAddr[5];HWREG(ulBase + MAC_O_IA1) = ulTemp;}//*****************************************************************************////! Gets the MAC address of the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucMACAddr is the pointer to the location in which to store the//! array of MAC-48 address octets.//!//! This function will read the currently programmed MAC address into the//! \e pucMACAddr buffer.//!//! \sa Refer to EthernetMACAddrSet() API description for more details about//! the MAC address format.//!//! \return None.////*****************************************************************************voidEthernetMACAddrGet(unsigned long ulBase, unsigned char *pucMACAddr){unsigned long ulTemp;unsigned char *pucTemp = (unsigned char *)&ulTemp;//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pucMACAddr != 0);//// Read the MAC address from the device. The first four bytes of the// MAC address are read from the IA0 register. The remaining two bytes// of the MAC addres//ulTemp = HWREG(ulBase + MAC_O_IA0);pucMACAddr[0] = pucTemp[0];pucMACAddr[1] = pucTemp[1];pucMACAddr[2] = pucTemp[2];pucMACAddr[3] = pucTemp[3];ulTemp = HWREG(ulBase + MAC_O_IA1);pucMACAddr[4] = pucTemp[0];pucMACAddr[5] = pucTemp[1];}//*****************************************************************************////! Enables the Ethernet controller for normal operation.//!//! \param ulBase is the base address of the controller.//!//! Once the Ethernet controller has been configured using the//! EthernetConfigSet() function and the MAC address has been programmed using//! the EthernetMACAddrSet() function, this API function can be called to//! enable the controller for normal operation.//!//! This function will enable the controller's transmitter and receiver, and//! will reset the receive FIFO.//!//! \return None.////*****************************************************************************voidEthernetEnable(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Reset the receive FIFO.//HWREG(ulBase + MAC_O_RCTL) |= MAC_RCTL_RSTFIFO;//// Enable the Ethernet receiver.//HWREG(ulBase + MAC_O_RCTL) |= MAC_RCTL_RXEN;//// Enable Ethernet transmitter.//HWREG(ulBase + MAC_O_TCTL) |= MAC_TCTL_TXEN;//// Reset the receive FIFO again, after the receiver has been enabled.//HWREG(ulBase + MAC_O_RCTL) |= MAC_RCTL_RSTFIFO;}//*****************************************************************************////! Disables the Ethernet controller.//!//! \param ulBase is the base address of the controller.//!//! When terminating operations on the Ethernet interface, this function should//! be called. This function will disable the transmitter and receiver, and//! will clear out the receive FIFO.//!//! \return None.////*****************************************************************************voidEthernetDisable(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Reset the receive FIFO.//HWREG(ulBase + MAC_O_RCTL) |= MAC_RCTL_RSTFIFO;//// Disable the Ethernet transmitter.//HWREG(ulBase + MAC_O_TCTL) &= ~(MAC_TCTL_TXEN);//// Disable the Ethernet receiver.//HWREG(ulBase + MAC_O_RCTL) &= ~(MAC_RCTL_RXEN);//// Reset the receive FIFO again, after the receiver has been disabled.//HWREG(ulBase + MAC_O_RCTL) |= MAC_RCTL_RSTFIFO;}//*****************************************************************************////! Check for packet available from the Ethernet controller.//!//! \param ulBase is the base address of the controller.//!//! The Ethernet controller provides a register that contains the number of//! packets available in the receive FIFO. When the last bytes of a packet are//! successfully received (that is, the frame check sequence bytes), the packet//! count is incremented. Once the packet has been fully read (including the//! frame check sequence bytes) from the FIFO, the packet count will be//! decremented.//!//! \return Returns \b true if there are one or more packets available in the//! receive FIFO, including the current packet being read, and \b false//! otherwise.////*****************************************************************************tBooleanEthernetPacketAvail(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Return the availability of packets.//return((HWREG(ulBase + MAC_O_NP) & MAC_NP_NPR_M) ? true : false);}//*****************************************************************************////! Checks for packet space available in the Ethernet controller.//!//! \param ulBase is the base address of the controller.//!//! The Ethernet controller's transmit FIFO is designed to support a single//! packet at a time. After the packet has been written into the FIFO, the//! transmit request bit must be set to enable the transmission of the packet.//! Only after the packet has been transmitted can a new packet be written//! into the FIFO. This function will simply check to see if a packet is//! in progress. If so, there is no space available in the transmit FIFO.//!//! \return Returns \b true if a space is available in the transmit FIFO, and//! \b false otherwise.////*****************************************************************************tBooleanEthernetSpaceAvail(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Return the availability of space.//return((HWREG(ulBase + MAC_O_TR) & MAC_TR_NEWTX) ? false : true);}//*****************************************************************************////! \internal//!//! Internal function for reading a packet from the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucBuf is the pointer to the packet buffer.//! \param lBufLen is the maximum number of bytes to be read into the buffer.//!//! Based on the following table of how the receive frame is stored in the//! receive FIFO, this function will extract a packet from the FIFO and store//! it in the packet buffer that was passed in.//!//! Format of the data in the RX FIFO is as follows://!//! \verbatim//! +---------+----------+----------+----------+----------+//! | | 31:24 | 23:16 | 15:8 | 7:0 |//! +---------+----------+----------+----------+----------+//! | Word 0 | DA 2 | DA 1 | FL MSB | FL LSB |//! +---------+----------+----------+----------+----------+//! | Word 1 | DA 6 | DA 5 | DA 4 | DA 3 |//! +---------+----------+----------+----------+----------+//! | Word 2 | SA 4 | SA 3 | SA 2 | SA 1 |//! +---------+----------+----------+----------+----------+//! | Word 3 | FT LSB | FT MSB | SA 6 | SA 5 |//! +---------+----------+----------+----------+----------+//! | Word 4 | DATA 4 | DATA 3 | DATA 2 | DATA 1 |//! +---------+----------+----------+----------+----------+//! | Word 5 | DATA 8 | DATA 7 | DATA 6 | DATA 5 |//! +---------+----------+----------+----------+----------+//! | Word 6 | DATA 12 | DATA 11 | DATA 10 | DATA 9 |//! +---------+----------+----------+----------+----------+//! | ... | | | | |//! +---------+----------+----------+----------+----------+//! | Word X | DATA n | DATA n-1 | DATA n-2 | DATA n-3 |//! +---------+----------+----------+----------+----------+//! | Word Y | FCS 4 | FCS 3 | FCS 2 | FCS 1 |//! +---------+----------+----------+----------+----------+//! \endverbatim//!//! Where FL is Frame Length, (FL + DA + SA + FT + DATA + FCS) Bytes.//! Where DA is Destination (MAC) Address.//! Where SA is Source (MAC) Address.//! Where FT is Frame Type (or Frame Length for Ethernet).//! Where DATA is Payload Data for the Ethernet Frame.//! Where FCS is the Frame Check Sequence.//!//! \return Returns the negated packet length \b -n if the packet is too large//! for \e pucBuf, and returns the packet length \b n otherwise.////*****************************************************************************static longEthernetPacketGetInternal(unsigned long ulBase, unsigned char *pucBuf,long lBufLen){unsigned long ulTemp;long lFrameLen, lTempLen;long i = 0;//// Read WORD 0 (see format above) from the FIFO, set the receive// Frame Length and store the first two bytes of the destination// address in the receive buffer.//ulTemp = HWREG(ulBase + MAC_O_DATA);lFrameLen = (long)(ulTemp & 0xFFFF);pucBuf[i++] = (unsigned char) ((ulTemp >> 16) & 0xff);pucBuf[i++] = (unsigned char) ((ulTemp >> 24) & 0xff);//// Read all but the last WORD into the receive buffer.//lTempLen = (lBufLen < (lFrameLen - 6)) ? lBufLen : (lFrameLen - 6);while(i <= (lTempLen - 4)){*(unsigned long *)&pucBuf[i] = HWREG(ulBase + MAC_O_DATA);i += 4;}//// Read the last 1, 2, or 3 BYTES into the buffer//if(i < lTempLen){ulTemp = HWREG(ulBase + MAC_O_DATA);if(i == lTempLen - 3){pucBuf[i++] = ((ulTemp >> 0) & 0xff);pucBuf[i++] = ((ulTemp >> 8) & 0xff);pucBuf[i++] = ((ulTemp >> 16) & 0xff);i += 1;}else if(i == lTempLen - 2){pucBuf[i++] = ((ulTemp >> 0) & 0xff);pucBuf[i++] = ((ulTemp >> 8) & 0xff);i += 2;}else if(i == lTempLen - 1){pucBuf[i++] = ((ulTemp >> 0) & 0xff);i += 3;}}//// Read any remaining WORDS (that did not fit into the buffer).//while(i < (lFrameLen - 2)){ulTemp = HWREG(ulBase + MAC_O_DATA);i += 4;}//// If frame was larger than the buffer, return the "negative" frame length//lFrameLen -= 6;if(lFrameLen > lBufLen){return(-lFrameLen);}//// Return the Frame Length//return(lFrameLen);}//*****************************************************************************////! Receives a packet from the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucBuf is the pointer to the packet buffer.//! \param lBufLen is the maximum number of bytes to be read into the buffer.//!//! This function reads a packet from the receive FIFO of the controller and//! places it into \e pucBuf. If no packet is available the function will//! return immediately. Otherwise, the function will read the entire packet//! from the receive FIFO. If there are more bytes in the packet than will fit//! into \e pucBuf (as specified by \e lBufLen), the function will return the//! negated length of the packet and the buffer will contain \e lBufLen bytes//! of the packet. Otherwise, the function will return the length of the//! packet that was read and \e pucBuf will contain the entire packet//! (excluding the frame check sequence bytes).//!//! This function replaces the original EthernetPacketNonBlockingGet() API and//! performs the same actions. A macro is provided in <tt>ethernet.h</tt> to//! map the original API to this API.//!//! \note This function will return immediately if no packet is available.//!//! \return Returns \b 0 if no packet is available, the negated packet length//! \b -n if the packet is too large for \e pucBuf, and the packet length \b n//! otherwise.////*****************************************************************************longEthernetPacketGetNonBlocking(unsigned long ulBase, unsigned char *pucBuf,long lBufLen){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pucBuf != 0);ASSERT(lBufLen > 0);//// Check to see if any packets are available.//if((HWREG(ulBase + MAC_O_NP) & MAC_NP_NPR_M) == 0){return(0);}//// Read the packet, and return.//return(EthernetPacketGetInternal(ulBase, pucBuf, lBufLen));}//*****************************************************************************////! Waits for a packet from the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucBuf is the pointer to the packet buffer.//! \param lBufLen is the maximum number of bytes to be read into the buffer.//!//! This function reads a packet from the receive FIFO of the controller and//! places it into \e pucBuf. The function will wait until a packet is//! available in the FIFO. Then the function will read the entire packet//! from the receive FIFO. If there are more bytes in the packet than will//! fit into \e pucBuf (as specified by \e lBufLen), the function will return//! the negated length of the packet and the buffer will contain \e lBufLen//! bytes of the packet. Otherwise, the function will return the length of//! the packet that was read and \e pucBuf will contain the entire packet//! (excluding the frame check sequence bytes).//!//! \note This function is blocking and will not return until a packet arrives.//!//! \return Returns the negated packet length \b -n if the packet is too large//! for \e pucBuf, and returns the packet length \b n otherwise.////*****************************************************************************longEthernetPacketGet(unsigned long ulBase, unsigned char *pucBuf,long lBufLen){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pucBuf != 0);ASSERT(lBufLen > 0);//// Wait for a packet to become available//while((HWREG(ulBase + MAC_O_NP) & MAC_NP_NPR_M) == 0){}//// Read the packet//return(EthernetPacketGetInternal(ulBase, pucBuf, lBufLen));}//*****************************************************************************////! \internal//!//! Internal function for sending a packet to the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucBuf is the pointer to the packet buffer.//! \param lBufLen is number of bytes in the packet to be transmitted.//!//! Puts a packet into the transmit FIFO of the controller.//!//! Format of the data in the TX FIFO is as follows://!//! \verbatim//! +---------+----------+----------+----------+----------+//! | | 31:24 | 23:16 | 15:8 | 7:0 |//! +---------+----------+----------+----------+----------+//! | Word 0 | DA 2 | DA 1 | PL MSB | PL LSB |//! +---------+----------+----------+----------+----------+//! | Word 1 | DA 6 | DA 5 | DA 4 | DA 3 |//! +---------+----------+----------+----------+----------+//! | Word 2 | SA 4 | SA 3 | SA 2 | SA 1 |//! +---------+----------+----------+----------+----------+//! | Word 3 | FT LSB | FT MSB | SA 6 | SA 5 |//! +---------+----------+----------+----------+----------+//! | Word 4 | DATA 4 | DATA 3 | DATA 2 | DATA 1 |//! +---------+----------+----------+----------+----------+//! | Word 5 | DATA 8 | DATA 7 | DATA 6 | DATA 5 |//! +---------+----------+----------+----------+----------+//! | Word 6 | DATA 12 | DATA 11 | DATA 10 | DATA 9 |//! +---------+----------+----------+----------+----------+//! | ... | | | | |//! +---------+----------+----------+----------+----------+//! | Word X | DATA n | DATA n-1 | DATA n-2 | DATA n-3 |//! +---------+----------+----------+----------+----------+//! \endverbatim//!//! Where PL is Payload Length, (DATA) only//! Where DA is Destination (MAC) Address//! Where SA is Source (MAC) Address//! Where FT is Frame Type (or Frame Length for Ethernet)//! Where DATA is Payload Data for the Ethernet Frame//!//! \return Returns the negated packet length \b -lBufLen if the packet is too//! large for FIFO, and the packet length \b lBufLen otherwise.////*****************************************************************************static longEthernetPacketPutInternal(unsigned long ulBase, unsigned char *pucBuf,long lBufLen){unsigned long ulTemp;long i = 0;//// If the packet is too large, return the negative packet length as// an error code.//if(lBufLen > (2048 - 2)){return(-lBufLen);}//// Build and write WORD 0 (see format above) to the transmit FIFO.//ulTemp = (unsigned long)(lBufLen - 14);ulTemp |= (pucBuf[i++] << 16);ulTemp |= (pucBuf[i++] << 24);HWREG(ulBase + MAC_O_DATA) = ulTemp;//// Write each subsequent WORD n to the transmit FIFO, except for the last// WORD (if the word does not contain 4 bytes).//while(i <= (lBufLen - 4)){HWREG(ulBase + MAC_O_DATA) = *(unsigned long *)&pucBuf[i];i += 4;}//// Build the last word of the remaining 1, 2, or 3 bytes, and store// the WORD into the transmit FIFO.//if(i != lBufLen){if(i == (lBufLen - 3)){ulTemp = (pucBuf[i++] << 0);ulTemp |= (pucBuf[i++] << 8);ulTemp |= (pucBuf[i++] << 16);HWREG(ulBase + MAC_O_DATA) = ulTemp;}else if(i == (lBufLen - 2)){ulTemp = (pucBuf[i++] << 0);ulTemp |= (pucBuf[i++] << 8);HWREG(ulBase + MAC_O_DATA) = ulTemp;}else if(i == (lBufLen - 1)){ulTemp = (pucBuf[i++] << 0);HWREG(ulBase + MAC_O_DATA) = ulTemp;}}//// Activate the transmitter//HWREG(ulBase + MAC_O_TR) = MAC_TR_NEWTX;//// Return the Buffer Length transmitted.//return(lBufLen);}//*****************************************************************************////! Sends a packet to the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucBuf is the pointer to the packet buffer.//! \param lBufLen is number of bytes in the packet to be transmitted.//!//! This function writes \e lBufLen bytes of the packet contained in \e pucBuf//! into the transmit FIFO of the controller and then activates the//! transmitter for this packet. If no space is available in the FIFO, the//! function will return immediately. If space is available, the//! function will return once \e lBufLen bytes of the packet have been placed//! into the FIFO and the transmitter has been started. The function will not//! wait for the transmission to complete. The function will return the//! negated \e lBufLen if the length is larger than the space available in//! the transmit FIFO.//!//! This function replaces the original EthernetPacketNonBlockingPut() API and//! performs the same actions. A macro is provided in <tt>ethernet.h</tt> to//! map the original API to this API.//!//! \note This function does not block and will return immediately if no space//! is available for the transmit packet.//!//! \return Returns \b 0 if no space is available in the transmit FIFO, the//! negated packet length \b -lBufLen if the packet is too large for FIFO, and//! the packet length \b lBufLen otherwise.////*****************************************************************************longEthernetPacketPutNonBlocking(unsigned long ulBase, unsigned char *pucBuf,long lBufLen){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pucBuf != 0);ASSERT(lBufLen > 0);//// Check if the transmit FIFO is in use and return the appropriate code.//if(HWREG(ulBase + MAC_O_TR) & MAC_TR_NEWTX){return(0);}//// Send the packet and return.//return(EthernetPacketPutInternal(ulBase, pucBuf, lBufLen));}//*****************************************************************************////! Waits to send a packet from the Ethernet controller.//!//! \param ulBase is the base address of the controller.//! \param pucBuf is the pointer to the packet buffer.//! \param lBufLen is number of bytes in the packet to be transmitted.//!//! This function writes \e lBufLen bytes of the packet contained in \e pucBuf//! into the transmit FIFO of the controller and then activates the transmitter//! for this packet. This function will wait until the transmit FIFO is empty.//! Once space is available, the function will return once \e lBufLen bytes of//! the packet have been placed into the FIFO and the transmitter has been//! started. The function will not wait for the transmission to complete. The//! function will return the negated \e lBufLen if the length is larger than//! the space available in the transmit FIFO.//!//! \note This function blocks and will wait until space is available for the//! transmit packet before returning.//!//! \return Returns the negated packet length \b -lBufLen if the packet is too//! large for FIFO, and the packet length \b lBufLen otherwise.////*****************************************************************************longEthernetPacketPut(unsigned long ulBase, unsigned char *pucBuf,long lBufLen){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pucBuf != 0);ASSERT(lBufLen > 0);//// Wait for current packet (if any) to complete.//while(HWREG(ulBase + MAC_O_TR) & MAC_TR_NEWTX){}//// Send the packet and return.//return(EthernetPacketPutInternal(ulBase, pucBuf, lBufLen));}//*****************************************************************************////! Registers an interrupt handler for an Ethernet interrupt.//!//! \param ulBase is the base address of the controller.//! \param pfnHandler is a pointer to the function to be called when the//! enabled Ethernet interrupts occur.//!//! This function sets the handler to be called when the Ethernet interrupt//! occurs. This will enable the global interrupt in the interrupt controller;//! specific Ethernet interrupts must be enabled via EthernetIntEnable(). It//! is the interrupt handler's responsibility to clear the interrupt source.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidEthernetIntRegister(unsigned long ulBase, void (*pfnHandler)(void)){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(pfnHandler != 0);//// Register the interrupt handler.//IntRegister(INT_ETH, pfnHandler);//// Enable the Ethernet interrupt.//IntEnable(INT_ETH);}//*****************************************************************************////! Unregisters an interrupt handler for an Ethernet interrupt.//!//! \param ulBase is the base address of the controller.//!//! This function unregisters the interrupt handler. This will disable the//! global interrupt in the interrupt controller so that the interrupt handler//! no longer is called.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidEthernetIntUnregister(unsigned long ulBase){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Disable the interrupt.//IntDisable(INT_ETH);//// Unregister the interrupt handler.//IntUnregister(INT_ETH);}//*****************************************************************************////! Enables individual Ethernet interrupt sources.//!//! \param ulBase is the base address of the controller.//! \param ulIntFlags is the bit mask of the interrupt sources to be enabled.//!//! Enables the indicated Ethernet interrupt sources. Only the sources that//! are enabled can be reflected to the processor interrupt; disabled sources//! have no effect on the processor.//!//! The \e ulIntFlags parameter is the logical OR of any of the following://!//! - \b ETH_INT_PHY - An interrupt from the PHY has occurred. The integrated//! PHY supports a number of interrupt conditions. The PHY register, PHY_MR17,//! must be read to determine which PHY interrupt has occurred. This register//! can be read using the EthernetPHYRead() API function.//! - \b ETH_INT_MDIO - This interrupt indicates that a transaction on the//! management interface has completed successfully.//! - \b ETH_INT_RXER - This interrupt indicates that an error has occurred//! during reception of a frame. This error can indicate a length mismatch, a//! CRC failure, or an error indication from the PHY.//! - \b ETH_INT_RXOF - This interrupt indicates that a frame has been received//! that exceeds the available space in the RX FIFO.//! - \b ETH_INT_TX - This interrupt indicates that the packet stored in the TX//! FIFO has been successfully transmitted.//! - \b ETH_INT_TXER - This interrupt indicates that an error has occurred//! during the transmission of a packet. This error can be either a retry//! failure during the back-off process, or an invalid length stored in the TX//! FIFO.//! - \b ETH_INT_RX - This interrupt indicates that one (or more) packets are//! available in the RX FIFO for processing.//!//! \return None.////*****************************************************************************voidEthernetIntEnable(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(!(ulIntFlags & ~(ETH_INT_PHY | ETH_INT_MDIO | ETH_INT_RXER |ETH_INT_RXOF | ETH_INT_TX | ETH_INT_TXER |ETH_INT_RX)));//// Enable the specified interrupts.//HWREG(ulBase + MAC_O_IM) |= ulIntFlags;}//*****************************************************************************////! Disables individual Ethernet interrupt sources.//!//! \param ulBase is the base address of the controller.//! \param ulIntFlags is the bit mask of the interrupt sources to be disabled.//!//! Disables the indicated Ethernet interrupt sources. Only the sources that//! are enabled can be reflected to the processor interrupt; disabled sources//! have no effect on the processor.//!//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags//! parameter to EthernetIntEnable().//!//! \return None.////*****************************************************************************voidEthernetIntDisable(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(!(ulIntFlags & ~(ETH_INT_PHY | ETH_INT_MDIO | ETH_INT_RXER |ETH_INT_RXOF | ETH_INT_TX | ETH_INT_TXER |ETH_INT_RX)));//// Disable the specified interrupts.//HWREG(ulBase + MAC_O_IM) &= ~ulIntFlags;}//*****************************************************************************////! Gets the current Ethernet interrupt status.//!//! \param ulBase is the base address of the controller.//! \param bMasked is false if the raw interrupt status is required and true//! if the masked interrupt status is required.//!//! This returns the interrupt status for the Ethernet controller. Either the//! raw interrupt status or the status of interrupts that are allowed to//! reflect to the processor can be returned.//!//! \return Returns the current interrupt status, enumerated as a bit field of//! values described in EthernetIntEnable().////*****************************************************************************unsigned longEthernetIntStatus(unsigned long ulBase, tBoolean bMasked){unsigned long ulStatus;//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Read the unmasked status.//ulStatus = HWREG(ulBase + MAC_O_RIS);//// If masked status is requested, mask it off.//if(bMasked){ulStatus &= HWREG(ulBase + MAC_O_IM);}//// Return the interrupt status value.//return(ulStatus);}//*****************************************************************************////! Clears Ethernet interrupt sources.//!//! \param ulBase is the base address of the controller.//! \param ulIntFlags is a bit mask of the interrupt sources to be cleared.//!//! The specified Ethernet interrupt sources are cleared so that they no longer//! assert. This must be done in the interrupt handler to keep it from being//! called again immediately upon exit.//!//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags//! parameter to EthernetIntEnable().//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidEthernetIntClear(unsigned long ulBase, unsigned long ulIntFlags){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);ASSERT(!(ulIntFlags & ~(ETH_INT_PHY | ETH_INT_MDIO | ETH_INT_RXER |ETH_INT_RXOF | ETH_INT_TX | ETH_INT_TXER |ETH_INT_RX)));//// Clear the requested interrupt sources.//HWREG(ulBase + MAC_O_IACK) = ulIntFlags;}//*****************************************************************************////! Writes to the PHY register.//!//! \param ulBase is the base address of the controller.//! \param ucRegAddr is the address of the PHY register to be accessed.//! \param ulData is the data to be written to the PHY register.//!//! This function will write the \e ulData to the PHY register specified by//! \e ucRegAddr.//!//! \return None.////*****************************************************************************voidEthernetPHYWrite(unsigned long ulBase, unsigned char ucRegAddr,unsigned long ulData){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Wait for any pending transaction to complete.//while(HWREG(ulBase + MAC_O_MCTL) & MAC_MCTL_START){}//// Program the DATA to be written.//HWREG(ulBase + MAC_O_MTXD) = ulData & MAC_MTXD_MDTX_M;//// Program the PHY register address and initiate the transaction.//HWREG(ulBase + MAC_O_MCTL) = (((ucRegAddr << 3) & MAC_MCTL_REGADR_M) |MAC_MCTL_WRITE | MAC_MCTL_START);//// Wait for the write transaction to complete.//while(HWREG(ulBase + MAC_O_MCTL) & MAC_MCTL_START){}}//*****************************************************************************////! Reads from a PHY register.//!//! \param ulBase is the base address of the controller.//! \param ucRegAddr is the address of the PHY register to be accessed.//!//! This function will return the contents of the PHY register specified by//! \e ucRegAddr.//!//! \return Returns the 16-bit value read from the PHY.////*****************************************************************************unsigned longEthernetPHYRead(unsigned long ulBase, unsigned char ucRegAddr){//// Check the arguments.//ASSERT(ulBase == ETH_BASE);//// Wait for any pending transaction to complete.//while(HWREG(ulBase + MAC_O_MCTL) & MAC_MCTL_START){}//// Program the PHY register address and initiate the transaction.//HWREG(ulBase + MAC_O_MCTL) = (((ucRegAddr << 3) & MAC_MCTL_REGADR_M) |MAC_MCTL_START);//// Wait for the transaction to complete.//while(HWREG(ulBase + MAC_O_MCTL) & MAC_MCTL_START){}//// Return the PHY data that was read.//return(HWREG(ulBase + MAC_O_MRXD) & MAC_MRXD_MDRX_M);}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:b9fa378d9f27f0a2d07e66aa28f07fbc43ead76b94613efe8a6c2fe88502e343size 7662123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172//*****************************************************************************//// ethernet.h - Defines and Macros for the ethernet module.//// Copyright (c) 2006-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __ETHERNET_H__#define __ETHERNET_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Values that can be passed to EthernetConfigSet as the ulConfig value, and// returned from EthernetConfigGet.////*****************************************************************************#define ETH_CFG_TS_TSEN 0x010000 // Enable Timestamp (CCP)#define ETH_CFG_RX_BADCRCDIS 0x000800 // Disable RX BAD CRC Packets#define ETH_CFG_RX_PRMSEN 0x000400 // Enable RX Promiscuous#define ETH_CFG_RX_AMULEN 0x000200 // Enable RX Multicast#define ETH_CFG_TX_DPLXEN 0x000010 // Enable TX Duplex Mode#define ETH_CFG_TX_CRCEN 0x000004 // Enable TX CRC Generation#define ETH_CFG_TX_PADEN 0x000002 // Enable TX Padding//*****************************************************************************//// Values that can be passed to EthernetIntEnable, EthernetIntDisable, and// EthernetIntClear as the ulIntFlags parameter, and returned from// EthernetIntStatus.////*****************************************************************************#define ETH_INT_PHY 0x040 // PHY Event/Interrupt#define ETH_INT_MDIO 0x020 // Management Transaction#define ETH_INT_RXER 0x010 // RX Error#define ETH_INT_RXOF 0x008 // RX FIFO Overrun#define ETH_INT_TX 0x004 // TX Complete#define ETH_INT_TXER 0x002 // TX Error#define ETH_INT_RX 0x001 // RX Complete//*****************************************************************************//// Helper Macros for Ethernet Processing////*****************************************************************************//// htonl/ntohl - big endian/little endian byte swapping macros for// 32-bit (long) values////*****************************************************************************#ifndef htonl#define htonl(a) \((((a) >> 24) & 0x000000ff) | \(((a) >> 8) & 0x0000ff00) | \(((a) << 8) & 0x00ff0000) | \(((a) << 24) & 0xff000000))#endif#ifndef ntohl#define ntohl(a) htonl((a))#endif//*****************************************************************************//// htons/ntohs - big endian/little endian byte swapping macros for// 16-bit (short) values////*****************************************************************************#ifndef htons#define htons(a) \((((a) >> 8) & 0x00ff) | \(((a) << 8) & 0xff00))#endif#ifndef ntohs#define ntohs(a) htons((a))#endif//*****************************************************************************//// API Function prototypes////*****************************************************************************extern void EthernetInitExpClk(unsigned long ulBase, unsigned long ulEthClk);extern void EthernetConfigSet(unsigned long ulBase, unsigned long ulConfig);extern unsigned long EthernetConfigGet(unsigned long ulBase);extern void EthernetMACAddrSet(unsigned long ulBase,unsigned char *pucMACAddr);extern void EthernetMACAddrGet(unsigned long ulBase,unsigned char *pucMACAddr);extern void EthernetEnable(unsigned long ulBase);extern void EthernetDisable(unsigned long ulBase);extern tBoolean EthernetPacketAvail(unsigned long ulBase);extern tBoolean EthernetSpaceAvail(unsigned long ulBase);extern long EthernetPacketGetNonBlocking(unsigned long ulBase,unsigned char *pucBuf,long lBufLen);extern long EthernetPacketGet(unsigned long ulBase, unsigned char *pucBuf,long lBufLen);extern long EthernetPacketPutNonBlocking(unsigned long ulBase,unsigned char *pucBuf,long lBufLen);extern long EthernetPacketPut(unsigned long ulBase, unsigned char *pucBuf,long lBufLen);extern void EthernetIntRegister(unsigned long ulBase,void (*pfnHandler)(void));extern void EthernetIntUnregister(unsigned long ulBase);extern void EthernetIntEnable(unsigned long ulBase, unsigned long ulIntFlags);extern void EthernetIntDisable(unsigned long ulBase, unsigned long ulIntFlags);extern unsigned long EthernetIntStatus(unsigned long ulBase, tBoolean bMasked);extern void EthernetIntClear(unsigned long ulBase, unsigned long ulIntFlags);extern void EthernetPHYWrite(unsigned long ulBase, unsigned char ucRegAddr,unsigned long ulData);extern unsigned long EthernetPHYRead(unsigned long ulBase,unsigned char ucRegAddr);//*****************************************************************************//// Several Ethernet APIs have been renamed, with the original function name// being deprecated. These defines provide backward compatibility.////*****************************************************************************#ifndef DEPRECATED#include "driverlib/sysctl.h"#define EthernetInit(a) \EthernetInitExpClk(a, SysCtlClockGet())#define EthernetPacketNonBlockingGet(a, b, c) \EthernetPacketGetNonBlocking(a, b, c)#define EthernetPacketNonBlockingPut(a, b, c) \EthernetPacketPutNonBlocking(a, b, c)#endif//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __ETHERNET_H__
123version https://git-lfs.github.com/spec/v1oid sha256:4a884b4ffaedc5744393ab098df94d5e461080412ee1af7c6f6ded3b18692997size 28532123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915//*****************************************************************************//// flash.c - Driver for programming the on-chip flash.//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup flash_api//! @{////*****************************************************************************#include "inc/hw_flash.h"#include "inc/hw_ints.h"#include "inc/hw_sysctl.h"#include "inc/hw_types.h"#include "driverlib/debug.h"#include "driverlib/flash.h"#include "driverlib/interrupt.h"//*****************************************************************************//// An array that maps the specified memory bank to the appropriate Flash// Memory Protection Program Enable (FMPPE) register.////*****************************************************************************static const unsigned long g_pulFMPPERegs[] ={FLASH_FMPPE,FLASH_FMPPE1,FLASH_FMPPE2,FLASH_FMPPE3};//*****************************************************************************//// An array that maps the specified memory bank to the appropriate Flash// Memory Protection Read Enable (FMPRE) register.////*****************************************************************************static const unsigned long g_pulFMPRERegs[] ={FLASH_FMPRE,FLASH_FMPRE1,FLASH_FMPRE2,FLASH_FMPRE3};//*****************************************************************************////! Gets the number of processor clocks per micro-second.//!//! This function returns the number of clocks per micro-second, as presently//! known by the flash controller.//!//! \return Returns the number of processor clocks per micro-second.////*****************************************************************************unsigned longFlashUsecGet(void){//// Return the number of clocks per micro-second.//return(HWREG(FLASH_USECRL) + 1);}//*****************************************************************************////! Sets the number of processor clocks per micro-second.//!//! \param ulClocks is the number of processor clocks per micro-second.//!//! This function is used to tell the flash controller the number of processor//! clocks per micro-second. This value must be programmed correctly or the//! flash most likely will not program correctly; it has no affect on reading//! flash.//!//! \return None.////*****************************************************************************voidFlashUsecSet(unsigned long ulClocks){//// Set the number of clocks per micro-second.//HWREG(FLASH_USECRL) = ulClocks - 1;}//*****************************************************************************////! Erases a block of flash.//!//! \param ulAddress is the start address of the flash block to be erased.//!//! This function will erase a 1 kB block of the on-chip flash. After erasing,//! the block will be filled with 0xFF bytes. Read-only and execute-only//! blocks cannot be erased.//!//! This function will not return until the block has been erased.//!//! \return Returns 0 on success, or -1 if an invalid block address was//! specified or the block is write-protected.////*****************************************************************************longFlashErase(unsigned long ulAddress){//// Check the arguments.//ASSERT(!(ulAddress & (FLASH_ERASE_SIZE - 1)));//// Clear the flash access interrupt.//HWREG(FLASH_FCMISC) = FLASH_FCMISC_AMISC;//// Erase the block.//HWREG(FLASH_FMA) = ulAddress;HWREG(FLASH_FMC) = FLASH_FMC_WRKEY | FLASH_FMC_ERASE;//// Wait until the block has been erased.//while(HWREG(FLASH_FMC) & FLASH_FMC_ERASE){}//// Return an error if an access violation occurred.//if(HWREG(FLASH_FCRIS) & FLASH_FCRIS_ARIS){return(-1);}//// Success.//return(0);}//*****************************************************************************////! Programs flash.//!//! \param pulData is a pointer to the data to be programmed.//! \param ulAddress is the starting address in flash to be programmed. Must//! be a multiple of four.//! \param ulCount is the number of bytes to be programmed. Must be a multiple//! of four.//!//! This function will program a sequence of words into the on-chip flash.//! Programming each location consists of the result of an AND operation//! of the new data and the existing data; in other words bits that contain//! 1 can remain 1 or be changed to 0, but bits that are 0 cannot be changed//! to 1. Therefore, a word can be programmed multiple times as long as these//! rules are followed; if a program operation attempts to change a 0 bit to//! a 1 bit, that bit will not have its value changed.//!//! Since the flash is programmed one word at a time, the starting address and//! byte count must both be multiples of four. It is up to the caller to//! verify the programmed contents, if such verification is required.//!//! This function will not return until the data has been programmed.//!//! \return Returns 0 on success, or -1 if a programming error is encountered.////*****************************************************************************longFlashProgram(unsigned long *pulData, unsigned long ulAddress,unsigned long ulCount){//// Check the arguments.//ASSERT(!(ulAddress & 3));ASSERT(!(ulCount & 3));//// Clear the flash access interrupt.//HWREG(FLASH_FCMISC) = FLASH_FCMISC_AMISC;//// See if this device has a write buffer.//if(HWREG(SYSCTL_NVMSTAT) & SYSCTL_NVMSTAT_FWB){//// Loop over the words to be programmed.//while(ulCount){//// Set the address of this block of words.//HWREG(FLASH_FMA) = ulAddress & ~(0x7f);//// Loop over the words in this 32-word block.//while(((ulAddress & 0x7c) || (HWREG(FLASH_FWBVAL) == 0)) &&(ulCount != 0)){//// Write this word into the write buffer.//HWREG(FLASH_FWBN + (ulAddress & 0x7c)) = *pulData++;ulAddress += 4;ulCount -= 4;}//// Program the contents of the write buffer into flash.//HWREG(FLASH_FMC2) = FLASH_FMC2_WRKEY | FLASH_FMC2_WRBUF;//// Wait until the write buffer has been programmed.//while(HWREG(FLASH_FMC2) & FLASH_FMC2_WRBUF){}}}else{//// Loop over the words to be programmed.//while(ulCount){//// Program the next word.//HWREG(FLASH_FMA) = ulAddress;HWREG(FLASH_FMD) = *pulData;HWREG(FLASH_FMC) = FLASH_FMC_WRKEY | FLASH_FMC_WRITE;//// Wait until the word has been programmed.//while(HWREG(FLASH_FMC) & FLASH_FMC_WRITE){}//// Increment to the next word.//pulData++;ulAddress += 4;ulCount -= 4;}}//// Return an error if an access violation occurred.//if(HWREG(FLASH_FCRIS) & FLASH_FCRIS_ARIS){return(-1);}//// Success.//return(0);}//*****************************************************************************////! Gets the protection setting for a block of flash.//!//! \param ulAddress is the start address of the flash block to be queried.//!//! This function will get the current protection for the specified 2 kB block//! of flash. Each block can be read/write, read-only, or execute-only.//! Read/write blocks can be read, executed, erased, and programmed. Read-only//! blocks can be read and executed. Execute-only blocks can only be executed;//! processor and debugger data reads are not allowed.//!//! \return Returns the protection setting for this block. See//! FlashProtectSet() for possible values.////*****************************************************************************tFlashProtectionFlashProtectGet(unsigned long ulAddress){unsigned long ulFMPRE, ulFMPPE;unsigned long ulBank;//// Check the argument.//ASSERT(!(ulAddress & (FLASH_PROTECT_SIZE - 1)));//// Calculate the Flash Bank from Base Address, and mask off the Bank// from ulAddress for subsequent reference.//ulBank = (((ulAddress / FLASH_PROTECT_SIZE) / 32) % 4);ulAddress &= ((FLASH_PROTECT_SIZE * 32) - 1);//// Read the appropriate flash protection registers for the specified// flash bank.//ulFMPRE = HWREG(g_pulFMPRERegs[ulBank]);ulFMPPE = HWREG(g_pulFMPPERegs[ulBank]);//// For Stellaris Sandstorm-class devices, revision C1 and C2, the upper// bits of the FMPPE register are used for JTAG protect options, and are// not available for the FLASH protection scheme. When Querying Block// Protection, assume these bits are 1.//if(CLASS_IS_SANDSTORM && (REVISION_IS_C1 || REVISION_IS_C2)){ulFMPRE |= (FLASH_FMP_BLOCK_31 | FLASH_FMP_BLOCK_30);}//// Check the appropriate protection bits for the block of memory that// is specified by the address.//switch((((ulFMPRE >> (ulAddress / FLASH_PROTECT_SIZE)) &FLASH_FMP_BLOCK_0) << 1) |((ulFMPPE >> (ulAddress / FLASH_PROTECT_SIZE)) & FLASH_FMP_BLOCK_0)){//// This block is marked as execute only (that is, it can not be erased// or programmed, and the only reads allowed are via the instruction// fecth interface).//case 0:case 1:{return(FlashExecuteOnly);}//// This block is marked as read only (that is, it can not be erased or// programmed).//case 2:{return(FlashReadOnly);}//// This block is read/write; it can be read, erased, and programmed.//case 3:default:{return(FlashReadWrite);}}}//*****************************************************************************////! Sets the protection setting for a block of flash.//!//! \param ulAddress is the start address of the flash block to be protected.//! \param eProtect is the protection to be applied to the block. Can be one//! of \b FlashReadWrite, \b FlashReadOnly, or \b FlashExecuteOnly.//!//! This function will set the protection for the specified 2 kB block of//! flash. Blocks which are read/write can be made read-only or execute-only.//! Blocks which are read-only can be made execute-only. Blocks which are//! execute-only cannot have their protection modified. Attempts to make the//! block protection less stringent (that is, read-only to read/write) will//! result in a failure (and be prevented by the hardware).//!//! Changes to the flash protection are maintained only until the next reset.//! This allows the application to be executed in the desired flash protection//! environment to check for inappropriate flash access (via the flash//! interrupt). To make the flash protection permanent, use the//! FlashProtectSave() function.//!//! \return Returns 0 on success, or -1 if an invalid address or an invalid//! protection was specified.////*****************************************************************************longFlashProtectSet(unsigned long ulAddress, tFlashProtection eProtect){unsigned long ulProtectRE, ulProtectPE;unsigned long ulBank;//// Check the argument.//ASSERT(!(ulAddress & (FLASH_PROTECT_SIZE - 1)));ASSERT((eProtect == FlashReadWrite) || (eProtect == FlashReadOnly) ||(eProtect == FlashExecuteOnly));//// Convert the address into a block number.//ulAddress /= FLASH_PROTECT_SIZE;//// ulAddress contains a "raw" block number. Derive the Flash Bank from// the "raw" block number, and convert ulAddress to a "relative"// block number.//ulBank = ((ulAddress / 32) % 4);ulAddress %= 32;//// Get the current protection for the specified flash bank.//ulProtectRE = HWREG(g_pulFMPRERegs[ulBank]);ulProtectPE = HWREG(g_pulFMPPERegs[ulBank]);//// For Stellaris Sandstorm-class devices, revision C1 and C2, the upper// bits of the FMPPE register are used for JTAG protect options, and are// not available for the FLASH protection scheme. When setting protection,// check to see if block 30 or 31 and protection is FlashExecuteOnly. If// so, return an error condition.//if(CLASS_IS_SANDSTORM && (REVISION_IS_C1 || REVISION_IS_C2)){if((ulAddress >= 30) && (eProtect == FlashExecuteOnly)){return(-1);}}//// Set the protection based on the requested proection.//switch(eProtect){//// Make this block execute only.//case FlashExecuteOnly:{//// Turn off the read and program bits for this block.//ulProtectRE &= ~(FLASH_FMP_BLOCK_0 << ulAddress);ulProtectPE &= ~(FLASH_FMP_BLOCK_0 << ulAddress);//// We're done handling this protection.//break;}//// Make this block read only.//case FlashReadOnly:{//// The block can not be made read only if it is execute only.//if(((ulProtectRE >> ulAddress) & FLASH_FMP_BLOCK_0) !=FLASH_FMP_BLOCK_0){return(-1);}//// Make this block read only.//ulProtectPE &= ~(FLASH_FMP_BLOCK_0 << ulAddress);//// We're done handling this protection.//break;}//// Make this block read/write.//case FlashReadWrite:default:{//// The block can not be made read/write if it is not already// read/write.//if((((ulProtectRE >> ulAddress) & FLASH_FMP_BLOCK_0) !=FLASH_FMP_BLOCK_0) ||(((ulProtectPE >> ulAddress) & FLASH_FMP_BLOCK_0) !=FLASH_FMP_BLOCK_0)){return(-1);}//// The block is already read/write, so there is nothing to do.//return(0);}}//// For Stellaris Sandstorm-class devices, revision C1 and C2, the upper// bits of the FMPPE register are used for JTAG options, and are not// available for the FLASH protection scheme. When setting block// protection, ensure that these bits are not altered.//if(CLASS_IS_SANDSTORM && (REVISION_IS_C1 || REVISION_IS_C2)){ulProtectRE &= ~(FLASH_FMP_BLOCK_31 | FLASH_FMP_BLOCK_30);ulProtectRE |= (HWREG(g_pulFMPRERegs[ulBank]) &(FLASH_FMP_BLOCK_31 | FLASH_FMP_BLOCK_30));}//// Set the new protection for the specified flash bank.//HWREG(g_pulFMPRERegs[ulBank]) = ulProtectRE;HWREG(g_pulFMPPERegs[ulBank]) = ulProtectPE;//// Success.//return(0);}//*****************************************************************************////! Saves the flash protection settings.//!//! This function will make the currently programmed flash protection settings//! permanent. This is a non-reversible operation; a chip reset or power cycle//! will not change the flash protection.//!//! This function will not return until the protection has been saved.//!//! \return Returns 0 on success, or -1 if a hardware error is encountered.////*****************************************************************************longFlashProtectSave(void){int ulTemp, ulLimit;//// If running on a Sandstorm-class device, only trigger a save of the first// two protection registers (FMPRE and FMPPE). Otherwise, save the// entire bank of flash protection registers.//ulLimit = CLASS_IS_SANDSTORM ? 2 : 8;for(ulTemp = 0; ulTemp < ulLimit; ulTemp++){//// Tell the flash controller to write the flash protection register.//HWREG(FLASH_FMA) = ulTemp;HWREG(FLASH_FMC) = FLASH_FMC_WRKEY | FLASH_FMC_COMT;//// Wait until the write has completed.//while(HWREG(FLASH_FMC) & FLASH_FMC_COMT){}}//// Success.//return(0);}//*****************************************************************************////! Gets the user registers.//!//! \param pulUser0 is a pointer to the location to store USER Register 0.//! \param pulUser1 is a pointer to the location to store USER Register 1.//!//! This function will read the contents of user registers (0 and 1), and//! store them in the specified locations.//!//! \return Returns 0 on success, or -1 if a hardware error is encountered.////*****************************************************************************longFlashUserGet(unsigned long *pulUser0, unsigned long *pulUser1){//// Verify that the pointers are valid.//ASSERT(pulUser0 != 0);ASSERT(pulUser1 != 0);//// Verify that hardware supports user registers.//if(CLASS_IS_SANDSTORM){return(-1);}//// Get and store the current value of the user registers.//*pulUser0 = HWREG(FLASH_USERREG0);*pulUser1 = HWREG(FLASH_USERREG1);//// Success.//return(0);}//*****************************************************************************////! Sets the user registers.//!//! \param ulUser0 is the value to store in USER Register 0.//! \param ulUser1 is the value to store in USER Register 1.//!//! This function will set the contents of the user registers (0 and 1) to//! the specified values.//!//! \return Returns 0 on success, or -1 if a hardware error is encountered.////*****************************************************************************longFlashUserSet(unsigned long ulUser0, unsigned long ulUser1){//// Verify that hardware supports user registers.//if(CLASS_IS_SANDSTORM){return(-1);}//// Save the new values into the user registers.//HWREG(FLASH_USERREG0) = ulUser0;HWREG(FLASH_USERREG1) = ulUser1;//// Success.//return(0);}//*****************************************************************************////! Saves the user registers.//!//! This function will make the currently programmed user register settings//! permanent. This is a non-reversible operation; a chip reset or power cycle//! will not change this setting.//!//! This function will not return until the protection has been saved.//!//! \return Returns 0 on success, or -1 if a hardware error is encountered.////*****************************************************************************longFlashUserSave(void){//// Verify that hardware supports user registers.//if(CLASS_IS_SANDSTORM){return(-1);}//// Setting the MSB of FMA will trigger a permanent save of a USER// register. Bit 0 will indicate User 0 (0) or User 1 (1).//HWREG(FLASH_FMA) = 0x80000000;HWREG(FLASH_FMC) = FLASH_FMC_WRKEY | FLASH_FMC_COMT;//// Wait until the write has completed.//while(HWREG(FLASH_FMC) & FLASH_FMC_COMT){}//// Tell the flash controller to write the USER1 Register.//HWREG(FLASH_FMA) = 0x80000001;HWREG(FLASH_FMC) = FLASH_FMC_WRKEY | FLASH_FMC_COMT;//// Wait until the write has completed.//while(HWREG(FLASH_FMC) & FLASH_FMC_COMT){}//// Success.//return(0);}//*****************************************************************************////! Registers an interrupt handler for the flash interrupt.//!//! \param pfnHandler is a pointer to the function to be called when the flash//! interrupt occurs.//!//! This sets the handler to be called when the flash interrupt occurs. The//! flash controller can generate an interrupt when an invalid flash access//! occurs, such as trying to program or erase a read-only block, or trying to//! read from an execute-only block. It can also generate an interrupt when a//! program or erase operation has completed. The interrupt will be//! automatically enabled when the handler is registered.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidFlashIntRegister(void (*pfnHandler)(void)){//// Register the interrupt handler, returning an error if an error occurs.//IntRegister(INT_FLASH, pfnHandler);//// Enable the flash interrupt.//IntEnable(INT_FLASH);}//*****************************************************************************////! Unregisters the interrupt handler for the flash interrupt.//!//! This function will clear the handler to be called when the flash interrupt//! occurs. This will also mask off the interrupt in the interrupt controller//! so that the interrupt handler is no longer called.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidFlashIntUnregister(void){//// Disable the interrupt.//IntDisable(INT_FLASH);//// Unregister the interrupt handler.//IntUnregister(INT_FLASH);}//*****************************************************************************////! Enables individual flash controller interrupt sources.//!//! \param ulIntFlags is a bit mask of the interrupt sources to be enabled.//! Can be any of the \b FLASH_FCIM_PROGRAM or \b FLASH_FCIM_ACCESS values.//!//! Enables the indicated flash controller interrupt sources. Only the sources//! that are enabled can be reflected to the processor interrupt; disabled//! sources have no effect on the processor.//!//! \return None.////*****************************************************************************voidFlashIntEnable(unsigned long ulIntFlags){//// Enable the specified interrupts.//HWREG(FLASH_FCIM) |= ulIntFlags;}//*****************************************************************************////! Disables individual flash controller interrupt sources.//!//! \param ulIntFlags is a bit mask of the interrupt sources to be disabled.//! Can be any of the \b FLASH_FCIM_PROGRAM or \b FLASH_FCIM_ACCESS values.//!//! Disables the indicated flash controller interrupt sources. Only the//! sources that are enabled can be reflected to the processor interrupt;//! disabled sources have no effect on the processor.//!//! \return None.////*****************************************************************************voidFlashIntDisable(unsigned long ulIntFlags){//// Disable the specified interrupts.//HWREG(FLASH_FCIM) &= ~(ulIntFlags);}//*****************************************************************************////! Gets the current interrupt status.//!//! \param bMasked is false if the raw interrupt status is required and true if//! the masked interrupt status is required.//!//! This returns the interrupt status for the flash controller. Either the raw//! interrupt status or the status of interrupts that are allowed to reflect to//! the processor can be returned.//!//! \return The current interrupt status, enumerated as a bit field of//! \b FLASH_FCMISC_PROGRAM and \b FLASH_FCMISC_AMISC.////*****************************************************************************unsigned longFlashIntGetStatus(tBoolean bMasked){//// Return either the interrupt status or the raw interrupt status as// requested.//if(bMasked){return(HWREG(FLASH_FCMISC));}else{return(HWREG(FLASH_FCRIS));}}//*****************************************************************************////! Clears flash controller interrupt sources.//!//! \param ulIntFlags is the bit mask of the interrupt sources to be cleared.//! Can be any of the \b FLASH_FCMISC_PROGRAM or \b FLASH_FCMISC_AMISC values.//!//! The specified flash controller interrupt sources are cleared, so that they//! no longer assert. This must be done in the interrupt handler to keep it//! from being called again immediately upon exit.//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidFlashIntClear(unsigned long ulIntFlags){//// Clear the flash interrupt.//HWREG(FLASH_FCMISC) = ulIntFlags;}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:855fdaf8eb06c50cc594b345698313a92005266f28841a43c5110d34e77a2730size 37411234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889//*****************************************************************************//// flash.h - Prototypes for the flash driver.//// Copyright (c) 2005-2007 Luminary Micro, Inc. All rights reserved// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __FLASH_H__#define __FLASH_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// Values that can be passed to FlashProtectSet(), and returned by// FlashProtectGet().////*****************************************************************************typedef enum{FlashReadWrite, // Flash can be read and writtenFlashReadOnly, // Flash can only be readFlashExecuteOnly // Flash can only be executed}tFlashProtection;//*****************************************************************************//// Prototypes for the APIs.////*****************************************************************************extern unsigned long FlashUsecGet(void);extern void FlashUsecSet(unsigned long ulClocks);extern long FlashErase(unsigned long ulAddress);extern long FlashProgram(unsigned long *pulData, unsigned long ulAddress,unsigned long ulCount);extern tFlashProtection FlashProtectGet(unsigned long ulAddress);extern long FlashProtectSet(unsigned long ulAddress,tFlashProtection eProtect);extern long FlashProtectSave(void);extern long FlashUserGet(unsigned long *pulUser0, unsigned long *pulUser1);extern long FlashUserSet(unsigned long ulUser0, unsigned long ulUser1);extern long FlashUserSave(void);extern void FlashIntRegister(void (*pfnHandler)(void));extern void FlashIntUnregister(void);extern void FlashIntEnable(unsigned long ulIntFlags);extern void FlashIntDisable(unsigned long ulIntFlags);extern unsigned long FlashIntGetStatus(tBoolean bMasked);extern void FlashIntClear(unsigned long ulIntFlags);//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __FLASH_H__
123version https://git-lfs.github.com/spec/v1oid sha256:e5f4ca274f93bc045801f130b0e05af0b79241f5d86898ebdf562a2aca866155size 52710123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512//*****************************************************************************//// gpio.c - API for GPIO ports//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup gpio_api//! @{////*****************************************************************************#include "../inc/hw_gpio.h"#include "../inc/hw_ints.h"#include "../inc/hw_memmap.h"#include "../inc/hw_sysctl.h"#include "../inc/hw_types.h"#include "../driverlib/debug.h"#include "../driverlib/gpio.h"#include "../driverlib/interrupt.h"//*****************************************************************************//// The base addresses of all the GPIO modules. Both the APB and AHB apertures// are provided.////*****************************************************************************static const unsigned long g_pulGPIOBaseAddrs[] ={GPIO_PORTA_BASE, GPIO_PORTA_AHB_BASE,GPIO_PORTB_BASE, GPIO_PORTB_AHB_BASE,GPIO_PORTC_BASE, GPIO_PORTC_AHB_BASE,GPIO_PORTD_BASE, GPIO_PORTD_AHB_BASE,GPIO_PORTE_BASE, GPIO_PORTE_AHB_BASE,GPIO_PORTF_BASE, GPIO_PORTF_AHB_BASE,GPIO_PORTG_BASE, GPIO_PORTG_AHB_BASE,GPIO_PORTH_BASE, GPIO_PORTH_AHB_BASE,GPIO_PORTJ_BASE, GPIO_PORTJ_AHB_BASE,};//*****************************************************************************////! \internal//! Checks a GPIO base address.//!//! \param ulPort is the base address of the GPIO port.//!//! This function determines if a GPIO port base address is valid.//!//! \return Returns \b true if the base address is valid and \b false//! otherwise.////*****************************************************************************#ifdef DEBUGstatic tBooleanGPIOBaseValid(unsigned long ulPort){return((ulPort == GPIO_PORTA_BASE) || (ulPort == GPIO_PORTA_AHB_BASE) ||(ulPort == GPIO_PORTB_BASE) || (ulPort == GPIO_PORTB_AHB_BASE) ||(ulPort == GPIO_PORTC_BASE) || (ulPort == GPIO_PORTC_AHB_BASE) ||(ulPort == GPIO_PORTD_BASE) || (ulPort == GPIO_PORTD_AHB_BASE) ||(ulPort == GPIO_PORTE_BASE) || (ulPort == GPIO_PORTE_AHB_BASE) ||(ulPort == GPIO_PORTF_BASE) || (ulPort == GPIO_PORTF_AHB_BASE) ||(ulPort == GPIO_PORTG_BASE) || (ulPort == GPIO_PORTG_AHB_BASE) ||(ulPort == GPIO_PORTH_BASE) || (ulPort == GPIO_PORTH_AHB_BASE) ||(ulPort == GPIO_PORTJ_BASE) || (ulPort == GPIO_PORTJ_AHB_BASE));}#endif//*****************************************************************************////! \internal//! Gets the GPIO interrupt number.//!//! \param ulPort is the base address of the GPIO port.//!//! Given a GPIO base address, returns the corresponding interrupt number.//!//! \return Returns a GPIO interrupt number, or -1 if \e ulPort is invalid.////*****************************************************************************static longGPIOGetIntNumber(unsigned long ulPort){unsigned int ulInt;//// Determine the GPIO interrupt number for the given module.//switch(ulPort){case GPIO_PORTA_BASE:case GPIO_PORTA_AHB_BASE:{ulInt = INT_GPIOA;break;}case GPIO_PORTB_BASE:case GPIO_PORTB_AHB_BASE:{ulInt = INT_GPIOB;break;}case GPIO_PORTC_BASE:case GPIO_PORTC_AHB_BASE:{ulInt = INT_GPIOC;break;}case GPIO_PORTD_BASE:case GPIO_PORTD_AHB_BASE:{ulInt = INT_GPIOD;break;}case GPIO_PORTE_BASE:case GPIO_PORTE_AHB_BASE:{ulInt = INT_GPIOE;break;}case GPIO_PORTF_BASE:case GPIO_PORTF_AHB_BASE:{ulInt = INT_GPIOF;break;}case GPIO_PORTG_BASE:case GPIO_PORTG_AHB_BASE:{ulInt = INT_GPIOG;break;}case GPIO_PORTH_BASE:case GPIO_PORTH_AHB_BASE:{ulInt = INT_GPIOH;break;}case GPIO_PORTJ_BASE:case GPIO_PORTJ_AHB_BASE:{ulInt = INT_GPIOJ;break;}default:{return(-1);}}//// Return GPIO interrupt number.//return(ulInt);}//*****************************************************************************////! Sets the direction and mode of the specified pin(s).//!//! \param ulPort is the base address of the GPIO port//! \param ucPins is the bit-packed representation of the pin(s).//! \param ulPinIO is the pin direction and/or mode.//!//! This function will set the specified pin(s) on the selected GPIO port//! as either an input or output under software control, or it will set the//! pin to be under hardware control.//!//! The parameter \e ulPinIO is an enumerated data type that can be one of//! the following values://!//! - \b GPIO_DIR_MODE_IN//! - \b GPIO_DIR_MODE_OUT//! - \b GPIO_DIR_MODE_HW//!//! where \b GPIO_DIR_MODE_IN specifies that the pin will be programmed as//! a software controlled input, \b GPIO_DIR_MODE_OUT specifies that the pin//! will be programmed as a software controlled output, and//! \b GPIO_DIR_MODE_HW specifies that the pin will be placed under//! hardware control.//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIODirModeSet(unsigned long ulPort, unsigned char ucPins,unsigned long ulPinIO){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));ASSERT((ulPinIO == GPIO_DIR_MODE_IN) || (ulPinIO == GPIO_DIR_MODE_OUT) ||(ulPinIO == GPIO_DIR_MODE_HW));//// Set the pin direction and mode.//HWREG(ulPort + GPIO_O_DIR) = ((ulPinIO & 1) ?(HWREG(ulPort + GPIO_O_DIR) | ucPins) :(HWREG(ulPort + GPIO_O_DIR) & ~(ucPins)));HWREG(ulPort + GPIO_O_AFSEL) = ((ulPinIO & 2) ?(HWREG(ulPort + GPIO_O_AFSEL) | ucPins) :(HWREG(ulPort + GPIO_O_AFSEL) &~(ucPins)));}//*****************************************************************************////! Gets the direction and mode of a pin.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPin is the pin number.//!//! This function gets the direction and control mode for a specified pin on//! the selected GPIO port. The pin can be configured as either an input or//! output under software control, or it can be under hardware control. The//! type of control and direction are returned as an enumerated data type.//!//! \return Returns one of the enumerated data types described for//! GPIODirModeSet().////*****************************************************************************unsigned longGPIODirModeGet(unsigned long ulPort, unsigned char ucPin){unsigned long ulDir, ulAFSEL;//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));ASSERT(ucPin < 8);//// Convert from a pin number to a bit position.//ucPin = 1 << ucPin;//// Return the pin direction and mode.//ulDir = HWREG(ulPort + GPIO_O_DIR);ulAFSEL = HWREG(ulPort + GPIO_O_AFSEL);return(((ulDir & ucPin) ? 1 : 0) | ((ulAFSEL & ucPin) ? 2 : 0));}//*****************************************************************************////! Sets the interrupt type for the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//! \param ulIntType specifies the type of interrupt trigger mechanism.//!//! This function sets up the various interrupt trigger mechanisms for the//! specified pin(s) on the selected GPIO port.//!//! The parameter \e ulIntType is an enumerated data type that can be one of//! the following values://!//! - \b GPIO_FALLING_EDGE//! - \b GPIO_RISING_EDGE//! - \b GPIO_BOTH_EDGES//! - \b GPIO_LOW_LEVEL//! - \b GPIO_HIGH_LEVEL//!//! where the different values describe the interrupt detection mechanism//! (edge or level) and the particular triggering event (falling, rising,//! or both edges for edge detect, low or high for level detect).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note In order to avoid any spurious interrupts, the user must//! ensure that the GPIO inputs remain stable for the duration of//! this function.//!//! \return None.////*****************************************************************************voidGPIOIntTypeSet(unsigned long ulPort, unsigned char ucPins,unsigned long ulIntType){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));ASSERT((ulIntType == GPIO_FALLING_EDGE) ||(ulIntType == GPIO_RISING_EDGE) || (ulIntType == GPIO_BOTH_EDGES) ||(ulIntType == GPIO_LOW_LEVEL) || (ulIntType == GPIO_HIGH_LEVEL));//// Set the pin interrupt type.//HWREG(ulPort + GPIO_O_IBE) = ((ulIntType & 1) ?(HWREG(ulPort + GPIO_O_IBE) | ucPins) :(HWREG(ulPort + GPIO_O_IBE) & ~(ucPins)));HWREG(ulPort + GPIO_O_IS) = ((ulIntType & 2) ?(HWREG(ulPort + GPIO_O_IS) | ucPins) :(HWREG(ulPort + GPIO_O_IS) & ~(ucPins)));HWREG(ulPort + GPIO_O_IEV) = ((ulIntType & 4) ?(HWREG(ulPort + GPIO_O_IEV) | ucPins) :(HWREG(ulPort + GPIO_O_IEV) & ~(ucPins)));}//*****************************************************************************////! Gets the interrupt type for a pin.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPin is the pin number.//!//! This function gets the interrupt type for a specified pin on the selected//! GPIO port. The pin can be configured as a falling edge, rising edge, or//! both edge detected interrupt, or it can be configured as a low level or//! high level detected interrupt. The type of interrupt detection mechanism//! is returned as an enumerated data type.//!//! \return Returns one of the enumerated data types described for//! GPIOIntTypeSet().////*****************************************************************************unsigned longGPIOIntTypeGet(unsigned long ulPort, unsigned char ucPin){unsigned long ulIBE, ulIS, ulIEV;//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));ASSERT(ucPin < 8);//// Convert from a pin number to a bit position.//ucPin = 1 << ucPin;//// Return the pin interrupt type.//ulIBE = HWREG(ulPort + GPIO_O_IBE);ulIS = HWREG(ulPort + GPIO_O_IS);ulIEV = HWREG(ulPort + GPIO_O_IEV);return(((ulIBE & ucPin) ? 1 : 0) | ((ulIS & ucPin) ? 2 : 0) |((ulIEV & ucPin) ? 4 : 0));}//*****************************************************************************////! Sets the pad configuration for the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//! \param ulStrength specifies the output drive strength.//! \param ulPinType specifies the pin type.//!//! This function sets the drive strength and type for the specified pin(s)//! on the selected GPIO port. For pin(s) configured as input ports, the//! pad is configured as requested, but the only real effect on the input//! is the configuration of the pull-up or pull-down termination.//!//! The parameter \e ulStrength can be one of the following values://!//! - \b GPIO_STRENGTH_2MA//! - \b GPIO_STRENGTH_4MA//! - \b GPIO_STRENGTH_8MA//! - \b GPIO_STRENGTH_8MA_SC//!//! where \b GPIO_STRENGTH_xMA specifies either 2, 4, or 8 mA output drive//! strength, and \b GPIO_OUT_STRENGTH_8MA_SC specifies 8 mA output drive with//! slew control.//!//! The parameter \e ulPinType can be one of the following values://!//! - \b GPIO_PIN_TYPE_STD//! - \b GPIO_PIN_TYPE_STD_WPU//! - \b GPIO_PIN_TYPE_STD_WPD//! - \b GPIO_PIN_TYPE_OD//! - \b GPIO_PIN_TYPE_OD_WPU//! - \b GPIO_PIN_TYPE_OD_WPD//! - \b GPIO_PIN_TYPE_ANALOG//!//! where \b GPIO_PIN_TYPE_STD* specifies a push-pull pin, \b GPIO_PIN_TYPE_OD*//! specifies an open-drain pin, \b *_WPU specifies a weak pull-up, \b *_WPD//! specifies a weak pull-down, and \b GPIO_PIN_TYPE_ANALOG specifies an//! analog input (for the comparators).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPadConfigSet(unsigned long ulPort, unsigned char ucPins,unsigned long ulStrength, unsigned long ulPinType){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));ASSERT((ulStrength == GPIO_STRENGTH_2MA) ||(ulStrength == GPIO_STRENGTH_4MA) ||(ulStrength == GPIO_STRENGTH_8MA) ||(ulStrength == GPIO_STRENGTH_8MA_SC));ASSERT((ulPinType == GPIO_PIN_TYPE_STD) ||(ulPinType == GPIO_PIN_TYPE_STD_WPU) ||(ulPinType == GPIO_PIN_TYPE_STD_WPD) ||(ulPinType == GPIO_PIN_TYPE_OD) ||(ulPinType == GPIO_PIN_TYPE_OD_WPU) ||(ulPinType == GPIO_PIN_TYPE_OD_WPD) ||(ulPinType == GPIO_PIN_TYPE_ANALOG))//// Set the output drive strength.//HWREG(ulPort + GPIO_O_DR2R) = ((ulStrength & 1) ?(HWREG(ulPort + GPIO_O_DR2R) | ucPins) :(HWREG(ulPort + GPIO_O_DR2R) & ~(ucPins)));HWREG(ulPort + GPIO_O_DR4R) = ((ulStrength & 2) ?(HWREG(ulPort + GPIO_O_DR4R) | ucPins) :(HWREG(ulPort + GPIO_O_DR4R) & ~(ucPins)));HWREG(ulPort + GPIO_O_DR8R) = ((ulStrength & 4) ?(HWREG(ulPort + GPIO_O_DR8R) | ucPins) :(HWREG(ulPort + GPIO_O_DR8R) & ~(ucPins)));HWREG(ulPort + GPIO_O_SLR) = ((ulStrength & 8) ?(HWREG(ulPort + GPIO_O_SLR) | ucPins) :(HWREG(ulPort + GPIO_O_SLR) & ~(ucPins)));//// Set the pin type.//HWREG(ulPort + GPIO_O_ODR) = ((ulPinType & 1) ?(HWREG(ulPort + GPIO_O_ODR) | ucPins) :(HWREG(ulPort + GPIO_O_ODR) & ~(ucPins)));HWREG(ulPort + GPIO_O_PUR) = ((ulPinType & 2) ?(HWREG(ulPort + GPIO_O_PUR) | ucPins) :(HWREG(ulPort + GPIO_O_PUR) & ~(ucPins)));HWREG(ulPort + GPIO_O_PDR) = ((ulPinType & 4) ?(HWREG(ulPort + GPIO_O_PDR) | ucPins) :(HWREG(ulPort + GPIO_O_PDR) & ~(ucPins)));HWREG(ulPort + GPIO_O_DEN) = ((ulPinType & 8) ?(HWREG(ulPort + GPIO_O_DEN) | ucPins) :(HWREG(ulPort + GPIO_O_DEN) & ~(ucPins)));//// Set the analog mode select register. This register only appears in// DustDevil-class (and later) devices, but is a harmless write on// Sandstorm- and Fury-class devices.//HWREG(ulPort + GPIO_O_AMSEL) =((ulPinType == GPIO_PIN_TYPE_ANALOG) ?(HWREG(ulPort + GPIO_O_AMSEL) | ucPins) :(HWREG(ulPort + GPIO_O_AMSEL) & ~(ucPins)));}//*****************************************************************************////! Gets the pad configuration for a pin.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPin is the pin number.//! \param pulStrength is a pointer to storage for the output drive strength.//! \param pulPinType is a pointer to storage for the output drive type.//!//! This function gets the pad configuration for a specified pin on the//! selected GPIO port. The values returned in \e pulStrength and//! \e pulPinType correspond to the values used in GPIOPadConfigSet(). This//! function also works for pin(s) configured as input pin(s); however, the//! only meaningful data returned is whether the pin is terminated with a//! pull-up or down resistor.//!//! \return None////*****************************************************************************voidGPIOPadConfigGet(unsigned long ulPort, unsigned char ucPin,unsigned long *pulStrength, unsigned long *pulPinType){unsigned long ulTemp1, ulTemp2, ulTemp3, ulTemp4;//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));ASSERT(ucPin < 8);//// Convert from a pin number to a bit position.//ucPin = (1 << ucPin);//// Get the drive strength for this pin.//ulTemp1 = HWREG(ulPort + GPIO_O_DR2R);ulTemp2 = HWREG(ulPort + GPIO_O_DR4R);ulTemp3 = HWREG(ulPort + GPIO_O_DR8R);ulTemp4 = HWREG(ulPort + GPIO_O_SLR);*pulStrength = (((ulTemp1 & ucPin) ? 1 : 0) | ((ulTemp2 & ucPin) ? 2 : 0) |((ulTemp3 & ucPin) ? 4 : 0) | ((ulTemp4 & ucPin) ? 8 : 0));//// Get the pin type.//ulTemp1 = HWREG(ulPort + GPIO_O_ODR);ulTemp2 = HWREG(ulPort + GPIO_O_PUR);ulTemp3 = HWREG(ulPort + GPIO_O_PDR);ulTemp4 = HWREG(ulPort + GPIO_O_DEN);*pulPinType = (((ulTemp1 & ucPin) ? 1 : 0) | ((ulTemp2 & ucPin) ? 2 : 0) |((ulTemp3 & ucPin) ? 4 : 0) | ((ulTemp4 & ucPin) ? 8 : 0));}//*****************************************************************************////! Enables interrupts for the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! Unmasks the interrupt for the specified pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPinIntEnable(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Enable the interrupts.//HWREG(ulPort + GPIO_O_IM) |= ucPins;}//*****************************************************************************////! Disables interrupts for the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! Masks the interrupt for the specified pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPinIntDisable(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Disable the interrupts.//HWREG(ulPort + GPIO_O_IM) &= ~(ucPins);}//*****************************************************************************////! Gets interrupt status for the specified GPIO port.//!//! \param ulPort is the base address of the GPIO port.//! \param bMasked specifies whether masked or raw interrupt status is//! returned.//!//! If \e bMasked is set as \b true, then the masked interrupt status is//! returned; otherwise, the raw interrupt status will be returned.//!//! \return Returns a bit-packed byte, where each bit that is set identifies//! an active masked or raw interrupt, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//! Bits 31:8 should be ignored.////*****************************************************************************longGPIOPinIntStatus(unsigned long ulPort, tBoolean bMasked){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Return the interrupt status.//if(bMasked){return(HWREG(ulPort + GPIO_O_MIS));}else{return(HWREG(ulPort + GPIO_O_RIS));}}//*****************************************************************************////! Clears the interrupt for the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! Clears the interrupt for the specified pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidGPIOPinIntClear(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Clear the interrupts.//HWREG(ulPort + GPIO_O_ICR) = ucPins;}//*****************************************************************************////! Registers an interrupt handler for a GPIO port.//!//! \param ulPort is the base address of the GPIO port.//! \param pfnIntHandler is a pointer to the GPIO port interrupt handling//! function.//!//! This function will ensure that the interrupt handler specified by//! \e pfnIntHandler is called when an interrupt is detected from the selected//! GPIO port. This function will also enable the corresponding GPIO interrupt//! in the interrupt controller; individual pin interrupts and interrupt//! sources must be enabled with GPIOPinIntEnable().//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidGPIOPortIntRegister(unsigned long ulPort, void (*pfnIntHandler)(void)){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Get the interrupt number associated with the specified GPIO.//ulPort = GPIOGetIntNumber(ulPort);//// Register the interrupt handler.//IntRegister(ulPort, pfnIntHandler);//// Enable the GPIO interrupt.//IntEnable(ulPort);}//*****************************************************************************////! Removes an interrupt handler for a GPIO port.//!//! \param ulPort is the base address of the GPIO port.//!//! This function will unregister the interrupt handler for the specified//! GPIO port. This function will also disable the corresponding//! GPIO port interrupt in the interrupt controller; individual GPIO interrupts//! and interrupt sources must be disabled with GPIOPinIntDisable().//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidGPIOPortIntUnregister(unsigned long ulPort){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Get the interrupt number associated with the specified GPIO.//ulPort = GPIOGetIntNumber(ulPort);//// Disable the GPIO interrupt.//IntDisable(ulPort);//// Unregister the interrupt handler.//IntUnregister(ulPort);}//*****************************************************************************////! Reads the values present of the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The values at the specified pin(s) are read, as specified by \e ucPins.//! Values are returned for both input and output pin(s), and the value//! for pin(s) that are not specified by \e ucPins are set to 0.//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return Returns a bit-packed byte providing the state of the specified//! pin, where bit 0 of the byte represents GPIO port pin 0, bit 1 represents//! GPIO port pin 1, and so on. Any bit that is not specified by \e ucPins//! is returned as a 0. Bits 31:8 should be ignored.////*****************************************************************************longGPIOPinRead(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Return the pin value(s).//return(HWREG(ulPort + (GPIO_O_DATA + (ucPins << 2))));}//*****************************************************************************////! Writes a value to the specified pin(s).//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//! \param ucVal is the value to write to the pin(s).//!//! Writes the corresponding bit values to the output pin(s) specified by//! \e ucPins. Writing to a pin configured as an input pin has no effect.//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPinWrite(unsigned long ulPort, unsigned char ucPins, unsigned char ucVal){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Write the pins.//HWREG(ulPort + (GPIO_O_DATA + (ucPins << 2))) = ucVal;}//*****************************************************************************////! Configures pin(s) for use as analog-to-digital converter inputs.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The analog-to-digital converter input pins must be properly configured//! to function correctly on DustDevil-class devices. This function provides//! the proper configuration for those pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into an ADC input; it only//! configures an ADC input pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeADC(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be inputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_IN);//// Set the pad(s) for analog operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_ANALOG);}//*****************************************************************************////! Configures pin(s) for use as a CAN device.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The CAN pins must be properly configured for the CAN peripherals to//! function correctly. This function provides a typical configuration for//! those pin(s); other configurations may work as well depending upon the//! board setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a CAN pin; it only//! configures a CAN pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeCAN(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be inputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_8MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use as an analog comparator input.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The analog comparator input pins must be properly configured for the analog//! comparator to function correctly. This function provides the proper//! configuration for those pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into an analog comparator input;//! it only configures an analog comparator pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeComparator(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be inputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_IN);//// Set the pad(s) for analog operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_ANALOG);}//*****************************************************************************////! Configures pin(s) for use as GPIO inputs.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The GPIO pins must be properly configured in order to function correctly as//! GPIO inputs; this is especially true of Fury-class devices where the//! digital input enable is turned off by default. This function provides the//! proper configuration for those pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPinTypeGPIOInput(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be inputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_IN);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use as GPIO outputs.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The GPIO pins must be properly configured in order to function correctly as//! GPIO outputs; this is especially true of Fury-class devices where the//! digital input enable is turned off by default. This function provides the//! proper configuration for those pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPinTypeGPIOOutput(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be outputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_OUT);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use as GPIO open drain outputs.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The GPIO pins must be properly configured in order to function correctly as//! GPIO outputs; this is especially true of Fury-class devices where the//! digital input enable is turned off by default. This function provides the//! proper configuration for those pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \return None.////*****************************************************************************voidGPIOPinTypeGPIOOutputOD(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be outputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_OUT);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_OD);}//*****************************************************************************////! Configures pin(s) for use by the I2C peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The I2C pins must be properly configured for the I2C peripheral to function//! correctly. This function provides the proper configuration for those//! pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into an I2C pin; it only//! configures an I2C pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeI2C(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for open-drain operation with a weak pull-up.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_OD_WPU);}//*****************************************************************************////! Configures pin(s) for use by the PWM peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The PWM pins must be properly configured for the PWM peripheral to function//! correctly. This function provides a typical configuration for those//! pin(s); other configurations may work as well depending upon the board//! setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a PWM pin; it only//! configures a PWM pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypePWM(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use by the QEI peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The QEI pins must be properly configured for the QEI peripheral to function//! correctly. This function provides a typical configuration for those//! pin(s); other configurations may work as well depending upon the board//! setup (for example, not using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a QEI pin; it only//! configures a QEI pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeQEI(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation with a weak pull-up.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);}//*****************************************************************************////! Configures pin(s) for use by the SSI peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The SSI pins must be properly configured for the SSI peripheral to function//! correctly. This function provides a typical configuration for those//! pin(s); other configurations may work as well depending upon the board//! setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a SSI pin; it only//! configures a SSI pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeSSI(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use by the Timer peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The CCP pins must be properly configured for the timer peripheral to//! function correctly. This function provides a typical configuration for//! those pin(s); other configurations may work as well depending upon the//! board setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a timer pin; it only//! configures a timer pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeTimer(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use by the UART peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! The UART pins must be properly configured for the UART peripheral to//! function correctly. This function provides a typical configuration for//! those pin(s); other configurations may work as well depending upon the//! board setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a UART pin; it only//! configures a UART pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeUART(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use by the USB peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! Some USB digital pins must be properly configured for the USB peripheral to//! function correctly. This function provides a typical configuration for//! the digital USB pin(s); other configurations may work as well depending//! upon the board setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a USB pin; it only//! configures a USB pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeUSBDigital(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures pin(s) for use by the USB peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! Some USB analog pins must be properly configured for the USB peripheral to//! function correctly. This function provides the proper configuration for//! those pin(s).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a USB pin; it only//! configures a USB pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeUSBAnalog(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be inputs.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_IN);//// Set the pad(s) for analog operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_ANALOG);}//*****************************************************************************////! Configures pin(s) for use by the I2S peripheral.//!//! \param ulPort is the base address of the GPIO port.//! \param ucPins is the bit-packed representation of the pin(s).//!//! Some I2S pins must be properly configured for the I2S peripheral to//! function correctly. This function provides a typical configuration for//! the digital I2S pin(s); other configurations may work as well depending//! upon the board setup (for example, using the on-chip pull-ups).//!//! The pin(s) are specified using a bit-packed byte, where each bit that is//! set identifies the pin to be accessed, and where bit 0 of the byte//! represents GPIO port pin 0, bit 1 represents GPIO port pin 1, and so on.//!//! \note This cannot be used to turn any pin into a I2S pin; it only//! configures a I2S pin for proper operation.//!//! \return None.////*****************************************************************************voidGPIOPinTypeI2S(unsigned long ulPort, unsigned char ucPins){//// Check the arguments.//ASSERT(GPIOBaseValid(ulPort));//// Make the pin(s) be peripheral controlled.//GPIODirModeSet(ulPort, ucPins, GPIO_DIR_MODE_HW);//// Set the pad(s) for standard push-pull operation.//GPIOPadConfigSet(ulPort, ucPins, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);}//*****************************************************************************////! Configures the alternate function of a GPIO pin.//!//! \param ulPinConfig is the pin configuration value, specified as one of the//! \b GPIO_P??_??? values.//!//! This function configures the pin mux that selects the peripheral function//! associated with a particular GPIO pin. Only one peripheral function at a//! time can be associated with a GPIO pin, and each peripheral function should//! only be associated with a single GPIO pin at a time (despite the fact that//! many of them can be associated with more than one GPIO pin).//!//! \note This function is only valid on Tempest-class devices.//!//! \return None.////*****************************************************************************voidGPIOPinConfigure(unsigned long ulPinConfig){unsigned long ulBase, ulShift;//// Check the argument.//ASSERT(((ulPinConfig >> 16) & 0xff) < 9);ASSERT(((ulPinConfig >> 8) & 0xe3) == 0);//// Extract the base address index from the input value.//ulBase = (ulPinConfig >> 16) & 0xff;//// Get the base address of the GPIO module, selecting either the APB or the// AHB aperture as appropriate.//if(HWREG(SYSCTL_GPIOHSCTL) & (1 << ulBase)){ulBase = g_pulGPIOBaseAddrs[(ulBase << 1) + 1];}else{ulBase = g_pulGPIOBaseAddrs[ulBase << 1];}//// Extract the shift from the input value.//ulShift = (ulPinConfig >> 8) & 0xff;//// Write the requested pin muxing value for this GPIO pin.//HWREG(ulBase + GPIO_O_PCTL) = ((HWREG(ulBase + GPIO_O_PCTL) &~(0xf << ulShift)) |((ulPinConfig & 0xf) << ulShift));}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
123version https://git-lfs.github.com/spec/v1oid sha256:056afdfe7e7bad96b2d98d966caee78737aeeb3565ab93b276ab2c36f830812csize 24277123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768//*****************************************************************************//// gpio.h - Defines and Macros for GPIO API.//// Copyright (c) 2005-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************#ifndef __GPIO_H__#define __GPIO_H__//*****************************************************************************//// If building with a C++ compiler, make all of the definitions in this header// have a C binding.////*****************************************************************************#ifdef __cplusplusextern "C"{#endif//*****************************************************************************//// The following values define the bit field for the ucPins argument to several// of the APIs.////*****************************************************************************#define GPIO_PIN_0 0x00000001 // GPIO pin 0#define GPIO_PIN_1 0x00000002 // GPIO pin 1#define GPIO_PIN_2 0x00000004 // GPIO pin 2#define GPIO_PIN_3 0x00000008 // GPIO pin 3#define GPIO_PIN_4 0x00000010 // GPIO pin 4#define GPIO_PIN_5 0x00000020 // GPIO pin 5#define GPIO_PIN_6 0x00000040 // GPIO pin 6#define GPIO_PIN_7 0x00000080 // GPIO pin 7//*****************************************************************************//// Values that can be passed to GPIODirModeSet as the ulPinIO parameter, and// returned from GPIODirModeGet.////*****************************************************************************#define GPIO_DIR_MODE_IN 0x00000000 // Pin is a GPIO input#define GPIO_DIR_MODE_OUT 0x00000001 // Pin is a GPIO output#define GPIO_DIR_MODE_HW 0x00000002 // Pin is a peripheral function//*****************************************************************************//// Values that can be passed to GPIOIntTypeSet as the ulIntType parameter, and// returned from GPIOIntTypeGet.////*****************************************************************************#define GPIO_FALLING_EDGE 0x00000000 // Interrupt on falling edge#define GPIO_RISING_EDGE 0x00000004 // Interrupt on rising edge#define GPIO_BOTH_EDGES 0x00000001 // Interrupt on both edges#define GPIO_LOW_LEVEL 0x00000002 // Interrupt on low level#define GPIO_HIGH_LEVEL 0x00000007 // Interrupt on high level//*****************************************************************************//// Values that can be passed to GPIOPadConfigSet as the ulStrength parameter,// and returned by GPIOPadConfigGet in the *pulStrength parameter.////*****************************************************************************#define GPIO_STRENGTH_2MA 0x00000001 // 2mA drive strength#define GPIO_STRENGTH_4MA 0x00000002 // 4mA drive strength#define GPIO_STRENGTH_8MA 0x00000004 // 8mA drive strength#define GPIO_STRENGTH_8MA_SC 0x0000000C // 8mA drive with slew rate control//*****************************************************************************//// Values that can be passed to GPIOPadConfigSet as the ulPadType parameter,// and returned by GPIOPadConfigGet in the *pulPadType parameter.////*****************************************************************************#define GPIO_PIN_TYPE_STD 0x00000008 // Push-pull#define GPIO_PIN_TYPE_STD_WPU 0x0000000A // Push-pull with weak pull-up#define GPIO_PIN_TYPE_STD_WPD 0x0000000C // Push-pull with weak pull-down#define GPIO_PIN_TYPE_OD 0x00000009 // Open-drain#define GPIO_PIN_TYPE_OD_WPU 0x0000000B // Open-drain with weak pull-up#define GPIO_PIN_TYPE_OD_WPD 0x0000000D // Open-drain with weak pull-down#define GPIO_PIN_TYPE_ANALOG 0x00000000 // Analog comparator//*****************************************************************************//// Values that can be passed to GPIOPinConfigure as the ulPinConfig parameter.////*****************************************************************************//// GPIO pin A0//#define GPIO_PA0_U0RX 0x00000001#define GPIO_PA0_I2C1SCL 0x00000008#define GPIO_PA0_U1RX 0x00000009//// GPIO pin A1//#define GPIO_PA1_U0TX 0x00000401#define GPIO_PA1_I2C1SDA 0x00000408#define GPIO_PA1_U1TX 0x00000409//// GPIO pin A2//#define GPIO_PA2_SSI0CLK 0x00000801#define GPIO_PA2_PWM4 0x00000804#define GPIO_PA2_I2S0RXSD 0x00000809//// GPIO pin A3//#define GPIO_PA3_SSI0FSS 0x00000c01#define GPIO_PA3_PWM5 0x00000c04#define GPIO_PA3_I2S0RXMCLK 0x00000c09//// GPIO pin A4//#define GPIO_PA4_SSI0RX 0x00001001#define GPIO_PA4_PWM6 0x00001004#define GPIO_PA4_CAN0RX 0x00001005#define GPIO_PA4_I2S0TXSCK 0x00001009//// GPIO pin A5//#define GPIO_PA5_SSI0TX 0x00001401#define GPIO_PA5_PWM7 0x00001404#define GPIO_PA5_CAN0TX 0x00001405#define GPIO_PA5_I2S0TXWS 0x00001409//// GPIO pin A6//#define GPIO_PA6_I2C1SCL 0x00001801#define GPIO_PA6_CCP1 0x00001802#define GPIO_PA6_PWM0 0x00001804#define GPIO_PA6_PWM4 0x00001805#define GPIO_PA6_CAN0RX 0x00001806#define GPIO_PA6_USB0EPEN 0x00001808#define GPIO_PA6_U1CTS 0x00001809//// GPIO pin A7//#define GPIO_PA7_I2C1SDA 0x00001c01#define GPIO_PA7_CCP4 0x00001c02#define GPIO_PA7_PWM1 0x00001c04#define GPIO_PA7_PWM5 0x00001c05#define GPIO_PA7_CAN0TX 0x00001c06#define GPIO_PA7_CCP3 0x00001c07#define GPIO_PA7_USB0PFLT 0x00001c08#define GPIO_PA7_U1DCD 0x00001c09//// GPIO pin B0//#define GPIO_PB0_CCP0 0x00010001#define GPIO_PB0_PWM2 0x00010002#define GPIO_PB0_U1RX 0x00010005//// GPIO pin B1//#define GPIO_PB1_CCP2 0x00010401#define GPIO_PB1_PWM3 0x00010402#define GPIO_PB1_CCP1 0x00010404#define GPIO_PB1_U1TX 0x00010405//// GPIO pin B2//#define GPIO_PB2_I2C0SCL 0x00010801#define GPIO_PB2_IDX0 0x00010802#define GPIO_PB2_CCP3 0x00010804#define GPIO_PB2_CCP0 0x00010805#define GPIO_PB2_USB0EPEN 0x00010808//// GPIO pin B3//#define GPIO_PB3_I2C0SDA 0x00010c01#define GPIO_PB3_FAULT0 0x00010c02#define GPIO_PB3_FAULT3 0x00010c04#define GPIO_PB3_USB0PFLT 0x00010c08//// GPIO pin B4//#define GPIO_PB4_U2RX 0x00011004#define GPIO_PB4_CAN0RX 0x00011005#define GPIO_PB4_IDX0 0x00011006#define GPIO_PB4_U1RX 0x00011007#define GPIO_PB4_EPI0S23 0x00011008//// GPIO pin B5//#define GPIO_PB5_C0O 0x00011401#define GPIO_PB5_CCP5 0x00011402#define GPIO_PB5_CCP6 0x00011403#define GPIO_PB5_CCP0 0x00011404#define GPIO_PB5_CAN0TX 0x00011405#define GPIO_PB5_CCP2 0x00011406#define GPIO_PB5_U1TX 0x00011407#define GPIO_PB5_EPI0S22 0x00011408//// GPIO pin B6//#define GPIO_PB6_CCP1 0x00011801#define GPIO_PB6_CCP7 0x00011802#define GPIO_PB6_C0O 0x00011803#define GPIO_PB6_FAULT1 0x00011804#define GPIO_PB6_IDX0 0x00011805#define GPIO_PB6_CCP5 0x00011806#define GPIO_PB6_I2S0TXSCK 0x00011809//// GPIO pin B7//#define GPIO_PB7_NMI 0x00011c04//// GPIO pin C0//#define GPIO_PC0_TCK 0x00020003//// GPIO pin C1//#define GPIO_PC1_TMS 0x00020403//// GPIO pin C2//#define GPIO_PC2_TDI 0x00020803//// GPIO pin C3//#define GPIO_PC3_TDO 0x00020c03//// GPIO pin C4//#define GPIO_PC4_CCP5 0x00021001#define GPIO_PC4_PHA0 0x00021002#define GPIO_PC4_PWM6 0x00021004#define GPIO_PC4_CCP2 0x00021005#define GPIO_PC4_CCP4 0x00021006#define GPIO_PC4_EPI0S2 0x00021008#define GPIO_PC4_CCP1 0x00021009//// GPIO pin C5//#define GPIO_PC5_CCP1 0x00021401#define GPIO_PC5_C1O 0x00021402#define GPIO_PC5_C0O 0x00021403#define GPIO_PC5_FAULT2 0x00021404#define GPIO_PC5_CCP3 0x00021405#define GPIO_PC5_USB0EPEN 0x00021406#define GPIO_PC5_EPI0S3 0x00021408//// GPIO pin C6//#define GPIO_PC6_CCP3 0x00021801#define GPIO_PC6_PHB0 0x00021802#define GPIO_PC6_C2O 0x00021803#define GPIO_PC6_PWM7 0x00021804#define GPIO_PC6_U1RX 0x00021805#define GPIO_PC6_CCP0 0x00021806#define GPIO_PC6_USB0PFLT 0x00021807#define GPIO_PC6_EPI0S4 0x00021808//// GPIO pin C7//#define GPIO_PC7_CCP4 0x00021c01#define GPIO_PC7_PHB0 0x00021c02#define GPIO_PC7_CCP0 0x00021c04#define GPIO_PC7_U1TX 0x00021c05#define GPIO_PC7_USB0PFLT 0x00021c06#define GPIO_PC7_C1O 0x00021c07#define GPIO_PC7_EPI0S5 0x00021c08//// GPIO pin D0//#define GPIO_PD0_PWM0 0x00030001#define GPIO_PD0_CAN0RX 0x00030002#define GPIO_PD0_IDX0 0x00030003#define GPIO_PD0_U2RX 0x00030004#define GPIO_PD0_U1RX 0x00030005#define GPIO_PD0_CCP6 0x00030006#define GPIO_PD0_I2S0RXSCK 0x00030008#define GPIO_PD0_U1CTS 0x00030009//// GPIO pin D1//#define GPIO_PD1_PWM1 0x00030401#define GPIO_PD1_CAN0TX 0x00030402#define GPIO_PD1_PHA0 0x00030403#define GPIO_PD1_U2TX 0x00030404#define GPIO_PD1_U1TX 0x00030405#define GPIO_PD1_CCP7 0x00030406#define GPIO_PD1_I2S0RXWS 0x00030408#define GPIO_PD1_U1DCD 0x00030409#define GPIO_PD1_CCP2 0x0003040a#define GPIO_PD1_PHB1 0x0003040b//// GPIO pin D2//#define GPIO_PD2_U1RX 0x00030801#define GPIO_PD2_CCP6 0x00030802#define GPIO_PD2_PWM2 0x00030803#define GPIO_PD2_CCP5 0x00030804#define GPIO_PD2_EPI0S20 0x00030808//// GPIO pin D3//#define GPIO_PD3_U1TX 0x00030c01#define GPIO_PD3_CCP7 0x00030c02#define GPIO_PD3_PWM3 0x00030c03#define GPIO_PD3_CCP0 0x00030c04#define GPIO_PD3_EPI0S21 0x00030c08//// GPIO pin D4//#define GPIO_PD4_CCP0 0x00031001#define GPIO_PD4_CCP3 0x00031002#define GPIO_PD4_I2S0RXSD 0x00031008#define GPIO_PD4_U1RI 0x00031009#define GPIO_PD4_EPI0S19 0x0003100a//// GPIO pin D5//#define GPIO_PD5_CCP2 0x00031401#define GPIO_PD5_CCP4 0x00031402#define GPIO_PD5_I2S0RXMCLK 0x00031408#define GPIO_PD5_U2RX 0x00031409#define GPIO_PD5_EPI0S28 0x0003140a//// GPIO pin D6//#define GPIO_PD6_FAULT0 0x00031801#define GPIO_PD6_I2S0TXSCK 0x00031808#define GPIO_PD6_U2TX 0x00031809#define GPIO_PD6_EPI0S29 0x0003180a//// GPIO pin D7//#define GPIO_PD7_IDX0 0x00031c01#define GPIO_PD7_C0O 0x00031c02#define GPIO_PD7_CCP1 0x00031c03#define GPIO_PD7_I2S0TXWS 0x00031c08#define GPIO_PD7_U1DTR 0x00031c09#define GPIO_PD7_EPI0S30 0x00031c0a//// GPIO pin E0//#define GPIO_PE0_PWM4 0x00040001#define GPIO_PE0_SSI1CLK 0x00040002#define GPIO_PE0_CCP3 0x00040003#define GPIO_PE0_EPI0S8 0x00040008#define GPIO_PE0_USB0PFLT 0x00040009//// GPIO pin E1//#define GPIO_PE1_PWM5 0x00040401#define GPIO_PE1_SSI1FSS 0x00040402#define GPIO_PE1_FAULT0 0x00040403#define GPIO_PE1_CCP2 0x00040404#define GPIO_PE1_CCP6 0x00040405#define GPIO_PE1_EPI0S9 0x00040408//// GPIO pin E2//#define GPIO_PE2_CCP4 0x00040801#define GPIO_PE2_SSI1RX 0x00040802#define GPIO_PE2_PHB1 0x00040803#define GPIO_PE2_PHA0 0x00040804#define GPIO_PE2_CCP2 0x00040805#define GPIO_PE2_EPI0S24 0x00040808//// GPIO pin E3//#define GPIO_PE3_CCP1 0x00040c01#define GPIO_PE3_SSI1TX 0x00040c02#define GPIO_PE3_PHA1 0x00040c03#define GPIO_PE3_PHB0 0x00040c04#define GPIO_PE3_CCP7 0x00040c05#define GPIO_PE3_EPI0S25 0x00040c08//// GPIO pin E4//#define GPIO_PE4_CCP3 0x00041001#define GPIO_PE4_FAULT0 0x00041004#define GPIO_PE4_U2TX 0x00041005#define GPIO_PE4_CCP2 0x00041006#define GPIO_PE4_I2S0TXWS 0x00041009//// GPIO pin E5//#define GPIO_PE5_CCP5 0x00041401#define GPIO_PE5_I2S0TXSD 0x00041409//// GPIO pin E6//#define GPIO_PE6_PWM4 0x00041801#define GPIO_PE6_C1O 0x00041802#define GPIO_PE6_U1CTS 0x00041809//// GPIO pin E7//#define GPIO_PE7_PWM5 0x00041c01#define GPIO_PE7_C2O 0x00041c02#define GPIO_PE7_U1DCD 0x00041c09//// GPIO pin F0//#define GPIO_PF0_CAN1RX 0x00050001#define GPIO_PF0_PHB0 0x00050002#define GPIO_PF0_PWM0 0x00050003#define GPIO_PF0_I2S0TXSD 0x00050008#define GPIO_PF0_U1DSR 0x00050009//// GPIO pin F1//#define GPIO_PF1_CAN1TX 0x00050401#define GPIO_PF1_IDX1 0x00050402#define GPIO_PF1_PWM1 0x00050403#define GPIO_PF1_I2S0TXMCLK 0x00050408#define GPIO_PF1_U1RTS 0x00050409#define GPIO_PF1_CCP3 0x0005040a//// GPIO pin F2//#define GPIO_PF2_LED1 0x00050801#define GPIO_PF2_PWM4 0x00050802#define GPIO_PF2_PWM2 0x00050804#define GPIO_PF2_SSI1CLK 0x00050809//// GPIO pin F3//#define GPIO_PF3_LED0 0x00050c01#define GPIO_PF3_PWM5 0x00050c02#define GPIO_PF3_PWM3 0x00050c04#define GPIO_PF3_SSI1FSS 0x00050c09//// GPIO pin F4//#define GPIO_PF4_CCP0 0x00051001#define GPIO_PF4_C0O 0x00051002#define GPIO_PF4_FAULT0 0x00051004#define GPIO_PF4_EPI0S12 0x00051008#define GPIO_PF4_SSI1RX 0x00051009//// GPIO pin F5//#define GPIO_PF5_CCP2 0x00051401#define GPIO_PF5_C1O 0x00051402#define GPIO_PF5_EPI0S15 0x00051408#define GPIO_PF5_SSI1TX 0x00051409//// GPIO pin F6//#define GPIO_PF6_CCP1 0x00051801#define GPIO_PF6_C2O 0x00051802#define GPIO_PF6_PHA0 0x00051804#define GPIO_PF6_I2S0TXMCLK 0x00051809#define GPIO_PF6_U1RTS 0x0005180a//// GPIO pin F7//#define GPIO_PF7_CCP4 0x00051c01#define GPIO_PF7_PHB0 0x00051c04#define GPIO_PF7_EPI0S12 0x00051c08#define GPIO_PF7_FAULT1 0x00051c09//// GPIO pin G0//#define GPIO_PG0_U2RX 0x00060001#define GPIO_PG0_PWM0 0x00060002#define GPIO_PG0_I2C1SCL 0x00060003#define GPIO_PG0_PWM4 0x00060004#define GPIO_PG0_USB0EPEN 0x00060007#define GPIO_PG0_EPI0S13 0x00060008//// GPIO pin G1//#define GPIO_PG1_U2TX 0x00060401#define GPIO_PG1_PWM1 0x00060402#define GPIO_PG1_I2C1SDA 0x00060403#define GPIO_PG1_PWM5 0x00060404#define GPIO_PG1_EPI0S14 0x00060408//// GPIO pin G2//#define GPIO_PG2_PWM0 0x00060801#define GPIO_PG2_FAULT0 0x00060804#define GPIO_PG2_IDX1 0x00060808#define GPIO_PG2_I2S0RXSD 0x00060809//// GPIO pin G3//#define GPIO_PG3_PWM1 0x00060c01#define GPIO_PG3_FAULT2 0x00060c04#define GPIO_PG3_FAULT0 0x00060c08#define GPIO_PG3_I2S0RXMCLK 0x00060c09//// GPIO pin G4//#define GPIO_PG4_CCP3 0x00061001#define GPIO_PG4_FAULT1 0x00061004#define GPIO_PG4_EPI0S15 0x00061008#define GPIO_PG4_PWM6 0x00061009#define GPIO_PG4_U1RI 0x0006100a//// GPIO pin G5//#define GPIO_PG5_CCP5 0x00061401#define GPIO_PG5_IDX0 0x00061404#define GPIO_PG5_FAULT1 0x00061405#define GPIO_PG5_PWM7 0x00061408#define GPIO_PG5_I2S0RXSCK 0x00061409#define GPIO_PG5_U1DTR 0x0006140a//// GPIO pin G6//#define GPIO_PG6_PHA1 0x00061801#define GPIO_PG6_PWM6 0x00061804#define GPIO_PG6_FAULT1 0x00061808#define GPIO_PG6_I2S0RXWS 0x00061809#define GPIO_PG6_U1RI 0x0006180a//// GPIO pin G7//#define GPIO_PG7_PHB1 0x00061c01#define GPIO_PG7_PWM7 0x00061c04#define GPIO_PG7_CCP5 0x00061c08#define GPIO_PG7_EPI0S31 0x00061c09//// GPIO pin H0//#define GPIO_PH0_CCP6 0x00070001#define GPIO_PH0_PWM2 0x00070002#define GPIO_PH0_EPI0S6 0x00070008#define GPIO_PH0_PWM4 0x00070009//// GPIO pin H1//#define GPIO_PH1_CCP7 0x00070401#define GPIO_PH1_PWM3 0x00070402#define GPIO_PH1_EPI0S7 0x00070408#define GPIO_PH1_PWM5 0x00070409//// GPIO pin H2//#define GPIO_PH2_IDX1 0x00070801#define GPIO_PH2_C1O 0x00070802#define GPIO_PH2_FAULT3 0x00070804#define GPIO_PH2_EPI0S1 0x00070808//// GPIO pin H3//#define GPIO_PH3_PHB0 0x00070c01#define GPIO_PH3_FAULT0 0x00070c02#define GPIO_PH3_USB0EPEN 0x00070c04#define GPIO_PH3_EPI0S0 0x00070c08//// GPIO pin H4//#define GPIO_PH4_USB0PFLT 0x00071004#define GPIO_PH4_EPI0S10 0x00071008#define GPIO_PH4_SSI1CLK 0x0007100b//// GPIO pin H5//#define GPIO_PH5_EPI0S11 0x00071408#define GPIO_PH5_FAULT2 0x0007140a#define GPIO_PH5_SSI1FSS 0x0007140b//// GPIO pin H6//#define GPIO_PH6_EPI0S26 0x00071808#define GPIO_PH6_PWM4 0x0007180a#define GPIO_PH6_SSI1RX 0x0007180b//// GPIO pin H7//#define GPIO_PH7_EPI0S27 0x00071c08#define GPIO_PH7_PWM5 0x00071c0a#define GPIO_PH7_SSI1TX 0x00071c0b//// GPIO pin J0//#define GPIO_PJ0_EPI0S16 0x00080008#define GPIO_PJ0_PWM0 0x0008000a#define GPIO_PJ0_I2C1SCL 0x0008000b//// GPIO pin J1//#define GPIO_PJ1_EPI0S17 0x00080408#define GPIO_PJ1_USB0PFLT 0x00080409#define GPIO_PJ1_PWM1 0x0008040a#define GPIO_PJ1_I2C1SDA 0x0008040b//// GPIO pin J2//#define GPIO_PJ2_EPI0S18 0x00080808#define GPIO_PJ2_CCP0 0x00080809#define GPIO_PJ2_FAULT0 0x0008080a//// GPIO pin J3//#define GPIO_PJ3_EPI0S19 0x00080c08#define GPIO_PJ3_U1CTS 0x00080c09#define GPIO_PJ3_CCP6 0x00080c0a//// GPIO pin J4//#define GPIO_PJ4_EPI0S28 0x00081008#define GPIO_PJ4_U1DCD 0x00081009#define GPIO_PJ4_CCP4 0x0008100a//// GPIO pin J5//#define GPIO_PJ5_EPI0S29 0x00081408#define GPIO_PJ5_U1DSR 0x00081409#define GPIO_PJ5_CCP2 0x0008140a//// GPIO pin J6//#define GPIO_PJ6_EPI0S30 0x00081808#define GPIO_PJ6_U1RTS 0x00081809#define GPIO_PJ6_CCP1 0x0008180a//// GPIO pin J7//#define GPIO_PJ7_U1DTR 0x00081c09#define GPIO_PJ7_CCP0 0x00081c0a//*****************************************************************************//// Prototypes for the APIs.////*****************************************************************************extern void GPIODirModeSet(unsigned long ulPort, unsigned char ucPins,unsigned long ulPinIO);extern unsigned long GPIODirModeGet(unsigned long ulPort, unsigned char ucPin);extern void GPIOIntTypeSet(unsigned long ulPort, unsigned char ucPins,unsigned long ulIntType);extern unsigned long GPIOIntTypeGet(unsigned long ulPort, unsigned char ucPin);extern void GPIOPadConfigSet(unsigned long ulPort, unsigned char ucPins,unsigned long ulStrength,unsigned long ulPadType);extern void GPIOPadConfigGet(unsigned long ulPort, unsigned char ucPin,unsigned long *pulStrength,unsigned long *pulPadType);extern void GPIOPinIntEnable(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinIntDisable(unsigned long ulPort, unsigned char ucPins);extern long GPIOPinIntStatus(unsigned long ulPort, tBoolean bMasked);extern void GPIOPinIntClear(unsigned long ulPort, unsigned char ucPins);extern void GPIOPortIntRegister(unsigned long ulPort,void (*pfnIntHandler)(void));extern void GPIOPortIntUnregister(unsigned long ulPort);extern long GPIOPinRead(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinWrite(unsigned long ulPort, unsigned char ucPins,unsigned char ucVal);extern void GPIOPinConfigure(unsigned long ulPinConfig);extern void GPIOPinTypeADC(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeCAN(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeComparator(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeGPIOInput(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeGPIOOutput(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeGPIOOutputOD(unsigned long ulPort,unsigned char ucPins);extern void GPIOPinTypeI2C(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeI2S(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypePWM(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeQEI(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeSSI(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeTimer(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeUART(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeUSBAnalog(unsigned long ulPort, unsigned char ucPins);extern void GPIOPinTypeUSBDigital(unsigned long ulPort, unsigned char ucPins);//*****************************************************************************//// Mark the end of the C bindings section for C++ compilers.////*****************************************************************************#ifdef __cplusplus}#endif#endif // __GPIO_H__
123version https://git-lfs.github.com/spec/v1oid sha256:c2c4047638a73619dd98c996d6bbef9cd90c55263be3b4073e7ecb5a6c729d25size 32461123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965//*****************************************************************************//// hibernate.c - Driver for the Hibernation module//// Copyright (c) 2007-2009 Luminary Micro, Inc. All rights reserved.// Software License Agreement//// Luminary Micro, Inc. (LMI) is supplying this software for use solely and// exclusively on LMI's microcontroller products.//// The software is owned by LMI and/or its suppliers, and is protected under// applicable copyright laws. All rights are reserved. You may not combine// this software with "viral" open-source software in order to form a larger// program. Any use in violation of the foregoing restrictions may subject// the user to criminal sanctions under applicable laws, as well as to civil// liability for the breach of the terms and conditions of this license.//// THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED// OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.// LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR// CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.//// This is part of revision 4652 of the Stellaris Peripheral Driver Library.////*****************************************************************************//*****************************************************************************////! \addtogroup hibernate_api//! @{////*****************************************************************************#include "inc/hw_hibernate.h"#include "inc/hw_ints.h"#include "inc/hw_sysctl.h"#include "inc/hw_types.h"#include "driverlib/debug.h"#include "driverlib/hibernate.h"#include "driverlib/interrupt.h"#include "driverlib/sysctl.h"//*****************************************************************************//// The delay in microseconds for writing to the Hibernation module registers.////*****************************************************************************#define DELAY_USECS 95//*****************************************************************************//// The number of processor cycles to execute one pass of the delay loop.////*****************************************************************************#define LOOP_CYCLES 3//*****************************************************************************//// The calculated number of delay loops to achieve the write delay.////*****************************************************************************static unsigned long g_ulWriteDelay;//*****************************************************************************////! \internal//!//! Polls until the write complete (WRC) bit in the hibernate control register//! is set.//!//! \param None.//!//! On non-Fury-class devices, the hibernate module provides an indication when//! any write is completed. This is used to pace writes to the module. This//! function merely polls this bit and returns as soon as it is set. At this//! point, it is safe to perform another write to the module.//!//! \return None.////*****************************************************************************voidHibernateWriteComplete(void){//// Spin until the write complete bit is set.//while(!(HWREG(HIB_CTL) & HIB_CTL_WRC)){}}//*****************************************************************************////! Enables the Hibernation module for operation.//!//! \param ulHibClk is the rate of the clock supplied to the Hibernation//! module.//!//! Enables the Hibernation module for operation. This function should be//! called before any of the Hibernation module features are used.//!//! The peripheral clock will be the same as the processor clock. This will be//! the value returned by SysCtlClockGet(), or it can be explicitly hard-coded//! if it is constant and known (to save the code/execution overhead of a call//! to SysCtlClockGet()).//!//! This function replaces the original HibernateEnable() API and performs the//! same actions. A macro is provided in <tt>hibernate.h</tt> to map the//! original API to this API.//!//! \return None.////*****************************************************************************voidHibernateEnableExpClk(unsigned long ulHibClk){//// Turn on the clock enable bit.//HWREG(HIB_CTL) |= HIB_CTL_CLK32EN;//// For Fury-class devices, compute the number of delay loops that must be// used to achieve the desired delay for writes to the hibernation// registers. This value will be used in calls to SysCtlDelay().//if(CLASS_IS_FURY){g_ulWriteDelay = (((ulHibClk / 1000) * DELAY_USECS) /(1000L * LOOP_CYCLES));g_ulWriteDelay++;}}//*****************************************************************************////! Disables the Hibernation module for operation.//!//! Disables the Hibernation module for operation. After this function is//! called, none of the Hibernation module features are available.//!//! \return None.////*****************************************************************************voidHibernateDisable(void){//// Turn off the clock enable bit.//HWREG(HIB_CTL) &= ~HIB_CTL_CLK32EN;}//*****************************************************************************////! Selects the clock input for the Hibernation module.//!//! \param ulClockInput specifies the clock input.//!//! Configures the clock input for the Hibernation module. The configuration//! option chosen depends entirely on hardware design. The clock input for the//! module will either be a 32.768 kHz oscillator or a 4.194304 MHz crystal.//! The \e ulClockFlags parameter must be one of the following://!//! - \b HIBERNATE_CLOCK_SEL_RAW - use the raw signal from a 32.768 kHz//! oscillator.//! - \b HIBERNATE_CLOCK_SEL_DIV128 - use the crystal input, divided by 128.//!//! \return None.////*****************************************************************************voidHibernateClockSelect(unsigned long ulClockInput){//// Check the arguments.//ASSERT((ulClockInput == HIBERNATE_CLOCK_SEL_RAW) ||(ulClockInput == HIBERNATE_CLOCK_SEL_DIV128));//// Set the clock selection bit according to the parameter.//HWREG(HIB_CTL) = ulClockInput | (HWREG(HIB_CTL) & ~HIB_CTL_CLKSEL);}//*****************************************************************************////! Enables the RTC feature of the Hibernation module.//!//! Enables the RTC in the Hibernation module. The RTC can be used to wake the//! processor from hibernation at a certain time, or to generate interrupts at//! certain times. This function must be called before using any of the RTC//! features of the Hibernation module.//!//! \return None.////*****************************************************************************voidHibernateRTCEnable(void){//// Turn on the RTC enable bit.//HWREG(HIB_CTL) |= HIB_CTL_RTCEN;}//*****************************************************************************////! Disables the RTC feature of the Hibernation module.//!//! Disables the RTC in the Hibernation module. After calling this function//! the RTC features of the Hibernation module will not be available.//!//! \return None.////*****************************************************************************voidHibernateRTCDisable(void){//// Turn off the RTC enable bit.//HWREG(HIB_CTL) &= ~HIB_CTL_RTCEN;}//*****************************************************************************////! Configures the wake conditions for the Hibernation module.//!//! \param ulWakeFlags specifies which conditions should be used for waking.//!//! Enables the conditions under which the Hibernation module will wake. The//! \e ulWakeFlags parameter is the logical OR of any combination of the//! following://!//! - \b HIBERNATE_WAKE_PIN - wake when the external wake pin is asserted.//! - \b HIBERNATE_WAKE_RTC - wake when one of the RTC matches occurs.//!//! \return None.////*****************************************************************************voidHibernateWakeSet(unsigned long ulWakeFlags){//// Check the arguments.//ASSERT(!(ulWakeFlags & ~(HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC)));//// Set the specified wake flags in the control register.//HWREG(HIB_CTL) = (ulWakeFlags |(HWREG(HIB_CTL) &~(HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC)));}//*****************************************************************************////! Gets the currently configured wake conditions for the Hibernation module.//!//! Returns the flags representing the wake configuration for the Hibernation//! module. The return value will be a combination of the following flags://!//! - \b HIBERNATE_WAKE_PIN - wake when the external wake pin is asserted.//! - \b HIBERNATE_WAKE_RTC - wake when one of the RTC matches occurs.//!//! \return Returns flags indicating the configured wake conditions.////*****************************************************************************unsigned longHibernateWakeGet(void){//// Read the wake bits from the control register and return// those bits to the caller.//return(HWREG(HIB_CTL) & (HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC));}//*****************************************************************************////! Configures the low battery detection.//!//! \param ulLowBatFlags specifies behavior of low battery detection.//!//! Enables the low battery detection and whether hibernation is allowed if a//! low battery is detected. If low battery detection is enabled, then a low//! battery condition will be indicated in the raw interrupt status register,//! and can also trigger an interrupt. Optionally, hibernation can be aborted//! if a low battery is detected.//!//! The \e ulLowBatFlags parameter is one of the following values://!//! - \b HIBERNATE_LOW_BAT_DETECT - detect a low battery condition.//! - \b HIBERNATE_LOW_BAT_ABORT - detect a low battery condition, and abort//! hibernation if low battery is detected.//!//! \return None.////*****************************************************************************voidHibernateLowBatSet(unsigned long ulLowBatFlags){//// Check the arguments.//ASSERT((ulLowBatFlags == HIBERNATE_LOW_BAT_DETECT) ||(ulLowBatFlags == HIBERNATE_LOW_BAT_ABORT));//// Set the low battery detect and abort bits in the control register,// according to the parameter.//HWREG(HIB_CTL) = (ulLowBatFlags |(HWREG(HIB_CTL) & ~HIBERNATE_LOW_BAT_ABORT));}//*****************************************************************************////! Gets the currently configured low battery detection behavior.//!//! Returns a value representing the currently configured low battery detection//! behavior. The return value will be one of the following://!//! - \b HIBERNATE_LOW_BAT_DETECT - detect a low battery condition.//! - \b HIBERNATE_LOW_BAT_ABORT - detect a low battery condition, and abort//! hibernation if low battery is detected.//!//! \return Returns a value indicating the configured low battery detection.////*****************************************************************************unsigned longHibernateLowBatGet(void){//// Read the low bat bits from the control register and return those bits to// the caller.//return(HWREG(HIB_CTL) & HIBERNATE_LOW_BAT_ABORT);}//*****************************************************************************////! Sets the value of the real time clock (RTC) counter.//!//! \param ulRTCValue is the new value for the RTC.//!//! Sets the value of the RTC. The RTC will count seconds if the hardware is//! configured correctly. The RTC must be enabled by calling//! HibernateRTCEnable() before calling this function.//!//! \return None.////*****************************************************************************voidHibernateRTCSet(unsigned long ulRTCValue){//// Write the new RTC value to the RTC load register.//HWREG(HIB_RTCLD) = ulRTCValue;//// Add a delay here to enforce the required delay between write accesses to// certain Hibernation module registers.//if(CLASS_IS_FURY){//// Delay a fixed time on Fury-class devices//SysCtlDelay(g_ulWriteDelay);}else{//// Wait for write complete to be signaled on later devices.//HibernateWriteComplete();}}//*****************************************************************************////! Gets the value of the real time clock (RTC) counter.//!//! Gets the value of the RTC and returns it to the caller.//!//! \return Returns the value of the RTC.////*****************************************************************************unsigned longHibernateRTCGet(void){//// Return the value of the RTC counter register to the caller.//return(HWREG(HIB_RTCC));}//*****************************************************************************////! Sets the value of the RTC match 0 register.//!//! \param ulMatch is the value for the match register.//!//! Sets the match 0 register for the RTC. The Hibernation module can be//! configured to wake from hibernation, and/or generate an interrupt when the//! value of the RTC counter is the same as the match register.//!//! \return None.////*****************************************************************************voidHibernateRTCMatch0Set(unsigned long ulMatch){//// Write the new match value to the match register.//HWREG(HIB_RTCM0) = ulMatch;//// Add a delay here to enforce the required delay between write accesses to// certain Hibernation module registers.//if(CLASS_IS_FURY){//// Delay a fixed time on Fury-class devices//SysCtlDelay(g_ulWriteDelay);}else{//// Wait for write complete to be signaled on later devices.//HibernateWriteComplete();}}//*****************************************************************************////! Gets the value of the RTC match 0 register.//!//! Gets the value of the match 0 register for the RTC.//!//! \return Returns the value of the match register.////*****************************************************************************unsigned longHibernateRTCMatch0Get(void){//// Return the value of the match register to the caller.//return(HWREG(HIB_RTCM0));}//*****************************************************************************////! Sets the value of the RTC match 1 register.//!//! \param ulMatch is the value for the match register.//!//! Sets the match 1 register for the RTC. The Hibernation module can be//! configured to wake from hibernation, and/or generate an interrupt when the//! value of the RTC counter is the same as the match register.//!//! \return None.////*****************************************************************************voidHibernateRTCMatch1Set(unsigned long ulMatch){//// Write the new match value to the match register.//HWREG(HIB_RTCM1) = ulMatch;//// Add a delay here to enforce the required delay between write accesses to// certain Hibernation module registers.//if(CLASS_IS_FURY){//// Delay a fixed time on Fury-class devices//SysCtlDelay(g_ulWriteDelay);}else{//// Wait for write complete to be signaled on later devices.//HibernateWriteComplete();}}//*****************************************************************************////! Gets the value of the RTC match 1 register.//!//! Gets the value of the match 1 register for the RTC.//!//! \return Returns the value of the match register.////*****************************************************************************unsigned longHibernateRTCMatch1Get(void){//// Return the value of the match register to the caller.//return(HWREG(HIB_RTCM1));}//*****************************************************************************////! Sets the value of the RTC predivider trim register.//!//! \param ulTrim is the new value for the pre-divider trim register.//!//! Sets the value of the pre-divider trim register. The input time source is//! divided by the pre-divider to achieve a one-second clock rate. Once every//! 64 seconds, the value of the pre-divider trim register is applied to the//! predivider to allow fine-tuning of the RTC rate, in order to make//! corrections to the rate. The software application can make adjustments to//! the predivider trim register to account for variations in the accuracy of//! the input time source. The nominal value is 0x7FFF, and it can be adjusted//! up or down in order to fine-tune the RTC rate.//!//! \return None.////*****************************************************************************voidHibernateRTCTrimSet(unsigned long ulTrim){//// Check the arguments.//ASSERT(ulTrim < 0x10000);//// Write the new trim value to the trim register.//HWREG(HIB_RTCT) = ulTrim;//// Add a delay here to enforce the required delay between write accesses to// certain Hibernation module registers.//if(CLASS_IS_FURY){//// Delay a fixed time on Fury-class devices//SysCtlDelay(g_ulWriteDelay);}else{//// Wait for write complete to be signaled on later devices.//HibernateWriteComplete();}}//*****************************************************************************////! Gets the value of the RTC predivider trim register.//!//! Gets the value of the pre-divider trim register. This function can be used//! to get the current value of the trim register prior to making an adjustment//! by using the HibernateRTCTrimSet() function.//!//! \return None.////*****************************************************************************unsigned longHibernateRTCTrimGet(void){//// Return the value of the trim register to the caller.//return(HWREG(HIB_RTCT));}//*****************************************************************************////! Stores data in the non-volatile memory of the Hibernation module.//!//! \param pulData points to the data that the caller wants to store in the//! memory of the Hibernation module.//! \param ulCount is the count of 32-bit words to store.//!//! Stores a set of data in the Hibernation module non-volatile memory. This//! memory will be preserved when the power to the processor is turned off, and//! can be used to store application state information which will be available//! when the processor wakes. Up to 64 32-bit words can be stored in the//! non-volatile memory. The data can be restored by calling the//! HibernateDataGet() function.//!//! \return None.////*****************************************************************************voidHibernateDataSet(unsigned long *pulData, unsigned long ulCount){unsigned int uIdx;//// Check the arguments.//ASSERT(ulCount <= 64);ASSERT(pulData != 0);//// Loop through all the words to be stored, storing one at a time.//for(uIdx = 0; uIdx < ulCount; uIdx++){//// Write a word to the non-volatile storage area.//HWREG(HIB_DATA + (uIdx * 4)) = pulData[uIdx];//// Add a delay between writes to the data area.//if(CLASS_IS_FURY){//// Delay a fixed time on Fury-class devices//SysCtlDelay(g_ulWriteDelay);}else{//// Wait for write complete to be signaled on later devices.//HibernateWriteComplete();}}}//*****************************************************************************////! Reads a set of data from the non-volatile memory of the Hibernation module.//!//! \param pulData points to a location where the data that is read from the//! Hibernation module will be stored.//! \param ulCount is the count of 32-bit words to read.//!//! Retrieves a set of data from the Hibernation module non-volatile memory//! that was previously stored with the HibernateDataSet() function. The//! caller must ensure that \e pulData points to a large enough memory block to//! hold all the data that is read from the non-volatile memory.//!//! \return None.////*****************************************************************************voidHibernateDataGet(unsigned long *pulData, unsigned long ulCount){unsigned int uIdx;//// Check the arguments.//ASSERT(ulCount <= 64);ASSERT(pulData != 0);//// Loop through all the words to be restored, reading one at a time.//for(uIdx = 0; uIdx < ulCount; uIdx++){//// Read a word from the non-volatile storage area. No delay is// required between reads.//pulData[uIdx] = HWREG(HIB_DATA + (uIdx * 4));}}//*****************************************************************************////! Requests hibernation mode.//!//! This function requests the Hibernation module to disable the external//! regulator, thus removing power from the processor and all peripherals. The//! Hibernation module will remain powered from the battery or auxiliary power//! supply.//!//! The Hibernation module will re-enable the external regulator when one of//! the configured wake conditions occurs (such as RTC match or external//! \b WAKE pin). When the power is restored the processor will go through a//! normal power-on reset. The processor can retrieve saved state information//! with the HibernateDataGet() function. Prior to calling the function to//! request hibernation mode, the conditions for waking must have already been//! set by using the HibernateWakeSet() function.//!//! Note that this function may return because some time may elapse before the//! power is actually removed, or it may not be removed at all. For this//! reason, the processor will continue to execute instructions for some time//! and the caller should be prepared for this function to return. There are//! various reasons why the power may not be removed. For example, if the//! HibernateLowBatSet() function was used to configure an abort if low//! battery is detected, then the power will not be removed if the battery//! voltage is too low. There may be other reasons, related to the external//! circuit design, that a request for hibernation may not actually occur.//!//! For all these reasons, the caller must be prepared for this function to//! return. The simplest way to handle it is to just enter an infinite loop//! and wait for the power to be removed.//!//! \return None.////*****************************************************************************voidHibernateRequest(void){//// Set the bit in the control register to cut main power to the processor.//HWREG(HIB_CTL) |= HIB_CTL_HIBREQ;}//*****************************************************************************////! Enables interrupts for the Hibernation module.//!//! \param ulIntFlags is the bit mask of the interrupts to be enabled.//!//! Enables the specified interrupt sources from the Hibernation module.//!//! The \e ulIntFlags parameter must be the logical OR of any combination of//! the following://!//! - \b HIBERNATE_INT_PIN_WAKE - wake from pin interrupt//! - \b HIBERNATE_INT_LOW_BAT - low battery interrupt//! - \b HIBERNATE_INT_RTC_MATCH_0 - RTC match 0 interrupt//! - \b HIBERNATE_INT_RTC_MATCH_1 - RTC match 1 interrupt//!//! \return None.////*****************************************************************************voidHibernateIntEnable(unsigned long ulIntFlags){//// Check the arguments.//ASSERT(!(ulIntFlags & ~(HIBERNATE_INT_PIN_WAKE | HIBERNATE_INT_LOW_BAT |HIBERNATE_INT_RTC_MATCH_0 |HIBERNATE_INT_RTC_MATCH_1)));//// Set the specified interrupt mask bits.//HWREG(HIB_IM) |= ulIntFlags;}//*****************************************************************************////! Disables interrupts for the Hibernation module.//!//! \param ulIntFlags is the bit mask of the interrupts to be disabled.//!//! Disables the specified interrupt sources from the Hibernation module.//!//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags//! parameter to the HibernateIntEnable() function.//!//! \return None.////*****************************************************************************voidHibernateIntDisable(unsigned long ulIntFlags){//// Check the arguments.//ASSERT(!(ulIntFlags & ~(HIBERNATE_INT_PIN_WAKE | HIBERNATE_INT_LOW_BAT |HIBERNATE_INT_RTC_MATCH_0 |HIBERNATE_INT_RTC_MATCH_1)));//// Clear the specified interrupt mask bits.//HWREG(HIB_IM) &= ~ulIntFlags;}//*****************************************************************************////! Registers an interrupt handler for the Hibernation module interrupt.//!//! \param pfnHandler points to the function to be called when a hibernation//! interrupt occurs.//!//! Registers the interrupt handler in the system interrupt controller. The//! interrupt is enabled at the global level, but individual interrupt sources//! must still be enabled with a call to HibernateIntEnable().//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidHibernateIntRegister(void (*pfnHandler)(void)){//// Register the interrupt handler.//IntRegister(INT_HIBERNATE, pfnHandler);//// Enable the hibernate module interrupt.//IntEnable(INT_HIBERNATE);}//*****************************************************************************////! Unregisters an interrupt handler for the Hibernation module interrupt.//!//! Unregisters the interrupt handler in the system interrupt controller. The//! interrupt is disabled at the global level, and the interrupt handler will//! no longer be called.//!//! \sa IntRegister() for important information about registering interrupt//! handlers.//!//! \return None.////*****************************************************************************voidHibernateIntUnregister(void){//// Disable the hibernate interrupt.//IntDisable(INT_HIBERNATE);//// Unregister the interrupt handler.//IntUnregister(INT_HIBERNATE);}//*****************************************************************************////! Gets the current interrupt status of the Hibernation module.//!//! \param bMasked is false to retrieve the raw interrupt status, and true to//! retrieve the masked interrupt status.//!//! Returns the interrupt status of the Hibernation module. The caller can use//! this to determine the cause of a hibernation interrupt. Either the masked//! or raw interrupt status can be returned.//!//! \return Returns the interrupt status as a bit field with the values as//! described in the HibernateIntEnable() function.////*****************************************************************************unsigned longHibernateIntStatus(tBoolean bMasked){//// Read and return the Hibernation module raw or masked interrupt status.//if(bMasked == true){return(HWREG(HIB_MIS) & 0xf);}else{return(HWREG(HIB_RIS) & 0xf);}}//*****************************************************************************////! Clears pending interrupts from the Hibernation module.//!//! \param ulIntFlags is the bit mask of the interrupts to be cleared.//!//! Clears the specified interrupt sources. This must be done from within the//! interrupt handler or else the handler will be called again upon exit.//!//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags//! parameter to the HibernateIntEnable() function.//!//! \note Since there is a write buffer in the Cortex-M3 processor, it may take//! several clock cycles before the interrupt source is actually cleared.//! Therefore, it is recommended that the interrupt source be cleared early in//! the interrupt handler (as opposed to the very last action) to avoid//! returning from the interrupt handler before the interrupt source is//! actually cleared. Failure to do so may result in the interrupt handler//! being immediately reentered (since NVIC still sees the interrupt source//! asserted).//!//! \return None.////*****************************************************************************voidHibernateIntClear(unsigned long ulIntFlags){//// Check the arguments.//ASSERT(!(ulIntFlags & ~(HIBERNATE_INT_PIN_WAKE | HIBERNATE_INT_LOW_BAT |HIBERNATE_INT_RTC_MATCH_0 |HIBERNATE_INT_RTC_MATCH_1)));//// Write the specified interrupt bits into the interrupt clear register.//HWREG(HIB_IC) |= ulIntFlags;}//*****************************************************************************////! Checks to see if the Hibernation module is already powered up.//!//! This function queries the control register to determine if the module is//! already active. This function can be called at a power-on reset to help//! determine if the reset is due to a wake from hibernation or a cold start.//! If the Hibernation module is already active, then it does not need to be//! re-enabled and its status can be queried immediately.//!//! The software application should also use the HibernateIntStatus() function//! to read the raw interrupt status to determine the cause of the wake. The//! HibernateDataGet() function can be used to restore state. These//! combinations of functions can be used by the software to determine if the//! processor is waking from hibernation and the appropriate action to take as//! a result.//!//! \return Returns \b true if the module is already active, and \b false if//! not.////*****************************************************************************unsigned intHibernateIsActive(void){//// Read the control register, and return true if the module is enabled.//return(HWREG(HIB_CTL) & HIB_CTL_CLK32EN ? 1 : 0);}//*****************************************************************************//// Close the Doxygen group.//! @}////*****************************************************************************
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/demo_v8.pdsprj
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/flash.ld+154-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/croutine.c+386-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/FreeRTOS.h+621-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/StackMacros.h+180-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/croutine.h+758-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/list.h+379-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/mpu_wrappers.h+153-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/portable.h+402-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/projdefs.h+89-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/queue.h+1685-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/semphr.h+840-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/task.h+1520-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/include/timers.h+960-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/list.c+204-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_1.c+170-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_2.c+299-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_3.c+131-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/mem/heap_4.c+391-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/portable/debug.h+32-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/portable/port.c+737-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/portable/portmacro.h+187-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/queue.c+2105-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/tasks.c
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/freertos/timers.c+707-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/make.bat+62-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/include/FreeRTOSConfig.h+96-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/include/serial.h+136-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/main.c+234-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Atmel/freertos_uart/source/serial.c+317-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/DLib_Config_Normal.h+13-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/adc.c+979-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/adc.h+149-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/can.c+2203-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/can.h+459-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/comp.c+439-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/comp.h+133-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/cpu.c+189-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/cpu.h+60-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/debug.h+56-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/driverlib.ewp+867-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/epi.c+1039-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/epi.h+229-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/ethernet.c+1280-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/ethernet.h+172-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/flash.c+915-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/flash.h+89-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/gpio.c+1512-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/gpio.h+768-3
Proteus 8 Professional/DATA/SAMPLES/VSM for Cortex M3/Stellaris/adc_oversampling/driverlib/hibernate.c+965-3