2 FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
5 VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
7 This file is part of the FreeRTOS distribution.
9 FreeRTOS is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License (version 2) as published by the
11 Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
13 ***************************************************************************
14 >>! NOTE: The modification to the GPL is included to allow you to !<<
15 >>! distribute a combined work that includes FreeRTOS without being !<<
16 >>! obliged to provide the source code for proprietary components !<<
17 >>! outside of the FreeRTOS kernel. !<<
18 ***************************************************************************
20 FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22 FOR A PARTICULAR PURPOSE. Full license text is available on the following
23 link: http://www.freertos.org/a00114.html
25 ***************************************************************************
27 * FreeRTOS provides completely free yet professionally developed, *
28 * robust, strictly quality controlled, supported, and cross *
29 * platform software that is more than just the market leader, it *
30 * is the industry's de facto standard. *
32 * Help yourself get started quickly while simultaneously helping *
33 * to support the FreeRTOS project by purchasing a FreeRTOS *
34 * tutorial book, reference manual, or both: *
35 * http://www.FreeRTOS.org/Documentation *
37 ***************************************************************************
39 http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
40 the FAQ page "My application does not run, what could be wrong?". Have you
41 defined configASSERT()?
43 http://www.FreeRTOS.org/support - In return for receiving this top quality
44 embedded software for free we request you assist our global community by
45 participating in the support forum.
47 http://www.FreeRTOS.org/training - Investing in training allows your team to
48 be as productive as possible as early as possible. Now you can receive
49 FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50 Ltd, and the world's leading authority on the world's leading RTOS.
52 http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53 including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54 compatible FAT file system, and our tiny thread aware UDP/IP stack.
56 http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57 Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
59 http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60 Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
61 licenses offer ticketed support, indemnification and commercial middleware.
63 http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64 engineered and independently SIL3 certified version for use in safety and
65 mission critical applications that require provable dependability.
71 * The documentation page for this demo available on http://www.FreeRTOS.org
72 * documents the hardware configuration required to run this demo. It also
73 * provides more information on the expected demo application behaviour.
75 * main() creates all the demo application tasks, then starts the scheduler.
76 * A lot of the created tasks are from the pool of "standard demo" tasks. The
77 * web documentation provides more details of the standard demo tasks, which
78 * provide no particular functionality but do provide good examples of how to
79 * use the FreeRTOS API.
81 * In addition to the standard demo tasks, the following tasks, interrupts and
82 * tests are defined and/or created within this file:
84 * "LCD" task - The LCD task is a 'gatekeeper' task. It is the only task that
85 * is permitted to access the LCD and therefore ensures access to the LCD is
86 * always serialised and there are no mutual exclusion issues. When a task or
87 * an interrupt wants to write to the LCD, it does not access the LCD directly
88 * but instead sends the message to the LCD task. The LCD task then performs
89 * the actual LCD output. This mechanism also allows interrupts to, in effect,
90 * write to the LCD by sending messages to the LCD task.
92 * The LCD task is also a demonstration of a 'controller' task design pattern.
93 * Some tasks do not actually send a string to the LCD task directly, but
94 * instead send a command that is interpreted by the LCD task. In a normal
95 * application these commands can be control values or set points, in this
96 * simple example the commands just result in messages being displayed on the
99 * "Button Poll" task - This task polls the state of the 'up' key on the
100 * joystick input device. It uses the vTaskDelay() API function to control
101 * the poll rate to ensure debouncing is not necessary and that the task does
102 * not use all the available CPU processing time.
104 * Button Interrupt and run time stats display - The select button on the
105 * joystick input device is configured to generate an external interrupt. The
106 * handler for this interrupt sends a message to LCD task, which interprets the
107 * message to mean, firstly write a message to the LCD, and secondly, generate
108 * a table of run time statistics. The run time statistics are displayed as a
109 * table that contains information on how much processing time each task has
110 * been allocated since the application started to execute. This information
111 * is provided both as an absolute time, and as a percentage of the total run
112 * time. The information is displayed in the terminal IO window of the IAR
113 * embedded workbench. The online documentation for this demo shows a screen
114 * shot demonstrating where the run time stats can be viewed.
116 * Idle Hook - The idle hook is a function that is called on each iteration of
117 * the idle task. In this case it is used to place the processor into a low
118 * power mode. Note however that this application is implemented using standard
119 * components, and is therefore not optimised for low power operation. Lower
120 * power consumption would be achieved by converting polling tasks into event
121 * driven tasks, and slowing the tick interrupt frequency.
123 * "Check" function called from the tick hook - The tick hook is called during
124 * each tick interrupt. It is called from an interrupt context so must execute
125 * quickly, not attempt to block, and not call any FreeRTOS API functions that
126 * do not end in "FromISR". In this case the tick hook executes a 'check'
127 * function. This only executes every five seconds. Its main function is to
128 * check that all the standard demo tasks are still operational. Each time it
129 * executes it sends a status code to the LCD task. The LCD task interprets the
130 * code and displays an appropriate message - which will be PASS if no tasks
131 * have reported any errors, or a message stating which task has reported an
135 /* Standard includes. */
138 /* Kernel includes. */
139 #include "FreeRTOS.h"
143 /* Demo application includes. */
147 #include "comtest2.h"
148 #include "GenQTest.h"
150 /* Eval board includes. */
151 #include "stm32_eval.h"
152 #include "stm32l152_eval_lcd.h"
154 /* The priorities assigned to the tasks. */
155 #define mainFLASH_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
156 #define mainLCD_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
157 #define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 )
158 #define mainGENERIC_QUEUE_TEST_PRIORITY ( tskIDLE_PRIORITY )
160 /* The length of the queue (the number of items the queue can hold) that is used
161 to send messages from tasks and interrupts the the LCD task. */
162 #define mainQUEUE_LENGTH ( 5 )
164 /* Codes sent within messages to the LCD task so the LCD task can interpret
165 exactly what the message it just received was. These are sent in the
166 cMessageID member of the message structure (defined below). */
167 #define mainMESSAGE_BUTTON_UP ( 1 )
168 #define mainMESSAGE_BUTTON_SEL ( 2 )
169 #define mainMESSAGE_STATUS ( 3 )
171 /* When the cMessageID member of the message sent to the LCD task is
172 mainMESSAGE_STATUS then these definitions are sent in the lMessageValue member
173 of the same message and indicate what the status actually is. */
174 #define mainERROR_DYNAMIC_TASKS ( pdPASS + 1 )
175 #define mainERROR_COM_TEST ( pdPASS + 2 )
176 #define mainERROR_GEN_QUEUE_TEST ( pdPASS + 3 )
178 /* Baud rate used by the comtest tasks. */
179 #define mainCOM_TEST_BAUD_RATE ( 115200 )
181 /* The LED used by the comtest tasks. See the comtest.c file for more
183 #define mainCOM_TEST_LED ( 3 )
185 /* The LCD task uses printf() so requires more stack than most of the other
187 #define mainLCD_TASK_STACK_SIZE ( configMINIMAL_STACK_SIZE * 2 )
189 /*-----------------------------------------------------------*/
192 * System configuration is performed prior to main() being called, this function
193 * configures the peripherals used by the demo application.
195 static void prvSetupHardware( void );
198 * Definition of the LCD/controller task described in the comments at the top
201 static void prvLCDTask( void *pvParameters );
204 * Definition of the button poll task described in the comments at the top of
207 static void prvButtonPollTask( void *pvParameters );
210 * Converts a status message value into an appropriate string for display on
211 * the LCD. The string is written to pcBuffer.
213 static void prvGenerateStatusMessage( char *pcBuffer, long lStatusValue );
215 /*-----------------------------------------------------------*/
217 /* The time base for the run time stats is generated by the 16 bit timer 6.
218 Each time the timer overflows ulTIM6_OverflowCount is incremented. Therefore,
219 when converting the total run time to a 32 bit number, the most significant two
220 bytes are given by ulTIM6_OverflowCount and the least significant two bytes are
221 given by the current TIM6 counter value. Care must be taken with data
222 consistency when combining the two in case a timer overflow occurs as the
223 value is being read. */
224 unsigned long ulTIM6_OverflowCount = 0UL;
226 /* The handle of the queue used to send messages from tasks and interrupts to
228 static QueueHandle_t xLCDQueue = NULL;
230 /* The definition of each message sent from tasks and interrupts to the LCD
234 char cMessageID; /* << States what the message is. */
235 long lMessageValue; /* << States the message value (can be an integer, string pointer, etc. depending on the value of cMessageID). */
238 /*-----------------------------------------------------------*/
242 /* Configure the peripherals used by this demo application. This includes
243 configuring the joystick input select button to generate interrupts. */
246 /* Create the queue used by tasks and interrupts to send strings to the LCD
248 xLCDQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( xQueueMessage ) );
250 /* If the queue could not be created then don't create any tasks that might
251 attempt to use the queue. */
252 if( xLCDQueue != NULL )
254 /* Add the created queue to the queue registry so it can be viewed in
255 the IAR FreeRTOS state viewer plug-in. */
256 vQueueAddToRegistry( xLCDQueue, "LCDQueue" );
258 /* Create the LCD and button poll tasks, as described at the top of this
260 xTaskCreate( prvLCDTask, "LCD", mainLCD_TASK_STACK_SIZE, NULL, mainLCD_TASK_PRIORITY, NULL );
261 xTaskCreate( prvButtonPollTask, "ButPoll", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
263 /* Create a subset of the standard demo tasks. */
264 vStartDynamicPriorityTasks();
265 vStartLEDFlashTasks( mainFLASH_TASK_PRIORITY );
266 vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainCOM_TEST_BAUD_RATE, mainCOM_TEST_LED );
267 vStartGenericQueueTasks( mainGENERIC_QUEUE_TEST_PRIORITY );
269 /* Start the scheduler. */
270 vTaskStartScheduler();
273 /* If all is well then this line will never be reached. If it is reached
274 then it is likely that there was insufficient (FreeRTOS) heap memory space
275 to create the idle task. This may have been trapped by the malloc() failed
276 hook function, if one is configured. */
279 /*-----------------------------------------------------------*/
281 static void prvLCDTask( void *pvParameters )
283 xQueueMessage xReceivedMessage;
285 const long lFontHeight = (((sFONT *)LCD_GetFont())->Height);
287 /* Buffer into which strings are formatted and placed ready for display on the
288 LCD. Note this is a static variable to prevent it being allocated on the task
289 stack, which is too small to hold such a variable. The stack size is configured
290 when the task is created. */
291 static char cBuffer[ 512 ];
293 /* This function is the only function that uses printf(). If printf() is
294 used from any other function then some sort of mutual exclusion on stdout
297 This is also the only function that is permitted to access the LCD.
299 First print out the number of bytes that remain in the FreeRTOS heap. This
300 can be viewed in the terminal IO window within the IAR Embedded Workbench. */
301 printf( "%d bytes of heap space remain unallocated\n", xPortGetFreeHeapSize() );
305 /* Wait for a message to be received. Using portMAX_DELAY as the block
306 time will result in an indefinite wait provided INCLUDE_vTaskSuspend is
307 set to 1 in FreeRTOSConfig.h, therefore there is no need to check the
308 function return value and the function will only return when a value
309 has been received. */
310 xQueueReceive( xLCDQueue, &xReceivedMessage, portMAX_DELAY );
312 /* Clear the LCD if no room remains for any more text output. */
319 /* What is this message? What does it contain? */
320 switch( xReceivedMessage.cMessageID )
322 case mainMESSAGE_BUTTON_UP : /* The button poll task has just
323 informed this task that the up
324 button on the joystick input has
325 been pressed or released. */
326 sprintf( cBuffer, "Button up = %d", xReceivedMessage.lMessageValue );
329 case mainMESSAGE_BUTTON_SEL : /* The select button interrupt
330 just informed this task that the
331 select button was pressed.
332 Generate a table of task run time
333 statistics and output this to
334 the terminal IO window in the IAR
335 embedded workbench. */
336 printf( "\nTask\t Abs Time\t %%Time\n*****************************************" );
337 vTaskGetRunTimeStats( cBuffer );
340 /* Also print out a message to
341 the LCD - in this case the
342 pointer to the string to print
343 is sent directly in the
344 lMessageValue member of the
345 message. This just demonstrates
346 a different communication
348 sprintf( cBuffer, "%s", ( char * ) xReceivedMessage.lMessageValue );
351 case mainMESSAGE_STATUS : /* The tick interrupt hook
352 function has just informed this
353 task of the system status.
354 Generate a string in accordance
355 with the status value. */
356 prvGenerateStatusMessage( cBuffer, xReceivedMessage.lMessageValue );
359 default : sprintf( cBuffer, "Unknown message" );
363 /* Output the message that was placed into the cBuffer array within the
364 switch statement above. */
365 LCD_DisplayStringLine( lLine, ( uint8_t * ) cBuffer );
367 /* Move onto the next LCD line, ready for the next iteration of this
369 lLine += lFontHeight;
372 /*-----------------------------------------------------------*/
374 static void prvGenerateStatusMessage( char *pcBuffer, long lStatusValue )
376 /* Just a utility function to convert a status value into a meaningful
377 string for output onto the LCD. */
378 switch( lStatusValue )
380 case pdPASS : sprintf( pcBuffer, "Task status = PASS" );
382 case mainERROR_DYNAMIC_TASKS : sprintf( pcBuffer, "Error: Dynamic tasks" );
384 case mainERROR_COM_TEST : sprintf( pcBuffer, "Err: loop connected?" ); /* Error in COM test - is the Loopback connector connected? */
386 case mainERROR_GEN_QUEUE_TEST : sprintf( pcBuffer, "Error: Gen Q test" );
388 default : sprintf( pcBuffer, "Unknown status" );
392 /*-----------------------------------------------------------*/
394 void EXTI9_5_IRQHandler( void )
396 /* Define the message sent to the LCD task from this interrupt. */
397 const xQueueMessage xMessage = { mainMESSAGE_BUTTON_SEL, ( unsigned long ) "Select Interrupt!" };
398 long lHigherPriorityTaskWoken = pdFALSE;
400 /* This is the interrupt handler for the joystick select button input.
401 The button has been pushed, write a message to the LCD via the LCD task. */
402 xQueueSendFromISR( xLCDQueue, &xMessage, &lHigherPriorityTaskWoken );
404 EXTI_ClearITPendingBit( SEL_BUTTON_EXTI_LINE );
406 /* If writing to xLCDQueue caused a task to unblock, and the unblocked task
407 has a priority equal to or above the task that this interrupt interrupted,
408 then lHigherPriorityTaskWoken will have been set to pdTRUE internally within
409 xQueuesendFromISR(), and portEND_SWITCHING_ISR() will ensure that this
410 interrupt returns directly to the higher priority unblocked task. */
411 portEND_SWITCHING_ISR( lHigherPriorityTaskWoken );
413 /*-----------------------------------------------------------*/
415 void vApplicationTickHook( void )
417 static unsigned long ulCounter = 0;
418 static const unsigned long ulCheckFrequency = 5000UL / portTICK_PERIOD_MS;
419 long lHigherPriorityTaskWoken = pdFALSE;
421 /* Define the status message that is sent to the LCD task. By default the
423 static xQueueMessage xStatusMessage = { mainMESSAGE_STATUS, pdPASS };
425 /* This is called from within the tick interrupt and performs the 'check'
426 functionality as described in the comments at the top of this file.
428 Is it time to perform the 'check' functionality again? */
430 if( ulCounter >= ulCheckFrequency )
432 /* See if the standard demo tasks are executing as expected, changing
433 the message that is sent to the LCD task from PASS to an error code if
434 any tasks set reports an error. */
435 if( xAreDynamicPriorityTasksStillRunning() != pdPASS )
437 xStatusMessage.lMessageValue = mainERROR_DYNAMIC_TASKS;
440 if( xAreComTestTasksStillRunning() != pdPASS )
442 xStatusMessage.lMessageValue = mainERROR_COM_TEST;
445 if( xAreGenericQueueTasksStillRunning() != pdPASS )
447 xStatusMessage.lMessageValue = mainERROR_GEN_QUEUE_TEST;
450 /* As this is the tick hook the lHigherPriorityTaskWoken parameter is not
451 needed (a context switch is going to be performed anyway), but it must
452 still be provided. */
453 xQueueSendFromISR( xLCDQueue, &xStatusMessage, &lHigherPriorityTaskWoken );
457 /*-----------------------------------------------------------*/
459 static void prvButtonPollTask( void *pvParameters )
461 long lLastState = pdTRUE;
463 xQueueMessage xMessage;
465 /* This tasks performs the button polling functionality as described at the
469 /* Check the button state. */
470 lState = STM_EVAL_PBGetState( BUTTON_UP );
471 if( lState != lLastState )
473 /* The state has changed, send a message to the LCD task. */
474 xMessage.cMessageID = mainMESSAGE_BUTTON_UP;
475 xMessage.lMessageValue = lState;
477 xQueueSend( xLCDQueue, &xMessage, portMAX_DELAY );
480 /* Block for 10 milliseconds so this task does not utilise all the CPU
481 time and debouncing of the button is not necessary. */
482 vTaskDelay( 10 / portTICK_PERIOD_MS );
485 /*-----------------------------------------------------------*/
487 static void prvSetupHardware( void )
489 /* Ensure that all 4 interrupt priority bits are used as the pre-emption
491 NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 );
493 /* Initialise the LEDs. */
494 vParTestInitialise();
496 /* Initialise the joystick inputs. */
497 STM_EVAL_PBInit( BUTTON_UP, BUTTON_MODE_GPIO );
498 STM_EVAL_PBInit( BUTTON_DOWN, BUTTON_MODE_GPIO );
499 STM_EVAL_PBInit( BUTTON_LEFT, BUTTON_MODE_GPIO );
500 STM_EVAL_PBInit( BUTTON_RIGHT, BUTTON_MODE_GPIO );
502 /* The select button in the middle of the joystick is configured to generate
503 an interrupt. The Eval board library will configure the interrupt
504 priority to be the lowest priority available so the priority need not be
505 set here explicitly. It is important that the priority is equal to or
506 below that set by the configMAX_SYSCALL_INTERRUPT_PRIORITY value set in
508 STM_EVAL_PBInit( BUTTON_SEL, BUTTON_MODE_EXTI );
510 /* Initialize the LCD */
511 STM32L152_LCD_Init();
513 LCD_SetBackColor( Blue );
514 LCD_SetTextColor( White );
515 LCD_DisplayStringLine( Line0, " www.FreeRTOS.org" );
517 /*-----------------------------------------------------------*/
519 void vConfigureTimerForRunTimeStats( void )
521 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
522 NVIC_InitTypeDef NVIC_InitStructure;
524 /* The time base for the run time stats is generated by the 16 bit timer 6.
525 Each time the timer overflows ulTIM6_OverflowCount is incremented.
526 Therefore, when converting the total run time to a 32 bit number, the most
527 significant two bytes are given by ulTIM6_OverflowCount and the least
528 significant two bytes are given by the current TIM6 counter value. Care
529 must be taken with data consistency when combining the two in case a timer
530 overflow occurs as the value is being read.
532 The portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro (in FreeRTOSConfig.h) is
533 defined to call this function, so the kernel will call this function
534 automatically at the appropriate time. */
536 /* TIM6 clock enable */
537 RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM6, ENABLE );
539 /* The 32MHz clock divided by 5000 should tick (very) approximately every
540 150uS and overflow a 16bit timer (very) approximately every 10 seconds. */
541 TIM_TimeBaseStructure.TIM_Period = 65535;
542 TIM_TimeBaseStructure.TIM_Prescaler = 5000;
543 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
544 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
546 TIM_TimeBaseInit( TIM6, &TIM_TimeBaseStructure );
548 /* Only interrupt on overflow events. */
549 TIM6->CR1 |= TIM_CR1_URS;
551 /* Enable the interrupt. */
552 TIM_ITConfig( TIM6, TIM_IT_Update, ENABLE );
554 /* Enable the TIM6 global Interrupt */
555 NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn;
556 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY;
557 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; /* Not used as 4 bits are used for the pre-emption priority. */
558 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
559 NVIC_Init(&NVIC_InitStructure);
561 TIM_ClearITPendingBit( TIM6, TIM_IT_Update );
562 TIM_Cmd( TIM6, ENABLE );
564 /*-----------------------------------------------------------*/
566 void TIM6_IRQHandler( void )
568 /* Interrupt handler for TIM 6
570 The time base for the run time stats is generated by the 16 bit timer 6.
571 Each time the timer overflows ulTIM6_OverflowCount is incremented.
572 Therefore, when converting the total run time to a 32 bit number, the most
573 significant two bytes are given by ulTIM6_OverflowCount and the least
574 significant two bytes are given by the current TIM6 counter value. Care
575 must be taken with data consistency when combining the two in case a timer
576 overflow occurs as the value is being read. */
577 if( TIM_GetITStatus( TIM6, TIM_IT_Update) != RESET)
579 ulTIM6_OverflowCount++;
580 TIM_ClearITPendingBit( TIM6, TIM_IT_Update );
583 /*-----------------------------------------------------------*/
585 void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
590 /* Run time stack overflow checking is performed if
591 configconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
592 function is called if a stack overflow is detected. */
595 /*-----------------------------------------------------------*/
597 void vApplicationMallocFailedHook( void )
599 /* Called if a call to pvPortMalloc() fails because there is insufficient
600 free memory available in the FreeRTOS heap. pvPortMalloc() is called
601 internally by FreeRTOS API functions that create tasks, queues or
605 /*-----------------------------------------------------------*/
607 void vApplicationIdleHook( void )
609 /* Called on each iteration of the idle task. In this case the idle task
610 just enters a low(ish) power mode. */
611 PWR_EnterSleepMode( PWR_Regulator_ON, PWR_SLEEPEntry_WFI );