- Olay(event) nasıl algılanmalı? Kesmeler normal olarak kullanılır ancak input’lar polling ile algılanır.
- Kesmeler kullanıldığında ISR(Interrupt Service Routine) içerisinde ne kadar işlem yapılmalı? Genelde her ISR in olabildiğince kısa tutulması tavsiye edilir.
- Olaylar ana kod(ISR içinde olmayan) ile nasıl iletişime geçirilmeli?
- Task, FreeRTOS un üzerinde çalıştığı donanım ile ilgisi olmayan bir yazılım özelliğidir. Bir taskın önceliği yazılımcı tarafından atanır ve buna göre scheduler hangi taskın running state de bulunacağına karar verir.
- ISR bir donanım özelliğidir çünkü hangi ISR’in çalışacağını ve ne zaman çalışacağını donanım kontrol eder. Tasklar sadece ISR’in yürütülmediği zamanlarda yürütülür. Bu nedenle en düşük öncelikli ISR en yüksek öncelikli taskı kesintiye uğratabilir.
FreeRTOS API Fonksiyonlarının Bir ISR İçerisinden Kullanılması
Interrupt Safe API
Semaphore
- Binary Semaphore
- Counting Semaphore
Binary Semaphore
xSemaphoreCreateBinary() Fonksiyonu
FreeRTOS’da binary semaphore oluşturmak için xSemaphoreCreateBinary() API fonksiyonu kullanılır.
1 | SemaphoreHandle_t xSemaphoreCreateBinary( void ); |
xSemaphoreTake() Fonksiyonu
Semaphore’u almak için ise xSemaphoreTake() fonksiyonu kullanılır. Binary semaphore sadece bir kez alınabilir. Recursive mutex hariç bütün FreeRTOS semaphore tipleri bu fonksiyon ile semaphore’u alır. Bu fonksiyon interrupt fonksiyonu içerisinde kullanılmamalıdır(çünkü bir kesme bloklanamaz).
1 | BaseType_t xSemaphoreTake( SemaphoreHandle_t xSemaphore, TickType_t xTicksToWait ); |
- xSemaphore: Alınacak olan semaphore’un girildiği parametredir. Birden fazla semaphore olabilir. Bu parametre xSemaphoreCreateBinary() fonksiyonunun döndürdüğü değeri alır.
- xTicksToWait: Eğer semaphore verilmemiş ise ne kadar süre ile blocked state de kalacağının belirlendiği parametredir. portMAX_DELAY ile süresiz olarak bloklanabilir.( FreeRTOSConfig.h dosyasında INCLUDE_vTaskSuspended makrosu 1 olarak tanımlı ise)
- Return Değeri: Semaphore alındı ise pdTRUE, semaphore elde edilemediyse ve blok süresi dolduysa pdFALSE değerini döndürür.
xSemaphoreGive() ve xSemaphoreGiveFromISR() Fonksiyonu
Semaphore vermek veya bırakmak için xSemaphoreGive() fonksiyonu kullanılır. Bu fonksiyonun aldığı tek parametre verilecek olan semaphore’un handle’ıdır.
1 | xSemaphoreGive( SemaphoreHandle_t xSemaphore ); |
Eğer interrupt fonksiyonu içerisinden bir semaphore bırakılacak ise xSemaphoreGiveFromISR() API fonksiyonu kullanılmalıdır. Bu fonksiyon xSemaphoreGive() fonksiyonunun interrupt-safe versiyonudur.
1 2 | BaseType_t xSemaphoreGiveFromISR( SemaphoreHandle_t xSemaphore, BaseType_t *pxHigherPriorityTaskWoken ); |
- xSemaphore: Bırakılacak olan semaphore handle’ı
- *pxHigherPriorityTaskWoken: Bu parametreyi anlamak biraz zor. Eğer xSemaphoreGiveFromISR() fonksiyonu bu parametreyi pdTRUE olarak ayarlarsa semaphore’u alan taskın önceliği, o anda çalışan taskın(kesme ile kesintiye uğrayan task) önceliğinden yüksek demektir. Eğer böyle bir durum var ise ISR fonksiyonundan çıkmadan FreeRTOS’u “context switch” denen bir işleme zorlamak gerekir. Context switching scheduler’ın tasklar arasında yaptığı geçiştir. Bu geçişi ise ISR fonksiyonunun sonunda portYIELD_FROM_ISR( xHigherPriorityTaskWoken ) şeklinde bir kod kullanarak yapabiliriz.
- Return Değeri: Eğer semaphore verildi(give) ise pdPASS, semaphore zaten mevcut ise pdFAIL değeri döndürür.
Counting Semaphore
xSemaphoreCreateCounting() Fonksiyonu
1 2 | SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount); |
- uxMaxCount: Maksimum count değerini ifade eder. Semaphore bu değere ulaştığında xSemaphoreGive() fonksiyonu ile daha fazla semafor verilemez.
- uxInitialCount: Başlangıçtaki count değerinin giridiği parametredir.
- Return Değeri: Semaphore oluşturulamadı ise NULL,oluşturuldu ise bir handle döndürür.
FreeRTOS’daki semaphore ile ilgili diğer fonksiyonlar hakkında daha fazla bilgi için buraya tıklayabilirsiniz.
FreeRTOS Semaphore Kullanımına Ait Örnek
1 2 3 | #include "FreeRTOS.h" #include "task.h" #include "semphr.h" |
1 | SemaphoreHandle_t BinarySem; |
1 | BinarySem = xSemaphoreCreateBinary(); |
1 2 3 4 | xTaskCreate(Task1,"Task 1",configMINIMAL_STACK_SIZE,NULL,0,NULL); // priorty 0 xTaskCreate(HandlerTask,"Task 2",configMINIMAL_STACK_SIZE,NULL,1,NULL); // priority 1 vTaskStartScheduler(); |
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 | void Task1(void * argument) { for(;;) { Uart_Print("Task1 is running...\n"); vTaskDelay(pdMS_TO_TICKS(1000)); } } void HandlerTask(void * argument) { for(;;) { xSemaphoreTake(BinarySem,portMAX_DELAY); // If semaphore is not available, the task waits for the maximum time in the blocked state. Uart_Print("Handler Task is running...\n"); } } void EXTI0_IRQHandler(void) // ISR function { BaseType_t xHigherPriorityTaskWoken = pdFALSE; Uart_Print("ISR is runnng...\n"); xSemaphoreGiveFromISR(BinarySem,&xHigherPriorityTaskWoken); // Give the semaphore from ISR __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_0); // clear flag portYIELD_FROM_ISR(xHigherPriorityTaskWoken); // if xHigherPriorityTaskWoken is equal pdTRUE then force the kernel to context switching } |
1 2 3 4 5 | /* The highest interrupt priority that can be used by any interrupt service routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER PRIORITY THAN THIS! (higher priorities are lower numeric values. */ #define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5 |
1 2 3 | /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI0_IRQn, 5, 0); HAL_NVIC_EnableIRQ(EXTI0_IRQn); |
FreeRTOS ile Semaphore Kullanımı Tüm Kodlar
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 | /** ****************************************************************************** * @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 <string.h> #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #define Uart_Print(__message) HAL_UART_Transmit(&huart1,(uint8_t *)__message,strlen(__message),1000) /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ UART_HandleTypeDef huart1; /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ SemaphoreHandle_t BinarySem; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_USART1_UART_Init(void); /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ void Task1(void * argument); void HandlerTask(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_USART1_UART_Init(); /* USER CODE BEGIN 2 */ BinarySem = xSemaphoreCreateBinary(); xTaskCreate(Task1,"Task 1",configMINIMAL_STACK_SIZE,NULL,0,NULL); // priority 0 xTaskCreate(HandlerTask,"Task 2",configMINIMAL_STACK_SIZE,NULL,1,NULL); // priority 1 vTaskStartScheduler(); /* USER CODE END 2 */ /* 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_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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); } /* 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_InitTypeDef GPIO_InitStruct; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /*Configure GPIO pin : PA0 */ GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI0_IRQn, 5, 0); HAL_NVIC_EnableIRQ(EXTI0_IRQn); } /* USER CODE BEGIN 4 */ /* Task Functions */ void Task1(void * argument) { for(;;) { Uart_Print("Task1 is running...\n"); vTaskDelay(pdMS_TO_TICKS(1000)); } } void HandlerTask(void * argument) { for(;;) { xSemaphoreTake(BinarySem,portMAX_DELAY); // If semaphore is not available, the task waits for the maximum time in the blocked state. Uart_Print("Handler Task is running...\n"); } } void EXTI0_IRQHandler(void) // ISR function { BaseType_t xHigherPriorityTaskWoken = pdFALSE; Uart_Print("ISR is runnng...\n"); xSemaphoreGiveFromISR(BinarySem,&xHigherPriorityTaskWoken); // Give semaphore from ISR __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_0); // clear ISR flag portYIELD_FROM_ISR(xHigherPriorityTaskWoken); // if xHigherPriorityTaskWoken is equal pdTRUE then force the kernel to context switching } /* 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 */ /* 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 Semaphore Örneği
osSemaphoreDef() Makrosu
1 | #define osSemaphoreDef( name) const osSemaphoreDef_t os_semaphore_def_##name = { 0 } |
osSemaphoreCreate() Fonskiyonu
1 | osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) |
- *semaphore_def: osSemaphoreDef() makrosu ile tanımlanmış olan semaphore isminin girildiği parametredir. Bu parametre osSemaphore() referansı ile girilmelidir.
- count: Buradaki count parametresi semaphore’un binary mi yoksa counting mi olacağını belirler. Eğer bu parametre 1 girilirse binary semaphore, 1 den fazla bir değer girilirse counting semaphore olarak tanımlanır.
- Return Değeri: Hata oluştu ise NULL, oluşmadı ise semaphore handle’ı döndürür.
1 | semaphore1Handle = osSemaphoreCreate(osSemaphore(semaphore1), 1); |
1 | osSemaphoreId semaphore1Handle; |
osSemaphoreWait() Fonskiyonu
Semaphore’u almak için bu fonksiyon kullanılır. Yani FreeRTOS daki xSemaphoreTake() fonksiyonunun CMSIS-RTOS daki karşılığıdır.
1 | int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) |
- semaphore_id: Alınacak olan semaphore handle’ı.
- millisec: Semaphore yoksa ne kadar süre bekleneceği bu parametre ile belirlenir. Bu parametre yerine osWaitForever yazılırsa süresiz olarak beklenir.
- Return Değeri : RTOS’da token( jeton) diye bir kavram vardır. Bu token sayısı kuyruktaki eleman sayısı gibi düşünülebilir. Bu fonksiyon kuyrukta bekleyen token yani jetonların sayısını döndürür. Counting semaphore kullanırken bu parametre kullanışlı olabilir. Eğer kuyrukta token kalmamışsa ve “millisec” parametresi osWaitForever dan farklı bir şey girilmiş ise bu süre sonunda -1 değeri döndürür. Bu demektir ki blok süresi dolmuş ve token yok.
1 | osSemaphoreWait(semaphore1Handle,osWaitForever); |
osSemaphoreRelease() Fonskiyonu
Bu fonksiyon semaphore’u bırakmak için kullanılır. CMSIS-RTOS’da bu fonksiyonun interrupt içinde de kullanılabilir. CMSIS-RTOS’da iki farklı versiyon fonksiyon oluşturmak yerine bu işlem tek fonskiyon ile yapılmış. Bu fonksiyon nereden çağrıldığını(interrupt veya task) biliyor. İlginç değil mi? Hatta eğer interrupt içinden çağrılmış ise context switching’i otomatik olarak yapıyor.
1 | osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) |
- semaphore_id: Semaphore handle
- Return Değeri: Eğer fonksiyon başarılı bir şekilde çalışmış ise osOK, hata oluşmuş ise osErrorOS değerini döndürür.
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 | void EXTI0_IRQHandler(void) // ISR function { Uart_Print("[CMSIS-RTOS] ISR is runnng...\n"); osSemaphoreRelease(semaphore1Handle); // relaese semaphore __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_0); // clear ISR flag } /* Task1_Function function */ void Task1_Function(void const * argument) { /* USER CODE BEGIN 5 */ /* Infinite loop */ for(;;) { Uart_Print("[CMSIS-RTOS] Task1 is running...\n"); osDelay(1000); } /* USER CODE END 5 */ } /* HandlerTask function */ void HandlerTask(void const * argument) { /* USER CODE BEGIN HandlerTask */ /* Infinite loop */ for(;;) { osSemaphoreWait(semaphore1Handle,osWaitForever); Uart_Print("[CMSIS-RTOS] Handler Task is running...\n"); } /* USER CODE END HandlerTask */ } |
CubeMX Ayarları
CMSIS-RTOS ile Semaphore Tüm Kodlar
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 | /** ****************************************************************************** * @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),1000) /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ UART_HandleTypeDef huart1; osThreadId Task1Handle; osThreadId HandlerHandle; osSemaphoreId semaphore1Handle; /* 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_USART1_UART_Init(void); void Task1_Function(void const * argument); void HandlerTask(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_USART1_UART_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* Create the semaphores(s) */ /* definition and creation of semaphore1 */ osSemaphoreDef(semaphore1); semaphore1Handle = osSemaphoreCreate(osSemaphore(semaphore1), 1); /* 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, Task1_Function, osPriorityNormal, 0, 128); Task1Handle = osThreadCreate(osThread(Task1), NULL); /* definition and creation of Handler */ osThreadDef(Handler, HandlerTask, osPriorityAboveNormal, 0, 128); HandlerHandle = osThreadCreate(osThread(Handler), 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 */ 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_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; 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); } /* 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_InitTypeDef GPIO_InitStruct; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /*Configure GPIO pin : PA0 */ GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_PULLDOWN; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI0_IRQn, 5, 0); HAL_NVIC_EnableIRQ(EXTI0_IRQn); } /* USER CODE BEGIN 4 */ void EXTI0_IRQHandler(void) // ISR function { Uart_Print("[CMSIS-RTOS] ISR is runnng...\n"); osSemaphoreRelease(semaphore1Handle); // relaese semaphore __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_0); // clear ISR flag } /* USER CODE END 4 */ /* Task1_Function function */ void Task1_Function(void const * argument) { /* USER CODE BEGIN 5 */ /* Infinite loop */ for(;;) { Uart_Print("[CMSIS-RTOS] Task1 is running...\n"); osDelay(1000); } /* USER CODE END 5 */ } /* HandlerTask function */ void HandlerTask(void const * argument) { /* USER CODE BEGIN HandlerTask */ /* Infinite loop */ for(;;) { osSemaphoreWait(semaphore1Handle,osWaitForever); Uart_Print("[CMSIS-RTOS] Handler Task is running...\n"); } /* USER CODE END HandlerTask */ } /** * @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 */ /* 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
Gayet açıklayıcı bir yazı olmuş,teşekkürler. Kafamdaki bazı soru işaretlerini sildi attı. 🙂
Rica ederim. 🙂
Selamlar,
STm32 cube ıde de freertos cimsis V2 kullanarak bir uygulama gerçeklemek istiyorum.
Uygulamada aynı priority e sahip tasklar var. yeni oluşturacağım task da aynı önceliğe sahip olacak. bu task içerisinde bir sensörden kesme alıp bu kesmeye göre task ın bazı işlemleri gerçeklemesini istiyorum. semaphore kullanmayı denedim fakat başarılı olamadım. diğer task işlemlerine sürekli devam ederken bu yeni oluşturduğum task a dallanma yapmıyor. (preemptive scheduling.) bu kesme geldiğinde diğer task çalışmasını durdurması gerek. o yüzden hepsi aynı priority olarak ayarlandı. fakat kesme task ına geçiş yapamıyor. semaphore işe yaramadı. Nedeni ne olabilir? Fikir verebilir misiniz?
Merhaba Furkan
Tam olarak sebebini bilmiyorum ama birkaç fikrim var. Kesmede kullandığın semaphore fonksiyonu interrupt safe versiyon olan olmayabilir. Ayarladığın kesme donanımsal bir kesme ise önceliği freertos’un kullandığı bir kesmeden düşük olabilir. Task’ın stack’i yetmiyor olabilir. Eğer task semaphore take fonksiyonunu çağırmadan kesme içinde semaphore release yapıyor olabilirsin. Şimdilik aklıma gelenler bunlar Furkan. Umarım yardımcı olabilmişimdir.
Teşekkürler.
Hocam merhaba, “fromISR” fonksiyonunu ben timer içinde kullanıyorum, bir veriyi sürekli kontrol ediyorum ve eğer gerekiyorsa task’a dallanıyor. Bazen sistemin çalışması duruyor heap size değerleri de yeterli seviyede. Yazınızda kesme önceliğinden bahsetmişsiniz bende değerler şu şekilde;
/*Timer kesme önceliği*/
NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
(Değer aralığı 0 ile 3 arasında)
/* Freertos config */
#define configPRIO_BITS 5
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5
#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 – configPRIO_BITS) )
Kullandığım işlemci Stm32f0 serisinden sizde configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5 iken bende daha yüksek bundan kaynaklı donmalar oluyor olabilir mi?
Merhaba, yorumunu yeni gördüm.
Bu donmalar bazen oluyorsa sorunun öncelikten kaynaklandığını düşünmüyorum. Heap size yeterli olup olmadığını neye göre karar verdin. Taskın içinde yaptığın fonksiyon çağrısına göre bile ayırdığın heap taşabilir. Tavisyem vApplicationStackOverflowHook fonksiyonu ile bir taşma olup olmadığını kontrol et. Bu fonksiyon içinde eğer taşma oluyorsa hangi tasktan kaynaklandığını bulabilirsin. Bu fonksiyonu kullanabilmek için FreeRTOS config dosyasında bir makro vardı galiba. O makroyu aktif etmek gerekecektir. Eğer sorun bundan kaynaklanmıyorsa tekrar yorum yaz tartışalım.
Merhaba, evet dediğiniz gibi öncelikten kaynaklı değilmiş. Problem tasklar başlamadan önce Timer kesmesi xSemaphoreGiveFromISR komutunu çağırıyor ve ondan sonra sistem donuyormuş:)