在這個實時操作系統泛濫的年代,有這么一個系統封裝接口層還是蠻有必要的。前些時間偶然間在STM32最新的固件庫中就發現了這個系統封裝接口,當時就把自己所用的系統進行封裝。直到最近KEIL5.0發現其中所到的RTX系統也進行了同相的封裝。對比了下感覺很有必要和大家分享一下。
采用這個接口層寫程序,基本上可以說不用再去管所用的是什么操作系統。相同的代碼可以輕而易舉的移植到不同的實時系統中。不敢說完全沒有改動,但絕對是最少的。其簡潔的書寫手法,也會給我的應用層帶來視覺上的體驗感,使用可以盡可能去關注應用。
下面先用uCOS-II系統接口為例進行簡單概述:
這里是主要的配置區,你所用到哪些功能用0或1來選擇和取消。由於有些和系統中宏配置有相同意思的宏配置,所以我這里直接用了系統配置中的宏。
這是所用不同系統時的主要不同處。其他地方就很少會改動了。
下面來舉例來說明如何簡單的使用這個接口。
首先進入main函數,官方樣例代碼:
1 if (osKernelInitialize () != osOK) { // check osStatus for other possible valid values 2 3 // exit with an error message 4 5 } 6 7 if (!osKernelRunning ()) { // is the kernel running ? 8 9 if (osKernelStart () != osOK) { // start the kernel 10 11 // kernel could not be started 12 13 } 14 15 }
進入首個函數中我們就需要建立任務
代碼事例:
圖上是RTX的接口代碼所以,所用的棧地址,和棧大小有點不一樣,uCOSII的是如下定義:
1 static uint32_t taskLedStk[TASK_LED_STK_SIZE] = {0}; 2 3 osThreadDef(TaskLed, TASK_LED_PRIO, taskLedStk, TASK_LED_STK_SIZE);
下面介紹信號量樣例代碼:
1 osSemaphoreDef(LED_CTRL); //定義信號量 2 osSemaphoreId osSem = NULL; //信號量句柄 3 osSem = osSemaphoreCreate(osSemaphore(LED_CTRL), 0); //建立一個信號量 初值為0 4 osSemaphoreRelease(osSem); //釋放一個信號量
定時回調函數事例代碼:
1 #include "cmsis_os.h"
2 void Timer1_Callback (void const *arg); // prototypes for timer callback function 3 void Timer2_Callback (void const *arg); 4 osTimerDef (Timer1, Timer1_Callback); // define timers 5 osTimerDef (Timer2, Timer2_Callback); 6 uint32_t exec1; // argument for the timer call back function 7 uint32_t exec2; // argument for the timer call back function
8 void TimerCreate_example (void) { 9 osTimerId id1; // timer id 10 osTimerId id2; // timer id 11 // Create one-shoot timer 12 exec1 = 1; 13 id1 = osTimerCreate (osTimer(Timer1), osTimerOnce, &exec1); 14 if (id1 != NULL) { 15 // One-shoot timer created 16 } 17 // Create periodic timer 18 exec2 = 2; 19 id2 = osTimerCreate (osTimer(Timer2), osTimerPeriodic, &exec2); 20 if (id2 != NULL) { 21 // Periodic timer created 22 } 23 : 24 }
好了, 這些只大概的進行說明。如果想知道更多的內容,你可以考慮安裝keil5.0。如下圖可以看到所有接口講解和使用方法。
下面分享 我封裝的uCOSII,uCOSIII這兩個系統接口。本人做過測試,相同的應用程序在這兩個系統運行的到相同的效果。
uCOSII
uCOSIII
樣例工程