Bu not serisinde tasklar arasında haberleşebilmenin birden fazla yolunu gördük. Bu yazıda tasklar arası haberleşmenin bir başka yolu olan task notification( task bildirim ) mekanizmasına değinelim.
Daha önce bahsettiğimiz queue, event groups ve semaphore üzerinden tasklar ile haberleşebilmek için nesne oluşturmak gerekiyordu. Aslında tasklar arasındaki haberleşme bu nesneler üzerinden yapılıyordu.
Task bildirim mekanizması tasklar arasında doğrudan bir haberleşme imkanı sağlar. Yani xSemaphoreCreate() fonksiyonu gibi bir fonksiyon ile herhangi bir nesne oluşturmaya gerek kalmaz.
Task bildirim özelliğini kullanabilmek için configUSE_TASK_NOTIFICATIONS makrosu 1 olarak ayarlanmalıdır. Eğer bu makro 1 olarak ayarlanırsa her task bir “Notification State” ve 32 bitlik bir “Notification Value” değerine sahip olur. Eğer bir task bildirim gönderiyorsa “notification state” i “pending” , eğer bildirim alıyorsa “not-pending” olarak ayarlanır.
Task bildirim mekanizması queue, event groups ve semaphore dan daha hızlıdır. RAM kullanımı da diğerlerine göre daha azdır. Task bildirim mekanizması RAM de task başına 8 byte’lık alan kaplar.
Task bildirim mekanizması hızlı ve daha az RAM kullanmasına rağmen bazı eksiklikleri vardır.
- Birden fazla taskı harekete geçirme
Diğer nesnelere birden fazla task tarafından erişilebilirken(handle ile) task bildirimde ise sadece bir taska bildirim gönderilebilir. Yani bir bildirim ile birden fazla task harekete geçirilemez her taska ayrı ayrı bildirim gönderilmelidir.
- Buffer da birden fazla veri tutamama.
Queue kullanımında kuyrukta veriler depolanabiliyordu. Task bildirimde ise sadece bir adet veri(notification value) tutulur.
- Gönderme tamamlanana kadar taskı bloklayamama.
Queue kullanırken eğer kuyruk dolu veya boş iken tasklar opsiyonel olarak bloklanabiliyordu. Task bildirimde ise eğer task bildirimi zaten almışken tekrar bildirim göndersek bile gönderen taskı bloklayamıyoruz.
Task Bildirim Fonksiyonları
Task bildirim mekanizması binary semaphore, counting semaphore , event grup ve hatta queue yerine kullanılabilen çok güçlü bir FreeRTOS özelliğidir. Bu geniş kullanım özelliğine sahip task bildirim mekanizmasında, bildirim göndermek için xTaskNotify() ve bildirim almak için xTaskNotifyWait() fonksiyonu kullanılabilir. Bu fonksiyonların daha basit halleri olan xTaskNotifyGive() ve ulTaskNotifyTake() fonksiyonları daha yaygın olarak kullanılır. Bu fonksiyonlar diğerlerine göre daha basit olmasına rağmen esnek değildirler.
xTaskNotifyGive() Fonksiyonu(Makrosu)
Bir taska bildirim göndermek için xTaskNotifyGive() fonksiyonu kullanılır. Bu fonksiyon kullanıldığında bildirim alacak olan taskın “notification value” yani bildirim değeri bir artar ve bildirim alacak olan taskın “notification state” i “pending” olur.
1 | BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify ); |
- xTaskNotify: Bildirim gönderilecek olan taskın handle’ı. Parametre olarak xTaskCreate() fonksiyonun döndürdüğü handle girilir.
- Return Değeri: xTaskNotifyGive() makrosuna girilen parametreler xTaskNotify() fonksiyonuna iletilir. Bu fonksiyona girilen parametreler dönüş olarak sadece pdPASS olacak şekilde ayarlanır.
Bu fonksiyonun interrupt-safe versiyonu xTaskNotifyGiveFromISR() şeklindedir.
ulTaskNotifyTake() Fonksiyonu
Bu fonksiyon bildirim değeri(notification value) sıfırdan büyük olana kadar taskı bloklamaya izin verir. Aynı zamanda bildirimi aldıktan sonra bildirim değerini bir azaltır veya tamamen siler.
1 | uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ); |
- xClearCountOnExit: Bu parametre pdTRUE olarak girilirse bildirim değeri bu fonksiyon daha herhangi birşey döndürmeden önce sıfırlanır. Eğer pdFALSE olarak girilirse bu fonksiyonu çağıran taskın bildirim değeri bir azaltılır.
- xTicksToWait: Taskın ne kadar bloklanacağının girildiği parametredir. Milisaniye cinsinden değer girilecek ise pdMS_TO_TICKS() fonksiyonu ile girilmelidir.
- Return Değeri: Dönüş değeri olarak taskın bildirim değerini döndürür(temizleme veya azaltmadan önce).
xTaskNotify() Fonksiyonu
xTaskNotify() fonksiyonu xTaskNotifyGive() fonksiyonunun daha komplex bir halidir.
- Bildirim alacak olan task’ın bildirim değeri(notification value) birer arttırılabilir.
- Bildirim değerinin bir veya birden fazla biti set edilebilir. Bu task bildirim değerinin bir event group gibi(event group tan daha hızlı) kullanılmasına izin verir.
xTaskNotify() fonksiyonu xTaskNotifyGive() fonksiyonundan daha esnek ve güçlüdür. Bu ekstra esneklik ve güç yüzünden bu fonksiyonun kullanımı daha komplekstir. Bu fonksiyonun interrupt-safe versiyonu xTaskNotifyFromISR() şeklindedir.
1 2 3 | BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction ); |
1 2 3 | BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction ); |
- xTaskToNotify: Bildirim gönderilecek olan task handle’ı. (xTaskCreate() fonksiyonunun döndürdüğü handle)
- ulValue: Bildirim değeri. Bu parametrenin nasıl kullanılacağı eNotifyAction parametresine bağlıdır.
- eNotifyAction: Bildirim değerinin nasıl değiştirileceğinin belirlendiği parametredir. Bu parametre ile ilgili detaylı bilgi aşağıda verilecektir.
eNotifyAction Parametresinin Alabileceği Değerler
eNoAction: Alıcı taskın bildirim durumu “pending” olarak set edilir. ulValue parametresi kullanılmaz. eNoAction parametresi task bildirimin binary semaphore gibi kullanılmasına izin verir.
eSetBits: ulValue parametresi ile alıcı taskın bildirim değeri bitwise OR işlemine tabi tutulur. Örneğin ulValue 0x01 olarak girilirse task bildirim değerinin(notification value) sıfırıncı biti set edilir. eSetBits parametresi task bildirim mekanizmasını event group’un daha hızlı bir versiyonu gibi kullanmayı sağlar.
eIncrement: Task bildirim değeri bir arttırılır. ulValue parametresi kullanılmaz. eIncrement değeri task bildirimi counting semaphore veya binary semaphore’un daha hızlı bir versiyonu olarak kullanmaya izin verir. xTaskNotify() fonksiyonu bu değer ile kullanıldığında xTaskNotifyGive() fonksiyonuna eşdeğerdir.
eSetValueWithoutOverwrite: Alıcı task hali hazırda bir bildirim almış ise xTaskNotify() fonksiyonu pdFAIL değerini döndürür. Eğer taskın bildirimi yoksa ve xTaskNotify() fonksiyonu çağrılırsa bildirim değeri ulValue parametresine girilen değer olarak ayarlanır.
eSetValueWithOverwrite: Alıcı taskın xTaskNotify() fonksiyonu çağrılmadan önce bir bildirime sahip olup olmadığına bakılmaksızın task bildirim değeri ulValue değerine eşitlenir.
xTaskNotifyWait() Fonksiyonu
xTaskNotifyWait() fonksiyonu xTaskNotifyTake() fonksiyonun daha kompleks bir halidir. xTaskNotifyWait() bitlerin hem fonksiyona girişte hem de çıkışta sıfırlanmasına izin verir.
1 2 3 4 | BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ); |
- ulBitsToClearOnEntry: Bu parametreye girilen değerin task bildirim değerindeki bit karşılığı fonksiyona girişte sıfırlanır. Örneğin bu parametre 0x01 olarak girilirse bildirim değerinin sıfırıncı biti fonksiyona girişte sıfırlanır.
- ulBitsToClearOnExit: İlk parametrenin tam tersi olarak fonksiyondan çıkışta bu parametreye girilen bitleri temizler. Örneğin bu parametre 0x03 olarak girilirse bit 0 ve bit 1 fonksiyondan çıkmadan hemen önce temizlenir. Taskın bildirim değeri *pulNotificationValue parametresine girilen değişkene kaydedildikten sonra bitler temizlenir.
- pulNotificationValue: Bildirim değerini başka bir değişkene atamak için kullanılır. Herhangi bir bit temizlenmeden task bildirim değeri bu parametreye girilen değişkene kopyalanır. Bu parametre opsiyoneldir. Kullanılmayacak ise NULL girilmelidir.
- xTicksToWait: Taskı bloklamak için girilen bekleme süresi.
- Return Değeri: Bildirim alınmış ise ve xTaskNotifyWait() fonksiyonu çağrılmadan önce task hali hazırda bir bildirime sahipse pdTRUE değeri döndürür. xTaskNotifyWait() fonksiyonu ile blok süresi boyunca herhangi bir bildirim alınmadı ise pdFALSE değerini döndürür.
FreeRTOS ile Task Notification Örneği
Amaç: Hem bir Timer interrupt fonksiyonundan hem de bir tasktan başka bir taska bildirim gönder. İnterrupt fonksiyonu Task1 e bildirim göndersin. Task1 bildirimi alınca hemen ardından Task2 ye bir bildirim göndersin.
Task Bildirimde bildirimin hangi taska gideceği task handle ile belirlenir. Bu yüzden her iki task için aşağıdaki gibi task handle tanımlanmıştır.
1 | TaskHandle_t Task1Handle,Task2Handle; |
Örnek olarak task fonksiyonları aşağıdaki gibi yazılabilir. Burada Task1 ve Task2 başlangıçta ulTaskNotfiyTake() fonksiyonu ile bildirim beklemektedir. Task1 bildirim aldığında Task2 ye bildirim gönderecek ve Task2 nin çalışmasını sağlayacaktır. Her iki taskın çalıştığını görmek için UART üzerinden string gönderilmiştir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | void TaskFunction1(void * argument) { for(;;) { ulTaskNotifyTake(pdTRUE,portMAX_DELAY); Uart_Print("Notification received-Task1 is running.\n"); xTaskNotifyGive(Task2Handle); } } void TaskFunction2(void * argument) { for(;;) { ulTaskNotifyTake(pdTRUE,portMAX_DELAY); Uart_Print("Notification received-Task2 is running.\n\n"); } } |
Timer interrupt fonksiyonu aşağıdaki gibidir. Hatırlayalım; FreeRTOS systick timer’ı kullandığı için CubeMX’de HAL kütüphanesi Timer1’i kullanacak şekilde ayarlamıştık. Bu örnek için Timer2 yi 2 saniyede bir kesme oluşacak şekilde kullandım. Herhangi bir Timer kesmesi oluştuğunda program aşağıdaki fonksiyona dallanacaktır. Aşağıda görüldüğü gibi kesme kaynağı Timer2 den gelmiş ise Task1’e bildirim gönderilmiştir. Eğer daha yüksek öncelikli bir task çalışmak için hazırda bekliyorsa bir context switching oluşacak ve sıradaki task çalışacaktır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM1) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ if (htim->Instance == TIM2) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; vTaskNotifyGiveFromISR(Task1Handle,&xHigherPriorityTaskWoken); portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } /* USER CODE END Callback 1 */ } |
xTaskCreate() fonksiyonunu kullanırken son parametre olarak daha önce oluşturduğumuz task handle değişkenlerini girdik. Bu handle’lar yukarıda görüldüğü gibi bildirim gönderirken kullanılmıştır.
1 2 3 4 5 | xTaskCreate(TaskFunction1,"Task1",configMINIMAL_STACK_SIZE,NULL,0,&Task1Handle); xTaskCreate(TaskFunction2,"Task2",configMINIMAL_STACK_SIZE,NULL,0,&Task2Handle); HAL_TIM_Base_Start_IT(&htim2); vTaskStartScheduler(); |
Scheduler başlatılmadan önce timer başlatılmıştır. Timer, task fonksiyonlarından birinin içerisinde sonsuz döngü üzerinde de başlatılabilir hatta öyle daha güvenlidir çünkü scheduler başlamadan bir timer kesmesi oluşur ve kesme fonksiyonundan taska bildirim gönderilmeye çalışılırsa burada bir hata oluşabilir.
Tüm Kodlar ( FreeRTOS ile)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * Copyright (c) 2020 STMicroelectronics International N.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f1xx_hal.h" /* USER CODE BEGIN Includes */ #include "FreeRTOS.h" #include "task.h" #include <string.h> #define Uart_Print(__message) HAL_UART_Transmit(&huart1,(uint8_t *)__message,strlen(__message),HAL_MAX_DELAY) /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ TIM_HandleTypeDef htim2; UART_HandleTypeDef huart1; /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ TaskHandle_t Task1Handle,Task2Handle; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM2_Init(void); static void MX_USART1_UART_Init(void); /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ void TaskFunction1(void * argument); void TaskFunction2(void * argument); /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * * @retval None */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_TIM2_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ xTaskCreate(TaskFunction1,"Task1",configMINIMAL_STACK_SIZE,NULL,0,&Task1Handle); xTaskCreate(TaskFunction2,"Task2",configMINIMAL_STACK_SIZE,NULL,0,&Task2Handle); HAL_TIM_Base_Start_IT(&htim2); vTaskStartScheduler(); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = 16; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL14; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Configure the Systick interrupt time */ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0); } /* TIM2 init function */ static void MX_TIM2_Init(void) { TIM_ClockConfigTypeDef sClockSourceConfig; TIM_MasterConfigTypeDef sMasterConfig; htim2.Instance = TIM2; htim2.Init.Prescaler = 55999; htim2.Init.CounterMode = TIM_COUNTERMODE_UP; htim2.Init.Period = 999; htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } } /* USART1 init function */ static void MX_USART1_UART_Init(void) { huart1.Instance = USART1; huart1.Init.BaudRate = 115200; huart1.Init.WordLength = UART_WORDLENGTH_8B; huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_NONE; huart1.Init.Mode = UART_MODE_TX_RX; huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart1.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart1) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } } /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ static void MX_GPIO_Init(void) { /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); } /* USER CODE BEGIN 4 */ /* TaskFunction1 function */ void TaskFunction1(void * argument) { for(;;) { ulTaskNotifyTake(pdTRUE,portMAX_DELAY); Uart_Print("Notification received-Task1 is running.\n"); xTaskNotifyGive(Task2Handle); } } /* TaskFunction2 function */ void TaskFunction2(void * argument) { for(;;) { ulTaskNotifyTake(pdTRUE,portMAX_DELAY); Uart_Print("Notification received-Task2 is running.\n\n"); } } /* USER CODE END 4 */ /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM1) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ if (htim->Instance == TIM2) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; vTaskNotifyGiveFromISR(Task1Handle,&xHigherPriorityTaskWoken); portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } /* USER CODE END Callback 1 */ } /** * @brief This function is executed in case of error occurrence. * @param file: The file name as string. * @param line: The line in file as a number. * @retval None */ void _Error_Handler(char *file, int line) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ while(1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ |
CMSIS-RTOS ile Task Notification
CMSIS-RTOS da bildirim Signal Events kavramı ile kullanılır. Yani Signal Events fonksiyonları arka planda Task notification fonksiyonlarını kullanır. CubeMX te signal events ile ilgili yapılacak tek ayar “USE_TASK_NOTIFICATIONS” kutucuğunun “Enabled” olarak ayarlanmasıdır. CMSIS-RTOS da tasklar arası bildirim göndermek için aşağıdaki fonksiyonlar kullanılır.
1 2 | int32_t osSignalSet(osThreadId thread_id, int32_t signals); |
- thread_id : Bildirim gönderilecek olan task handle’ı
- signals : Gönderilecek olan 32 bitlik bildirim değeri.
- Return değeri : Taskın önceki bildirim değeri veya yanlış parametreler durumunda 0x80000000 değerini döndürür.
1 2 | osEvent osSignalWait(int32_t signals, uint32_t millisec); |
- signals : Task tarafından beklenen 32 bitlik bildirim değeri.
- millisec : Taskı blocked state de tutmak için girilen süre.
- Return değeri: osEvent tipinde bir struct döndürür. Bu struct ile bildirim değeri veya error tipine ulaşılabilir.
Signal events ile ilgili diğer fonksiyonlar için buraya tıklayabilirsiniz.
CMSIS-RTOS da task fonksiyonlarını aşağıdaki gibi düzenleyebiliriz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /* TaskFunction1 function */ void TaskFunction1(void const * argument) { for(;;) { osSignalWait(0x0001,osWaitForever); Uart_Print("Notification received-Task1 is running.\n"); osSignalSet(Task2Handle,0x0002); } } /* TaskFunction2 function */ void TaskFunction2(void const * argument) { for(;;) { osSignalWait(0x0002,osWaitForever); Uart_Print("Notification received-Task2 is running.\n\n"); } } |
Burada Task1 0x0001 bildirim değerini beklemektedir. Task2 ise farklı bir değer olan 0x0002 değerini beklemektedir. Her iki task ta aynı değeri bekleyebilir. Yukarıdaki fonksiyonlar FreeRTOS fonksiyonları ile yapılan örnekteki aynı işlemleri yapmaktadırlar.
Timer Kesme fonksiyonu ise aşağıdaki gibi düzenlenmiştir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM1) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ if (htim->Instance == TIM2) { osSignalSet(Task1Handle,0x0001); } /* USER CODE END Callback 1 */ } |
Burada dikkat edilirse CMSIS-RTOS da “fromISR” ile biten bir interrupt-safe fonksiyonu yoktur. osSignalSet() fonksiyonu interrupt veya task içinden çağrılabilecek şekilde yazılmıştır. osSignalSet() fonksiyonunun tanımlandığı yere gittiğimizde karşımıza aşağıdaki fonksiyon çıkar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | int32_t osSignalSet (osThreadId thread_id, int32_t signal) { #if( configUSE_TASK_NOTIFICATIONS == 1 ) BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t ulPreviousNotificationValue = 0; if (inHandlerMode()) { if(xTaskGenericNotifyFromISR( thread_id , (uint32_t)signal, eSetBits, &;ulPreviousNotificationValue, &xHigherPriorityTaskWoken ) != pdPASS ) return 0x80000000; portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } else if(xTaskGenericNotify( thread_id , (uint32_t)signal, eSetBits, &ulPreviousNotificationValue) != pdPASS ) return 0x80000000; return ulPreviousNotificationValue; #else (void) thread_id; (void) signal; return 0x80000000; /* Task Notification not supported */ #endif } |
Yukarıdaki fonksiyon incelendiğinde görüldüğü gibi bir handler yani interrupt içinden çağırıldığında xTaskGenericNotifyFromISR() fonksiyonu , bir task içerisinden çağrıldığında ise xTaskGenericNotify() fonksiyonu kullanılmaktadır.
Tüm Kodlar (CMSIS-RTOS ile)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 | /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * Copyright (c) 2020 STMicroelectronics International N.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f1xx_hal.h" #include "cmsis_os.h" /* USER CODE BEGIN Includes */ #include <string.h> #define Uart_Print(__message) HAL_UART_Transmit(&huart1,(uint8_t *)__message,strlen(__message),HAL_MAX_DELAY) /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ TIM_HandleTypeDef htim2; UART_HandleTypeDef huart1; osThreadId Task1Handle; osThreadId Task2Handle; /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM2_Init(void); static void MX_USART1_UART_Init(void); void TaskFunction1(void const * argument); void TaskFunction2(void const * argument); /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * * @retval None */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_TIM2_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* Create the thread(s) */ /* definition and creation of Task1 */ osThreadDef(Task1, TaskFunction1, osPriorityNormal, 0, 128); Task1Handle = osThreadCreate(osThread(Task1), NULL); /* definition and creation of Task2 */ osThreadDef(Task2, TaskFunction2, osPriorityNormal, 0, 128); Task2Handle = osThreadCreate(osThread(Task2), NULL); /* USER CODE BEGIN RTOS_THREADS */ /* add threads, ... */ /* USER CODE END RTOS_THREADS */ /* USER CODE BEGIN RTOS_QUEUES */ /* add queues, ... */ /* USER CODE END RTOS_QUEUES */ /* Start scheduler */ HAL_TIM_Base_Start_IT(&htim2); osKernelStart(); /* We should never get here as control is now taken by the scheduler */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = 16; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL14; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Configure the Systick interrupt time */ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0); } /* TIM2 init function */ static void MX_TIM2_Init(void) { TIM_ClockConfigTypeDef sClockSourceConfig; TIM_MasterConfigTypeDef sMasterConfig; htim2.Instance = TIM2; htim2.Init.Prescaler = 55999; htim2.Init.CounterMode = TIM_COUNTERMODE_UP; htim2.Init.Period = 1999; htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } } /* USART1 init function */ static void MX_USART1_UART_Init(void) { huart1.Instance = USART1; huart1.Init.BaudRate = 115200; huart1.Init.WordLength = UART_WORDLENGTH_8B; huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_NONE; huart1.Init.Mode = UART_MODE_TX_RX; huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart1.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart1) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } } /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ static void MX_GPIO_Init(void) { /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /* TaskFunction1 function */ void TaskFunction1(void const * argument) { for(;;) { osSignalWait(0x0001,osWaitForever); Uart_Print("Notification received-Task1 is running.\n"); osSignalSet(Task2Handle,0x0002); } } /* TaskFunction2 function */ void TaskFunction2(void const * argument) { for(;;) { osSignalWait(0x0002,osWaitForever); Uart_Print("Notification received-Task2 is running.\n\n"); } } /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM1) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ if (htim->Instance == TIM2) { osSignalSet(Task1Handle,0x0001); } /* USER CODE END Callback 1 */ } /** * @brief This function is executed in case of error occurrence. * @param file: The file name as string. * @param line: The line in file as a number. * @retval None */ void _Error_Handler(char *file, int line) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ while(1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ |
Kaynaklar
- Mastering the FreeRTOS™ Real Time Kernel-A Hands-On Tutorial Guide , Richard Barry
- freertos.org
- https://www.keil.com/pack/doc/CMSIS/RTOS/html/index.html
Teşekkürler, eline sağlık
Rica eder yorumunuz için ben teşekkür ederim. Umarım bu notların öğrenmek isteyenlere bir faydası dokunur.
Harika anlatım, bu kadar net açıklamaları bulabilmek neredeyse imkansız, elinize sağlık
Değerli yorumunuz için teşekkür ederim.