3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 * the Software, and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 * http://www.FreeRTOS.org
23 * http://aws.amazon.com/freertos
29 * The documentation page for this demo available on http://www.FreeRTOS.org
30 * documents the hardware configuration required to run this demo. It also
31 * provides more information on the expected demo application behaviour.
33 * main() creates all the demo application tasks, then starts the scheduler.
34 * A lot of the created tasks are from the pool of "standard demo" tasks. The
35 * web documentation provides more details of the standard demo tasks, which
36 * provide no particular functionality but do provide good examples of how to
37 * use the FreeRTOS API.
39 * In addition to the standard demo tasks, the following tasks, interrupts tests
40 * and timers are defined and/or created within this file:
42 * "LCD" task - The LCD task is a 'gatekeeper' task. It is the only task that
43 * is permitted to access the LCD and therefore ensures access to the LCD is
44 * always serialised and there are no mutual exclusion issues. When a task or
45 * an interrupt wants to write to the LCD, it does not access the LCD directly
46 * but instead sends the message to the LCD task. The LCD task then performs
47 * the actual LCD output. This mechanism also allows interrupts to, in effect,
48 * write to the LCD by sending messages to the LCD task.
50 * The LCD task is also a demonstration of a 'controller' task design pattern.
51 * Some tasks do not actually send a string to the LCD task directly, but
52 * instead send a command that is interpreted by the LCD task. In a normal
53 * application these commands can be control values or set points, in this
54 * simple example the commands just result in messages being displayed on the
57 * "Button Poll" task - This task polls the state of the 'up' key on the
58 * joystick input device. It uses the vTaskDelay() API function to control
59 * the poll rate to ensure debouncing is not necessary and that the task does
60 * not use all the available CPU processing time.
62 * Button Interrupt - The select button on the joystick input device is
63 * configured to generate an external interrupt. The handler for this interrupt
64 * sends a message to LCD task, which then prints out a string to say the
65 * joystick select button was pressed.
67 * Idle Hook - The idle hook is a function that is called on each iteration of
68 * the idle task. In this case it is used to place the processor into a low
69 * power mode. Note however that this application is implemented using standard
70 * components, and is therefore not optimised for low power operation. Lower
71 * power consumption would be achieved by converting polling tasks into event
72 * driven tasks, and slowing the tick interrupt frequency, etc.
74 * "Check" callback function - Called each time the 'check' timer expires. The
75 * check timer executes every five seconds. Its main function is to check that
76 * all the standard demo tasks are still operational. Each time it executes it
77 * sends a status code to the LCD task. The LCD task interprets the code and
78 * displays an appropriate message - which will be PASS if no tasks have
79 * reported any errors, or a message stating which task has reported an error.
81 * "Reg test" tasks - These fill the registers with known values, then check
82 * that each register still contains its expected value. Each task uses
83 * different values. The tasks run with very low priority so get preempted
84 * very frequently. A check variable is incremented on each iteration of the
85 * test loop. A register containing an unexpected value is indicative of an
86 * error in the context switching mechanism and will result in a branch to a
87 * null loop - which in turn will prevent the check variable from incrementing
88 * any further and allow the check timer callback (described a above) to
89 * determine that an error has occurred. The nature of the reg test tasks
90 * necessitates that they are written in assembly code.
92 * Tick hook function - called inside the RTOS tick function, this simple
93 * example does nothing but toggle an LED.
95 * *NOTE 1* vApplicationSetupTimerInterrupt() is called by the kernel to let
96 * the application set up a timer to generate the tick interrupt. In this
97 * example a timer A0 is used for this purpose.
101 /* Standard includes. */
104 /* FreeRTOS includes. */
105 #include "FreeRTOS.h"
110 /* Hardware includes. */
112 #include "hal_MSP-EXP430F5438.h"
114 /* Standard demo includes. */
117 #include "comtest2.h"
118 #include "GenQTest.h"
119 #include "TimerDemo.h"
120 #include "countsem.h"
122 /* Codes sent within messages to the LCD task so the LCD task can interpret
123 exactly what the message it just received was. These are sent in the
124 cMessageID member of the message structure (defined below). */
125 #define mainMESSAGE_BUTTON_UP ( 1 )
126 #define mainMESSAGE_BUTTON_SEL ( 2 )
127 #define mainMESSAGE_STATUS ( 3 )
129 /* When the cMessageID member of the message sent to the LCD task is
130 mainMESSAGE_STATUS then these definitions are sent in the ulMessageValue member
131 of the same message and indicate what the status actually is. */
132 #define mainERROR_DYNAMIC_TASKS ( pdPASS + 1 )
133 #define mainERROR_COM_TEST ( pdPASS + 2 )
134 #define mainERROR_GEN_QUEUE_TEST ( pdPASS + 3 )
135 #define mainERROR_REG_TEST ( pdPASS + 4 )
136 #define mainERROR_TIMER_TEST ( pdPASS + 5 )
137 #define mainERROR_COUNT_SEM_TEST ( pdPASS + 6 )
139 /* The length of the queue (the number of items the queue can hold) that is used
140 to send messages from tasks and interrupts the the LCD task. */
141 #define mainQUEUE_LENGTH ( 5 )
143 /* Priorities used by the test and demo tasks. */
144 #define mainLCD_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
145 #define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 )
146 #define mainGENERIC_QUEUE_TEST_PRIORITY ( tskIDLE_PRIORITY )
148 /* The LED used by the comtest tasks. See the comtest.c file for more
150 #define mainCOM_TEST_LED ( 1 )
152 /* The baud rate used by the comtest tasks. */
153 #define mainCOM_TEST_BAUD_RATE ( 38400 )
155 /* The maximum number of lines of text that can be displayed on the LCD. */
156 #define mainMAX_LCD_LINES ( 8 )
158 /* Just used to ensure parameters are passed into tasks correctly. */
159 #define mainTASK_PARAMETER_CHECK_VALUE ( ( void * ) 0xDEAD )
161 /* The base period used by the timer test tasks. */
162 #define mainTIMER_TEST_PERIOD ( 50 )
164 /* The frequency at which the check timer (described in the comments at the top
165 of this file) will call its callback function. */
166 #define mainCHECK_TIMER_PERIOD ( 5000UL / ( unsigned long ) portTICK_PERIOD_MS )
169 #define mainDONT_BLOCK ( 0 )
170 /*-----------------------------------------------------------*/
173 * The reg test tasks as described at the top of this file.
175 extern void vRegTest1Task( void *pvParameters );
176 extern void vRegTest2Task( void *pvParameters );
179 * Configures clocks, LCD, port pints, etc. necessary to execute this demo.
181 static void prvSetupHardware( void );
184 * Definition of the LCD/controller task described in the comments at the top
187 static void prvLCDTask( void *pvParameters );
190 * Definition of the button poll task described in the comments at the top of
193 static void prvButtonPollTask( void *pvParameters );
196 * Converts a status message value into an appropriate string for display on
197 * the LCD. The string is written to pcBuffer.
199 static void prvGenerateStatusMessage( char *pcBuffer, unsigned long ulStatusValue );
202 * Defines the 'check' functionality as described at the top of this file. This
203 * function is the callback function for the 'check' timer. */
204 static void vCheckTimerCallback( TimerHandle_t xTimer );
206 /*-----------------------------------------------------------*/
208 /* Variables that are incremented on each iteration of the reg test tasks -
209 provided the tasks have not reported any errors. The check task inspects these
210 variables to ensure they are still incrementing as expected. If a variable
211 stops incrementing then it is likely that its associate task has stalled. */
212 volatile unsigned short usRegTest1Counter = 0, usRegTest2Counter = 0;
214 /* The handle of the queue used to send messages from tasks and interrupts to
216 static QueueHandle_t xLCDQueue = NULL;
218 /* The 'check' timer, as described at the top of this file. */
219 static TimerHandle_t xCheckTimer = NULL;
221 /* The definition of each message sent from tasks and interrupts to the LCD
225 char cMessageID; /* << States what the message is. */
226 unsigned long ulMessageValue; /* << States the message value (can be an integer, string pointer, etc. depending on the value of cMessageID). */
229 /*-----------------------------------------------------------*/
233 /* Configure the peripherals used by this demo application. This includes
234 configuring the joystick input select button to generate interrupts. */
237 /* Create the queue used by tasks and interrupts to send strings to the LCD
239 xLCDQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( xQueueMessage ) );
241 /* If the queue could not be created then don't create any tasks that might
242 attempt to use the queue. */
243 if( xLCDQueue != NULL )
245 /* Create the standard demo tasks. */
246 vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainCOM_TEST_BAUD_RATE, mainCOM_TEST_LED );
247 vStartDynamicPriorityTasks();
248 vStartGenericQueueTasks( mainGENERIC_QUEUE_TEST_PRIORITY );
249 vStartCountingSemaphoreTasks();
251 /* Note that creating the timer test/demo tasks will fill the timer
252 command queue. This is intentional, and forms part of the test the tasks
253 perform. It does mean however that, after this function is called, no
254 more timer commands can be sent until after the scheduler has been
255 started (at which point the timer daemon will drained the timer command
256 queue, freeing up space for more commands to be received). */
257 vStartTimerDemoTask( mainTIMER_TEST_PERIOD );
259 /* Create the LCD, button poll and register test tasks, as described at
260 the top of this file. */
261 xTaskCreate( prvLCDTask, "LCD", configMINIMAL_STACK_SIZE * 2, mainTASK_PARAMETER_CHECK_VALUE, mainLCD_TASK_PRIORITY, NULL );
262 xTaskCreate( prvButtonPollTask, "BPoll", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
263 xTaskCreate( vRegTest1Task, "Reg1", configMINIMAL_STACK_SIZE, NULL, 0, NULL );
264 xTaskCreate( vRegTest2Task, "Reg2", configMINIMAL_STACK_SIZE, NULL, 0, NULL );
266 /* Create the 'check' timer - the timer that periodically calls the
267 check function as described at the top of this file. Note that, for
268 the reasons stated in the comments above the call to
269 vStartTimerDemoTask(), that the check timer is not actually started
270 until after the scheduler has been started. */
271 xCheckTimer = xTimerCreate( "Check timer", mainCHECK_TIMER_PERIOD, pdTRUE, ( void * ) 0, vCheckTimerCallback );
273 /* Start the scheduler. */
274 vTaskStartScheduler();
277 /* If all is well then this line will never be reached. If it is reached
278 then it is likely that there was insufficient (FreeRTOS) heap memory space
279 to create the idle task. This may have been trapped by the malloc() failed
280 hook function, if one is configured. */
283 /*-----------------------------------------------------------*/
285 static void prvLCDTask( void *pvParameters )
287 xQueueMessage xReceivedMessage;
289 /* Buffer into which strings are formatted and placed ready for display on the
290 LCD. Note this is a static variable to prevent it being allocated on the task
291 stack, which is too small to hold such a variable. The stack size is configured
292 when the task is created. */
293 static char cBuffer[ 50 ];
294 unsigned char ucLine = 1;
296 /* Now the scheduler has been started (it must have been for this task to
297 be running), start the check timer too. The call to xTimerStart() will
298 block until the command has been accepted. */
299 if( xCheckTimer != NULL )
301 xTimerStart( xCheckTimer, portMAX_DELAY );
304 /* This is the only function that is permitted to access the LCD.
306 First print out the number of bytes that remain in the FreeRTOS heap. This
307 is done after a short delay to ensure all the demo tasks have created all
308 the objects they are going to use. */
309 vTaskDelay( mainTIMER_TEST_PERIOD * 10 );
310 sprintf( cBuffer, "%d heap free", ( int ) xPortGetFreeHeapSize() );
311 halLcdPrintLine( cBuffer, ucLine, OVERWRITE_TEXT );
314 /* Just as a test of the port, and for no functional reason, check the task
315 parameter contains its expected value. */
316 if( pvParameters != mainTASK_PARAMETER_CHECK_VALUE )
318 halLcdPrintLine( "Invalid parameter", ucLine, OVERWRITE_TEXT );
324 /* Wait for a message to be received. Using portMAX_DELAY as the block
325 time will result in an indefinite wait provided INCLUDE_vTaskSuspend is
326 set to 1 in FreeRTOSConfig.h, therefore there is no need to check the
327 function return value and the function will only return when a value
328 has been received. */
329 xQueueReceive( xLCDQueue, &xReceivedMessage, portMAX_DELAY );
331 /* Clear the LCD if no room remains for any more text output. */
332 if( ucLine > mainMAX_LCD_LINES )
338 /* What is this message? What does it contain? */
339 switch( xReceivedMessage.cMessageID )
341 case mainMESSAGE_BUTTON_UP : /* The button poll task has just
342 informed this task that the up
343 button on the joystick input has
344 been pressed or released. */
345 sprintf( cBuffer, "Button up = %d", ( int ) xReceivedMessage.ulMessageValue );
348 case mainMESSAGE_BUTTON_SEL : /* The select button interrupt
349 just informed this task that the
350 select button has been pressed.
351 In this case the pointer to the
352 string to print is sent directly
353 in the ulMessageValue member of
354 the message. This just
355 demonstrates a different
356 communication technique. */
357 sprintf( cBuffer, "%s", ( char * ) xReceivedMessage.ulMessageValue );
360 case mainMESSAGE_STATUS : /* The tick interrupt hook
361 function has just informed this
362 task of the system status.
363 Generate a string in accordance
364 with the status value. */
365 prvGenerateStatusMessage( cBuffer, xReceivedMessage.ulMessageValue );
368 default : sprintf( cBuffer, "Unknown message" );
372 /* Output the message that was placed into the cBuffer array within the
373 switch statement above, then move onto the next line ready for the next
374 message to arrive on the queue. */
375 halLcdPrintLine( cBuffer, ucLine, OVERWRITE_TEXT );
379 /*-----------------------------------------------------------*/
381 static void prvGenerateStatusMessage( char *pcBuffer, unsigned long ulStatusValue )
383 /* Just a utility function to convert a status value into a meaningful
384 string for output onto the LCD. */
385 switch( ulStatusValue )
387 case pdPASS : sprintf( pcBuffer, "Status = PASS" );
389 case mainERROR_DYNAMIC_TASKS : sprintf( pcBuffer, "Err: Dynamic tsks" );
391 case mainERROR_COM_TEST : sprintf( pcBuffer, "Err: COM test" );
393 case mainERROR_GEN_QUEUE_TEST : sprintf( pcBuffer, "Error: Gen Q test" );
395 case mainERROR_REG_TEST : sprintf( pcBuffer, "Error: Reg test" );
397 case mainERROR_TIMER_TEST : sprintf( pcBuffer, "Error: Tmr test" );
399 case mainERROR_COUNT_SEM_TEST : sprintf( pcBuffer, "Error: Count sem" );
401 default : sprintf( pcBuffer, "Unknown status" );
405 /*-----------------------------------------------------------*/
407 static void prvButtonPollTask( void *pvParameters )
409 unsigned char ucLastState = pdFALSE, ucState;
410 xQueueMessage xMessage;
412 /* This tasks performs the button polling functionality as described at the
416 /* Check the button state. */
417 ucState = ( halButtonsPressed() & BUTTON_UP );
421 /* The button was pressed. */
425 if( ucState != ucLastState )
427 /* The state has changed, send a message to the LCD task. */
428 xMessage.cMessageID = mainMESSAGE_BUTTON_UP;
429 xMessage.ulMessageValue = ( unsigned long ) ucState;
430 ucLastState = ucState;
431 xQueueSend( xLCDQueue, &xMessage, portMAX_DELAY );
434 /* Block for 10 milliseconds so this task does not utilise all the CPU
435 time and debouncing of the button is not necessary. */
436 vTaskDelay( 10 / portTICK_PERIOD_MS );
439 /*-----------------------------------------------------------*/
441 static void vCheckTimerCallback( TimerHandle_t xTimer )
443 static unsigned short usLastRegTest1Counter = 0, usLastRegTest2Counter = 0;
445 /* Define the status message that is sent to the LCD task. By default the
447 static xQueueMessage xStatusMessage = { mainMESSAGE_STATUS, pdPASS };
449 /* This is the callback function used by the 'check' timer, as described
450 at the top of this file. */
452 /* The parameter is not used. */
455 /* See if the standard demo tasks are executing as expected, changing
456 the message that is sent to the LCD task from PASS to an error code if
457 any tasks set reports an error. */
458 if( xAreComTestTasksStillRunning() != pdPASS )
460 xStatusMessage.ulMessageValue = mainERROR_COM_TEST;
463 if( xAreDynamicPriorityTasksStillRunning() != pdPASS )
465 xStatusMessage.ulMessageValue = mainERROR_DYNAMIC_TASKS;
468 if( xAreGenericQueueTasksStillRunning() != pdPASS )
470 xStatusMessage.ulMessageValue = mainERROR_GEN_QUEUE_TEST;
473 if( xAreCountingSemaphoreTasksStillRunning() != pdPASS )
475 xStatusMessage.ulMessageValue = mainERROR_COUNT_SEM_TEST;
478 if( xAreTimerDemoTasksStillRunning( ( TickType_t ) mainCHECK_TIMER_PERIOD ) != pdPASS )
480 xStatusMessage.ulMessageValue = mainERROR_TIMER_TEST;
483 /* Check the reg test tasks are still cycling. They will stop
484 incrementing their loop counters if they encounter an error. */
485 if( usRegTest1Counter == usLastRegTest1Counter )
487 xStatusMessage.ulMessageValue = mainERROR_REG_TEST;
490 if( usRegTest2Counter == usLastRegTest2Counter )
492 xStatusMessage.ulMessageValue = mainERROR_REG_TEST;
495 usLastRegTest1Counter = usRegTest1Counter;
496 usLastRegTest2Counter = usRegTest2Counter;
498 /* This is called from a timer callback so must not block! */
499 xQueueSendToBack( xLCDQueue, &xStatusMessage, mainDONT_BLOCK );
501 /*-----------------------------------------------------------*/
503 static void prvSetupHardware( void )
505 taskDISABLE_INTERRUPTS();
507 /* Disable the watchdog. */
508 WDTCTL = WDTPW + WDTHOLD;
512 LFXT_Start( XT1DRIVE_0 );
513 hal430SetSystemClock( configCPU_CLOCK_HZ, configLFXT_CLOCK_HZ );
515 halButtonsInit( BUTTON_ALL );
516 halButtonsInterruptEnable( BUTTON_SELECT );
518 /* Initialise the LCD, but note that the backlight is not used as the
519 library function uses timer A0 to modulate the backlight, and this file
520 defines vApplicationSetupTimerInterrupt() to also use timer A0 to generate
521 the tick interrupt. If the backlight is required, then change either the
522 halLCD library or vApplicationSetupTimerInterrupt() to use a different
523 timer. Timer A1 is used for the run time stats time base6. */
525 halLcdSetContrast( 100 );
528 halLcdPrintLine( " www.FreeRTOS.org", 0, OVERWRITE_TEXT );
530 /*-----------------------------------------------------------*/
533 void vApplicationTickHook( void )
535 static unsigned long ulCounter = 0;
537 /* Is it time to toggle the LED again? */
540 /* Just periodically toggle an LED to show that the tick interrupt is
541 running. Note that this access LED_PORT_OUT in a non-atomic way, so tasks
542 that access the same port must do so from a critical section. */
543 if( ( ulCounter & 0xff ) == 0 )
545 if( ( LED_PORT_OUT & LED_1 ) == 0 )
547 LED_PORT_OUT |= LED_1;
551 LED_PORT_OUT &= ~LED_1;
555 /*-----------------------------------------------------------*/
557 #pragma vector=PORT2_VECTOR
558 interrupt void prvSelectButtonInterrupt( void )
560 /* Define the message sent to the LCD task from this interrupt. */
561 static const xQueueMessage xMessage = { mainMESSAGE_BUTTON_SEL, ( unsigned long ) "Select Interrupt" };
562 portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
564 /* This is the interrupt handler for the joystick select button input.
565 The button has been pushed, write a message to the LCD via the LCD task. */
566 xQueueSendFromISR( xLCDQueue, &xMessage, &xHigherPriorityTaskWoken );
570 /* If writing to xLCDQueue caused a task to unblock, and the unblocked task
571 has a priority equal to or above the task that this interrupt interrupted,
572 then lHigherPriorityTaskWoken will have been set to pdTRUE internally within
573 xQueuesendFromISR(), and portEND_SWITCHING_ISR() will ensure that this
574 interrupt returns directly to the higher priority unblocked task. */
575 portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
577 /*-----------------------------------------------------------*/
579 /* The MSP430X port uses this callback function to configure its tick interrupt.
580 This allows the application to choose the tick interrupt source.
581 configTICK_VECTOR must also be set in FreeRTOSConfig.h to the correct
582 interrupt vector for the chosen tick interrupt source. This implementation of
583 vApplicationSetupTimerInterrupt() generates the tick from timer A0, so in this
584 case configTICK_VECTOR is set to TIMER0_A0_VECTOR. */
585 void vApplicationSetupTimerInterrupt( void )
587 const unsigned short usACLK_Frequency_Hz = 32768;
589 /* Ensure the timer is stopped. */
592 /* Run the timer from the ACLK. */
595 /* Clear everything to start with. */
598 /* Set the compare match value according to the tick rate we want. */
599 TA0CCR0 = usACLK_Frequency_Hz / configTICK_RATE_HZ;
601 /* Enable the interrupts. */
604 /* Start up clean. */
610 /*-----------------------------------------------------------*/
612 void vApplicationIdleHook( void )
614 /* Called on each iteration of the idle task. In this case the idle task
615 just enters a low(ish) power mode. */
616 __bis_SR_register( LPM1_bits + GIE );
618 /*-----------------------------------------------------------*/
620 void vApplicationMallocFailedHook( void )
622 /* Called if a call to pvPortMalloc() fails because there is insufficient
623 free memory available in the FreeRTOS heap. pvPortMalloc() is called
624 internally by FreeRTOS API functions that create tasks, queues or
626 taskDISABLE_INTERRUPTS();
629 /*-----------------------------------------------------------*/
631 void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
636 /* Run time stack overflow checking is performed if
637 configconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
638 function is called if a stack overflow is detected. */
639 taskDISABLE_INTERRUPTS();
642 /*-----------------------------------------------------------*/