CMSIS-RTOS for Mecrisp-Cube

Why a Preemptive Real Time Operating System?

Forth systems traditionally make use of cooperative multitasking. It is very simple and clever. But it has its limits. If you write all your software by yourself, each software part can be cooperative. But if you want to benefit from middleware written by somebody else (and most probably not written in Forth), you can be sure that software is not cooperative (in the context of multitasking). Forth wants to rule your system. I would like to have a Forth system that is cooperative. It should extend the system, to make it interactive and easy to use.

The Forth itself is only a thread and can be used as some sort of CLI for testing purposes or could be the main part of the application.

How to Create a Thread

A very simple thread could be like this one, a boring blinker:

: blink-thread  ( -- )
    led1@ 0= led1!   \ toggle blue LED
    200 osDelay drop  \ wait 200 ms
  0 led1! 

If you type the word blink-thread, the blue LED blinks, after push the button SW1, the blinking stops an the ok. apears. But if you try to start the thread with

' blink-thread 0 0 osThreadNew
Nothing happens and probably the Forth system hangs. Restart the Forth system with the Reset button SW4.

If you create a new RTOS Thread, CMSIS-RTOS (FreeRTOS) allocate some memory from the heap for the stack and the thread control block. But Forth thread needs another stack, the data stack. The blink-thread runs concurrent to the Forth interpreter and use the same data stack. This cannot work. Each thread must have its own data stack, the thread function can get one with osNewDataStack (see below for the assembler source).

: blink-thread  ( -- )
    led1@ 0= led1!   \ toggle blue LED
    200 osDelay drop  
  0 led1! 

osThreadExit is needed to exit the thread, otherwise the Forth system hangs after leaving the thread. These threads are very similar to the control tasks described in Starting Forth, Leo Brodie. But without user variables. If a thread wants to use variables and share these variables with other threads, the variables have to be protected by a mutex or a semaphore. Anyway variables have to be created by the main Forth thread (terminal task) before.

Now you can interactively play with the words osThreadGetId, osThreadGetState, osThreadSuspend, and osThreadResume without the tedious edit-compile-download-run-abort.

// -----------------------------------------------------------------------------
		Wortbirne Flag_visible, "osNewDataStack"
		@ (  --  ) Creates an new data stack for a Forth thread.
// -----------------------------------------------------------------------------
	push	{r0-r3, lr}
	ldr	r0, =256	// 64 levels should be more than enough
	bl	pvPortMalloc
	adds	r7, r0, #256	// stack grows down
	movs	tos, 42
	pop	{r0-r3, pc}

Interrupts and Forth

Mecrisp uses R7 as data stack pointer and R6 as TOS. If Forth rules the system R7 is always the data stack pointer and you can use the data stack pointer within a interrupt service routine. But in a mixed system, where C routines are used, there is no guarantee that the register R7 remains unchanged. When the interrupt occurs while a C routine is executed, the data stack pointer is invalid and Forth words can't be used in interrupt service routines. A possible solution would be a separate data stack for the ISRs. I don't do that and use C for the ISRs. The Forth threads are synchronized by RTOS IPCs like semaphores.

For details see bsp.c.

  * @brief  Output Compare callback in non-blocking mode
  * @param  htim TIM OC handle
  * @retval None
