]> begriffs open source - cmsis-freertos/blob - Demo/Flshlite/main.c
Update cmsis_os2.c
[cmsis-freertos] / Demo / Flshlite / main.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
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.
12
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     ***************************************************************************
19
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
24
25     ***************************************************************************
26      *                                                                       *
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.                               *
31      *                                                                       *
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                              *
36      *                                                                       *
37     ***************************************************************************
38
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()?
42
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.
46
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.
51
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.
55
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.
58
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.
62
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.
66
67     1 tab == 4 spaces!
68 */
69
70 /*
71  * Creates all the demo application tasks, then starts the scheduler.
72  *
73  * Main. c also creates a task called "Print".  This only executes every five 
74  * seconds but has the highest priority so is guaranteed to get processor time.  
75  * Its main function is to check that all the other tasks are still operational.  
76  * Nearly all the tasks in the demo application maintain a unique count that is 
77  * incremented each time the task successfully completes its function.  Should any 
78  * error occur within the task the count is permanently halted.  The print task 
79  * checks the count of each task to ensure it has changed since the last time the 
80  * print task executed.  If any count is found not to have changed the print task
81  * displays an appropriate message, halts, and flashes the on board LED rapidly.
82  * If all the tasks are still incrementing their unique counts the print task
83  * displays an "OK" message.
84  *
85  * The LED flash tasks do not maintain a count as they already provide visual
86  * feedback of their status.
87  *
88  * The print task blocks on the queue into which messages that require displaying
89  * are posted.  It will therefore only block for the full 5 seconds if no messages
90  * are posted onto the queue.
91  *
92  * Main. c also provides a demonstration of how the trace visualisation utility can
93  * be used, and how the scheduler can be stopped.
94  *
95  * On the Flashlite it is preferable not to try to write to the console during
96  * real time operation.  The built in LED is toggled every cycle of the print task
97  * that does not encounter any errors, so the console IO may be removed if required.
98  * The build in LED will start flashing rapidly if any task reports an error.
99  */
100
101 /*
102 Changes from V1.01:
103
104         + Previously, if an error occurred in a task the on board LED was stopped from
105           toggling.  Now if an error occurs the check task enters an infinite loop,
106           toggling the LED rapidly.
107
108 Changes from V1.2.3
109
110         + The integer and comtest tasks are now used when the cooperative scheduler 
111           is being used.  Previously they were only used with the preemptive
112           scheduler.
113
114 Changes from V1.2.5
115
116         + Made the communications RX task a higher priority.
117
118 Changes from V2.0.0
119
120         + Delay periods are now specified using variables and constants of
121           TickType_t rather than unsigned long.
122 */
123
124 #include <stdlib.h>
125 #include <conio.h>
126 #include "FreeRTOS.h"
127 #include "task.h"
128 #include "partest.h"
129 #include "serial.h"
130
131 /* Demo file headers. */
132 #include "BlockQ.h"
133 #include "PollQ.h"
134 #include "death.h"
135 #include "flash.h"
136 #include "integer.h"
137 #include "print.h"
138 #include "comtest.h"
139 #include "fileio.h"
140 #include "semtest.h"
141
142 /* Priority definitions for all the tasks in the demo application. */
143 #define mainLED_TASK_PRIORITY                   ( tskIDLE_PRIORITY + 1 )
144 #define mainCREATOR_TASK_PRIORITY               ( tskIDLE_PRIORITY + 3 )
145 #define mainPRINT_TASK_PRIORITY                 ( tskIDLE_PRIORITY + 5 )
146 #define mainQUEUE_POLL_PRIORITY                 ( tskIDLE_PRIORITY + 2 )
147 #define mainQUEUE_BLOCK_PRIORITY                ( tskIDLE_PRIORITY + 3 )
148 #define mainCOM_TEST_PRIORITY                   ( tskIDLE_PRIORITY + 3 )
149 #define mainSEMAPHORE_TASK_PRIORITY             ( tskIDLE_PRIORITY + 1 )
150
151 #define mainPRINT_STACK_SIZE            ( ( unsigned short ) 256 )
152 #define mainDEBUG_LOG_BUFFER_SIZE       ( ( unsigned short ) 20480 )
153
154 /* Constant definitions for accessing the build in LED on the Flashlite 186. */
155 #define mainLED_REG_DIR                         ( ( unsigned short ) 0xff78 )
156 #define mainLED_REG                             ( ( unsigned short ) 0xff7a )
157
158 /* If an error is detected in a task then the vErrorChecks() task will enter
159 an infinite loop flashing the LED at this rate. */
160 #define mainERROR_FLASH_RATE            ( ( TickType_t ) 100 / portTICK_PERIOD_MS )
161
162 /* Task function for the "Print" task as described at the top of the file. */
163 static void vErrorChecks( void *pvParameters );
164
165 /* Function that checks the unique count of all the other tasks as described at
166 the top of the file. */
167 static void prvCheckOtherTasksAreStillRunning( void );
168
169 /* Functions to setup and use the built in LED on the Flashlite 186 board. */
170 static void prvToggleLED( void );
171 static void prvInitLED( void );
172
173 /* Key presses can be used to start/stop the trace visualisation utility or stop
174 the scheduler. */
175 static void     prvCheckForKeyPresses( void );
176
177 /* Buffer used by the trace visualisation utility. */
178 static char pcWriteBuffer[ mainDEBUG_LOG_BUFFER_SIZE ];
179
180 /*-----------------------------------------------------------*/
181 short main( void )
182 {
183         /* Initialise hardware and utilities. */
184         vParTestInitialise();
185         vPrintInitialise();
186         prvInitLED();
187
188         /* CREATE ALL THE DEMO APPLICATION TASKS. */
189
190         vStartComTestTasks( mainCOM_TEST_PRIORITY, serCOM2, ser38400 );
191         vStartIntegerMathTasks( tskIDLE_PRIORITY );
192         vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY );
193         vStartBlockingQueueTasks( mainQUEUE_BLOCK_PRIORITY );
194         vStartLEDFlashTasks( mainLED_TASK_PRIORITY );
195         vStartSemaphoreTasks( mainSEMAPHORE_TASK_PRIORITY );
196
197         /* Create the "Print" task as described at the top of the file. */
198         xTaskCreate( vErrorChecks, "Print", mainPRINT_STACK_SIZE, NULL, mainPRINT_TASK_PRIORITY, NULL );
199
200         /* This task has to be created last as it keeps account of the number of tasks
201         it expects to see running. */
202         vCreateSuicidalTasks( mainCREATOR_TASK_PRIORITY );
203
204         /* Set the scheduler running.  This function will not return unless a task
205         calls vTaskEndScheduler(). */
206         vTaskStartScheduler();
207
208         return 1;
209 }
210 /*-----------------------------------------------------------*/
211
212 static void vErrorChecks( void *pvParameters )
213 {
214 TickType_t xExpectedWakeTime;
215 const TickType_t xPrintRate = ( TickType_t ) 5000 / portTICK_PERIOD_MS;
216 const long lMaxAllowableTimeDifference = ( long ) 0;
217 TickType_t xWakeTime;
218 long lTimeDifference;
219 const char *pcReceivedMessage;
220 const char * const pcTaskBlockedTooLongMsg = "Print task blocked too long!\r\n";
221
222         /* Stop warnings. */
223     ( void ) pvParameters;
224
225         /* Loop continuously, blocking, then checking all the other tasks are still
226         running, before blocking once again.  This task blocks on the queue of messages
227         that require displaying so will wake either by its time out expiring, or a
228         message becoming available. */
229         for( ;; )
230         {
231                 /* Calculate the time we will unblock if no messages are received
232                 on the queue.  This is used to check that we have not blocked for too long. */
233                 xExpectedWakeTime = xTaskGetTickCount();
234                 xExpectedWakeTime += xPrintRate;
235
236                 /* Block waiting for either a time out or a message to be posted that
237                 required displaying. */
238                 pcReceivedMessage = pcPrintGetNextMessage( xPrintRate );
239
240                 /* Was a message received? */
241                 if( pcReceivedMessage == NULL )
242                 {
243                         /* A message was not received so we timed out, did we unblock at the
244                         expected time? */
245                         xWakeTime = xTaskGetTickCount();
246
247                         /* Calculate the difference between the time we unblocked and the
248                         time we should have unblocked. */
249                         if( xWakeTime > xExpectedWakeTime )
250                         {
251                                 lTimeDifference = ( long ) ( xWakeTime - xExpectedWakeTime );
252                         }
253                         else
254                         {
255                                 lTimeDifference = ( long ) ( xExpectedWakeTime - xWakeTime );
256                         }
257
258                         if( lTimeDifference > lMaxAllowableTimeDifference )
259                         {
260                                 /* We blocked too long - create a message that will get
261                                 printed out the next time around. */
262                                 vPrintDisplayMessage( &pcTaskBlockedTooLongMsg );
263                         }
264
265                         /* Check the other tasks are still running, just in case. */
266                         prvCheckOtherTasksAreStillRunning();
267                 }
268                 else
269                 {
270                         /* We unblocked due to a message becoming available.  Send the message
271                         for printing. */
272                         vDisplayMessage( pcReceivedMessage );
273                 }
274
275                 /* Key presses are used to invoke the trace visualisation utility, or
276                 end the program. */
277                 prvCheckForKeyPresses();
278         }
279 } /*lint !e715 !e818 pvParameters is not used but all task functions must take this form. */
280 /*-----------------------------------------------------------*/
281
282 static void      prvCheckForKeyPresses( void )
283 {
284         #ifdef USE_STDIO
285
286         short sIn;
287
288         
289                 taskENTER_CRITICAL();
290                         sIn = kbhit();
291                 taskEXIT_CRITICAL();
292
293                 if( sIn )
294                 {
295                         unsigned long ulBufferLength;
296
297                         /* Key presses can be used to start/stop the trace utility, or end the
298                         program. */
299                         sIn = getch();
300                         switch( sIn )
301                         {
302                                 /* Only define keys for turning on and off the trace if the trace
303                                 is being used. */
304                                 #if configUSE_TRACE_FACILITY == 1
305                                         case 't' :      vTaskList( pcWriteBuffer );
306                                                                 vWriteMessageToDisk( pcWriteBuffer );
307                                                                 break;
308
309                                         /* The legacy trace is no longer supported.  Use FreeRTOS+Trace instead.
310                                         case 's' :      vTaskStartTrace( pcWriteBuffer, mainDEBUG_LOG_BUFFER_SIZE );
311                                                                 break;
312
313                                         case 'e' :      ulBufferLength = ulTaskEndTrace();
314                                                                 vWriteBufferToDisk( pcWriteBuffer, ulBufferLength );
315                                                                 break;*/
316                                 #endif
317
318                                 default  :      vTaskEndScheduler();
319                                                         break;
320                         }
321                 }
322
323         #else
324                 ( void ) pcWriteBuffer;
325         #endif
326 }
327 /*-----------------------------------------------------------*/
328
329 static void prvCheckOtherTasksAreStillRunning( void )
330 {
331 short sErrorHasOccurred = pdFALSE;
332
333         if( xAreComTestTasksStillRunning() != pdTRUE )
334         {
335                 vDisplayMessage( "Com test count unchanged!\r\n" );
336                 sErrorHasOccurred = pdTRUE;
337         }
338
339         if( xAreIntegerMathsTaskStillRunning() != pdTRUE )
340         {
341                 vDisplayMessage( "Integer maths task count unchanged!\r\n" );
342                 sErrorHasOccurred = pdTRUE;
343         }
344
345         if( xAreBlockingQueuesStillRunning() != pdTRUE )
346         {
347                 vDisplayMessage( "Blocking queues count unchanged!\r\n" );
348                 sErrorHasOccurred = pdTRUE;
349         }
350
351         if( xArePollingQueuesStillRunning() != pdTRUE )
352         {
353                 vDisplayMessage( "Polling queue count unchanged!\r\n" );
354                 sErrorHasOccurred = pdTRUE;
355         }
356
357         if( xIsCreateTaskStillRunning() != pdTRUE )
358         {
359                 vDisplayMessage( "Incorrect number of tasks running!\r\n" );
360                 sErrorHasOccurred = pdTRUE;
361         }
362
363         if( xAreSemaphoreTasksStillRunning() != pdTRUE )
364         {
365                 vDisplayMessage( "Semaphore take count unchanged!\r\n" );
366                 sErrorHasOccurred = pdTRUE;
367         }
368
369         if( sErrorHasOccurred == pdFALSE )
370         {
371                 vDisplayMessage( "OK " );
372                 /* Toggle the LED if everything is okay so we know if an error occurs even if not
373                 using console IO. */
374                 prvToggleLED();
375         }
376         else
377         {
378                 for( ;; )
379                 {
380                         /* An error has occurred in one of the tasks.  Don't go any further and
381                         flash the LED rapidly in case console IO is not being used. */
382                         prvToggleLED();
383                         vTaskDelay( mainERROR_FLASH_RATE );
384                 }
385         }
386 }
387 /*-----------------------------------------------------------*/
388
389 static void prvInitLED( void )
390 {
391 unsigned short usPortDirection;
392 const unsigned short usLEDOut = 0x400;
393
394         /* Set the LED bit to an output. */
395
396         usPortDirection = inpw( mainLED_REG_DIR );
397         usPortDirection &= ~usLEDOut;
398         outpw( mainLED_REG_DIR, usPortDirection );
399 }
400 /*-----------------------------------------------------------*/
401
402 static void prvToggleLED( void )
403 {
404 static short sLED = pdTRUE;
405 unsigned short usLEDState;
406 const unsigned short usLEDBit = 0x400;
407
408         /* Flip the state of the LED. */
409         usLEDState = inpw( mainLED_REG );
410         if( sLED )
411         {
412                 usLEDState &= ~usLEDBit;
413         }
414         else
415         {
416                 usLEDState |= usLEDBit;
417         }
418         outpw( mainLED_REG, usLEDState );
419
420         sLED = !sLED;
421 }
422
423