void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim) {
	if (htim->Instance == TIM2) {
		if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) {
			// D5, PA15
		if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3) {
			// D1, PA2
		if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4) {
			// D0, PA3

 *  @brief
 *      Waits for Output Compare.
 *	@param[in]
 *      pin_number  port pin 0 D0, 1 D1, or 5 D5
 *  @return
 *      none
void BSP_waitOC(int pin_number) {
	switch (pin_number) {
	case 0:
		osSemaphoreAcquire(ICOC_CH4_SemaphoreID, osWaitForever);
	case 1:
		osSemaphoreAcquire(ICOC_CH3_SemaphoreID, osWaitForever);
	case 5:
		osSemaphoreAcquire(ICOC_CH1_SemaphoreID, osWaitForever);

OCwait Forth word waits for the event Output Compare, timer interrupt assigned to a port pin. Details bsp.s.

@ -----------------------------------------------------------------------------
		Wortbirne Flag_visible, "OCwait"
		@ ( a -- )    wait for the end of output capture pin a
// void BSP_waitOC(int pin_number);
@ -----------------------------------------------------------------------------
	push	{r0-r3, lr}
	movs	r0, tos		// pin_number
	bl	BSP_waitOC
	pop	{r0-r3, pc}


The C function prototype for osThreadNew looks like this:

osThreadId_t osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr);

param[in]     func          thread function.
param[in]     argument      pointer that is passed to the thread function as start argument.
param[in]     attr          thread attributes; NULL: default values.

return        thread ID for reference by other functions or NULL in case of error.

The parameter order for the Forth Word is the same: addr1 is func, addr2 is argument, and addr3 is attr.

osThreadNew  ( addr1 addr2 addr3 -- u )   Create a thread and add it to Active Threads.

Start the knightrider (for details see and BoardSupportPackage) thread with default parameters and print the thread ID:

' knightrider-thread 0 0 osThreadNew .[RET] 536871016 ok.

Stop the thread with pressing button SW1 or

536871016 osThreadTerminate drop[RET] ok.

Start the Knightrider thread with name="Knightrider" priority=48, stack_size=256:

\ buffer for thread attributes
/osThreadAttr buffer: threadAttr[RET] ok.      
\ clear the buffer
threadAttr /osThreadAttr 0 fill[RET] ok.
\ set the thread name
16 buffer: threadString[RET] ok.
threadString .str" Knightrider"[RET] ok.
\ set the thread parameters
threadString threadAttr thName+ + ![RET] ok.
256 threadAttr thStackSize+ + ![RET] ok.
 48 threadAttr thPriority+  + ![RET] ok.
\ start the thread
' knightrider-thread 0 threadAttr osThreadNew .[RET] 0 ok.
\ print all threads
Name                State    Priority   Stack Space
MainThread          Running     24          0754
CDC_Thread          Blocked     24          0087
IDLE                Ready       00          0107
HRS_THREAD          Blocked     24          0380
Knightrider         Blocked     48          0023
UART_TxThread       Blocked     40          0217
HCI_USER_EVT_TH     Blocked     24          0217
ADV_UPDATE_THRE     Blocked     24          0217
CRS_Thread          Blocked     40          0207
SHCI_USER_EVT_T     Blocked     24          0071
Tmr Svc             Ready       02          0209
UART_RxThread       Blocked     40          0213

See also osThreadNew and MicroSdBlocks#C_String_Helpers

RTOS Support Functions

osNewDataStack       ( --   )       Creates an new data stack for a Forth thread.
xPortGetFreeHeapSize ( -- u )       returns the total amount of heap space that remains
pvPortMalloc         ( u -- addr )  allocate dynamic memory (thread save)
vPortFree            ( addr -- )    free dynamic memory (thread save)

/osThreadAttr        ( -- u ) Gets the osThreadAttr_t structure size
thName+              ( -- u ) Gets the osThreadAttr_t structure name attribut offset
thAttrBits+          ( -- u ) Gets the osThreadAttr_t structure attr_bits attribut offset
thCbMem+             ( -- u ) Gets the osThreadAttr_t structure size attribut offset
thCbSize+            ( -- u ) Gets the osThreadAttr_t structure cb_size attribut offset
thStackMem+          ( -- u ) Gets the osThreadAttr_t structure stack_mem attribut offset
thStackSize+         ( -- u ) Gets the osThreadAttr_t structure stack_size attribut offset
thPriority+          ( -- u ) Gets the osThreadAttr_t structure priority attribut offset
thTzModule+          ( -- u ) Gets the osThreadAttr_t structure tz_module attribut offset

/osEventFlagsAttr    ( -- u ) Gets the osEventFlagsAttr_t structure size
/osMessageQueueAttr  ( -- u ) Gets the osMessageQueueAttr_t structure size
/osMutexAttr         ( -- u ) Gets the osMutexAttr_t structure size
/osSemaphoreAttr     ( -- u ) Gets the osSemaphoreAttr_t structure size

Kernel Management Functions

Kernel Information and Control
  • osKernelGetTickCount
  • osKernelGetTickFreq
  • osKernelGetSysTimerCount
  • osKernelGetSysTimerFreq

Generic Wait Functions

Generic Wait Functions
  • osDelay
  • osDelayUntil

Thread Management

Thread Management
  • osThreadNew default Attributes if attr==NULL: name="", priority=24 (osPriorityNormal), stack_size=128
  • osThreadGetId
  • osThreadGetName
  • osThreadGetState
  • osThreadSetPriority
  • osThreadGetPriority
  • osThreadYield
  • osThreadSuspend
  • osThreadResume
  • osThreadExit
  • osThreadTerminate
  • osThreadGetStackSpace
  • osThreadGetCount
  • osThreadEnumerate

Timer Management Functions

Timer Management
  • osTimerNew
  • osTimerGetName
  • osTimerStart
  • osTimerStop
  • osTimerIsRunning
  • osTimerDelete

Event Flags Management Functions

Event Flags
  • osEventFlagsNew
  • osEventFlagsSet
  • osEventFlagsClear
  • osEventFlagsGet
  • osEventFlagsWait
  • osEventFlagsDelete

Mutex Management Functions

Mutex Management
  • osMutexNew
  • osMutexAcquire
  • osMutexRelease
  • osMutexGetOwner
  • osMutexDelete

Semaphore Management Functions

  • osSemaphoreNew
  • osSemaphoreAcquire
  • osSemaphoreRelease
  • osSemaphoreGetCount
  • osSemaphoreDelete

Message Queue Management Functions

Message Queue
  • osMessageQueueNew
  • osMessageQueuePut
  • osMessageQueueGet
  • osMessageQueueGetCapacity
  • osMessageQueueGetMsgSize
  • osMessageQueueGetCount
  • osMessageQueueGetSpace
  • osMessageQueueReset
  • osMessageQueueDelete

A multi-tasking wordset for Standard Forth, Andrew Haley

-- Peter Schmid - 2020-04-07


Topic attachments
I Attachment History Action Size Date Who Comment
Unknown file formatfs knightrider.fs r1 manage 0.6 K 2020-08-30 - 09:05 PeterSchmid  
Edit | Attach | Watch | Print version | History: r21 < r20 < r19 < r18 < r17 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r21 - 2021-01-08 - PeterSchmid
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2021 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback