Software Timer Callback Fonksiyonu
Callback fonksiyonu void tipinde tanımlanmış yani herhangi bir değer döndürmeyen, parametre olarak TimerHandle_t tipinde bir değer alan aşağıdaki gibi bir fonksiyondur.
1 | void ATimerCallback( TimerHandle_t xTimer ); |
One-shot ve Auto-Reload Timer
- One-shot: Callback fonksiyonu sadece bir kez yürütülür. Manuel olarak tekrar başlatılmalıdır. Kendini otomatik olarak tekrar başlatmaz.
- Auto-reload: Timer callback fonksiyonu otomatik olarak yürütülür. Periyoda bağlı olarak kendini tekrar başlatır. Yani callback fonksiyonu periyodik olarak yürütülür.
Yazılımsal Timer Durumları
- Dormant(uykuda): Callback fonksiyonunun kodlarının yürütülmediği, timerın bir nevi uykuda olduğu durumdur.
- Running: Bu durumda bulunan timer periyod süresini tamamladıktan sonra callback fonksiyonunu çalıştırır.
Timer Daemon (Timer Service) Task
Timer Komut Kuyruğu
Timer Oluşturma
FreeRTOS da timer oluşturmak için xTimerCreate() fonksiyonu kullanılır. Bu fonksiyon TimerHandle_t tipinde bir handle döndürür. Başlangıçta software timer dormant state’de bulunur. Yani oluşturulur oluşturulmaz hemen saymaya başlamaz. Timer scheduler dan önce veya sonra bir task içerisinde oluşturulabilir.
1 2 3 4 5 | TimerHandle_t xTimerCreate( const char * const pcTimerName, TickType_t xTimerPeriodInTicks, UBaseType_t uxAutoReload, void * pvTimerID, TimerCallbackFunction_t pxCallbackFunction ); |
- pcTimerName: Timer a isim vermek için kullanılır. Bu parametre FreeRTOS tarafından kullanılmaz , debug vb işlemler için kullanılabilir.
- xTimerPeriodlnTicks: Tick cinsinden timer periyodudur. pdMS_TO_TICKS() fonksiyonu kullanılarak periyod milisaniye cinsinden ayarlanabilir.
- uxAutoReload: Bu parametre pdTRUE olarak girilirse timer auto-reload olarak çalışır. Eğer pdFALSE olarak girilirse one-shot timer olarak çalışır.
- pvTimerID: Her yazılımsal timerın bir ID değeri vardır. Bu ID void pointer olarak tanımlıdır ve yazılımcı tarafından herhangi bir amaç için kullanılabilir. ID genelde aynı callback fonskiyonunu birden fazla timerın kullandığı uygulamalarda kullanışlıdır.
- pxCallbackFunction: Timer callback fonksiyonunun adı bu parametre ile girilir.
- Return Değeri: Döndürdüğü değer NULL ise timer oluşturmada hata olmuş demektir. Eğer hatasız oluşturulmuş ise bir handle değeri döner.
Timer’ı Başlatma
1 | BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); |
- xTimer: xTimerCreate fonskiyonunun döndürdüğü handle girilir.
- xTicksToWait: Timerın komut kuyruğu kullandığını söylemiştik. Bu parametre kuyruk dolu ise ne kadar süre bekleneceğini belirtmek için kullanılır. Eğer xTimerStart fonksiyonu scheduler başlatma fonksiyonundan önce kullanılırsa FreeRTOS bu parametreyi dikkate almaz.
- Return Değeri: timer başlatma komutu kuyruğa başarılı bir şekilde gönderildi ise pdTRUE, gönderilemedi ise pdFALSE değeri döndürür.
FreeRTOS Yazılımsal Timer Kullanımına Ait Bir Örnek
1 2 3 4 5 | /* Software timer definitions. */ #define configUSE_TIMERS 1 #define configTIMER_TASK_PRIORITY ( 6 ) #define configTIMER_QUEUE_LENGTH 10 #define configTIMER_TASK_STACK_DEPTH 256 |
1 2 3 | #include "FreeRTOS.h" #include "task.h" #include "timers.h" |
1 | TimerHandle_t Auto_Reload_Timer,One_Shot_Timer; |
İki adet timer handle oluşturuldu. Bu handle timer’ı başlatmak, durdurmak gibi işlemleri yapan fonksiyonlara parametre olarak gönderilir.
1 2 3 4 5 6 7 8 9 10 11 | One_Shot_Timer = xTimerCreate("One-Shot", // Software timer's name pdMS_TO_TICKS(3500), // Period pdFALSE, // One-shot mode 0, // Timer id OneShotTimerCallback); // Callback function Auto_Reload_Timer = xTimerCreate("Auto-Reload", // Software timer's name pdMS_TO_TICKS(1000), // Period pdTRUE, // One-shot mode 0, // Timer id AutoReloadTimerCallback); // Callback function, |
Timer periyodları 3500 ve 1000 milisaniye olarak ayarlanmıştır. Bu örnekte timer id si kullanılmadığı için sıfır olarak girilmiştir.
1 2 3 4 | xTimerStart(One_Shot_Timer,0); xTimerStart(Auto_Reload_Timer,0); vTaskStartScheduler(); |
Timerlar schedulerdan önce başlatılmıştır. Burada blok süresi sıfırdan farklı girilse bile FreeRTOS bu parametreye dikkat etmez çünkü henüz scheduler başlatılmamıştır. Yani timer başlatma fonksiyonları çağrılsa bile scheduler başlatılmadan timer saymaya başlamaz. Timer herhangi bir task fonksiyonu içerisinden de başlatılabilirdi. Bu örnekte normal bir task fonksiyonu tanımlanmamıştır. Bu yüzden scheduler başlatıldıktan sonra çalışacak olan tek task “Idle Task” tır. Timer periyotlarına göre arada Daemon task da çalışacaktır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | void OneShotTimerCallback(TimerHandle_t xTimer) { TickType_t CurrentTime; char string[50]; CurrentTime = xTaskGetTickCount(); sprintf(string,"One-Shot Timer: %d\n",CurrentTime); Uart_Print(string); } void AutoReloadTimerCallback(TimerHandle_t xTimer) { TickType_t CurrentTime; char string[50]; CurrentTime = xTaskGetTickCount(); sprintf(string,"Auto-Reload Timer: %d\n",CurrentTime); Uart_Print(string); } |
Tüm Kodlar (FreeRTOS İle)
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 | /** ****************************************************************************** * @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 "timers.h" /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ UART_HandleTypeDef huart1; #define Uart_Print(__message) HAL_UART_Transmit(&huart1,(uint8_t *)__message,strlen(__message),HAL_MAX_DELAY) /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ TimerHandle_t Auto_Reload_Timer,One_Shot_Timer; /* 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 OneShotTimerCallback(TimerHandle_t xTimer); void AutoReloadTimerCallback(TimerHandle_t xTimer); /* 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 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ One_Shot_Timer = xTimerCreate("One-Shot", // Software timer's name pdMS_TO_TICKS(3500), // Period pdFALSE, // One-shot mode 0, // Timer id OneShotTimerCallback); // Callback function Auto_Reload_Timer = xTimerCreate("Auto-Reload", // Software timer's name pdMS_TO_TICKS(1000), // Period pdTRUE, // One-shot mode 0, // Timer id AutoReloadTimerCallback);// Callback function, xTimerStart(One_Shot_Timer,0); xTimerStart(Auto_Reload_Timer,0); vTaskStartScheduler(); 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 Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); } /* USER CODE BEGIN 4 */ void OneShotTimerCallback(TimerHandle_t xTimer) { TickType_t CurrentTime; char string[50]; CurrentTime = xTaskGetTickCount(); sprintf(string,"One-Shot Timer: %d\n",CurrentTime); Uart_Print(string); } void AutoReloadTimerCallback(TimerHandle_t xTimer) { TickType_t CurrentTime; char string[50]; CurrentTime = xTaskGetTickCount(); sprintf(string,"Auto-Reload Timer: %d\n",CurrentTime); Uart_Print(string); } /* 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 Yazılımsal Timer Kullanımı
1 2 3 | osThreadId defaultTaskHandle; osTimerId OneShotHandle; osTimerId AutoReloadHandle; |
1 2 3 4 5 6 7 | /* definition and creation of OneShot */ osTimerDef(OneShot, OneShotCallback); OneShotHandle = osTimerCreate(osTimer(OneShot), osTimerOnce, NULL); /* definition and creation of AutoReload */ osTimerDef(AutoReload, AutoReloadCallback); AutoReloadHandle = osTimerCreate(osTimer(AutoReload), osTimerPeriodic, NULL); |
1 | #define osTimerDef(name,function) |
Timer oluşturmak için osTimerCreate() fonksiyonu kullanılır.
1 2 3 | osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) |
- *timer_def: Bu parametre osTimerDef_t tipinde olmalı ve osTimer ile referans verilerek girilmelidir.
- type: Timer’ın tipini seçmek için kullanılan parametredir. osTimerOnce ise one-shot timer , osTimerPeriodic ise Auto-Reload Timer olarak ayarlanır.
- *argument : Timer callback fonksiyonuna değer göndermek için kullanılır. Bu örnek te değer gönderilmediği için NULL olarak girilmiştir.
- Return değeri: Eğer timer sorunsuz oluşturuldu ise osTimerId tipinde bir handle döndürür. Sorun oluştu ise NULL değeri döner.
1 | osStatus osTimerStart (osTimerId timer_id, uint32_t millisec) |
- timer_id: osTimerCreate() fonksiyonunun döndürdüğü değer girilir.
- millisec: Milisaniye cinsinden timer periyodunu belirlemek için girilen parametredir.
1 2 3 | osTimerStart(OneShotHandle,3500); osTimerStart(AutoReloadHandle,1000); osKernelStart(); |
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 | void OneShotCallback(void const * argument) { /* USER CODE BEGIN OneShotCallback */ char string[50]; uint32_t currentTick; currentTick = osKernelSysTick(); sprintf(string,"One-Shot Timer : %d\n",currentTick); Uart_Print(string); /* USER CODE END OneShotCallback */ } /* AutoReloadCallback function */ void AutoReloadCallback(void const * argument) { /* USER CODE BEGIN AutoReloadCallback */ char string[50]; uint32_t currentTick; currentTick = osKernelSysTick(); sprintf(string,"Auto-Reload Timer : %d\n",currentTick); Uart_Print(string); /* USER CODE END AutoReloadCallback */ } |
CMSIS-RTOS da yazılımsal timer ile ilgili diğer fonksiyonlara buraya tıklayarak ulaşabilirsiniz.
CubeMX Ayarları
- Scheduler başlatılmadan önce birden fazla timer API fonksiyonunun çağrılması
- Interrup-safe adı verilen yani ISR içerisinden çağrılan sonu “fromISR” ile biten timer fonksiyonları kullanmak(kuyruğu dolduracak kadar fazla).
- Timer Service Task(Daemon Task) ın önceliğinden daha yüksek öncelikteki bir taskın içerisinde birden fazla timer API fonksiyonları kullanmak.
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 | /** ****************************************************************************** * @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 ---------------------------------------------------------*/ UART_HandleTypeDef huart1; osThreadId defaultTaskHandle; osTimerId OneShotHandle; osTimerId AutoReloadHandle; /* 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 StartDefaultTask(void const * argument); void OneShotCallback(void const * argument); void AutoReloadCallback(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 */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* Create the timer(s) */ /* definition and creation of OneShot */ osTimerDef(OneShot, OneShotCallback); OneShotHandle = osTimerCreate(osTimer(OneShot), osTimerOnce, NULL); /* definition and creation of AutoReload */ osTimerDef(AutoReload, AutoReloadCallback); AutoReloadHandle = osTimerCreate(osTimer(AutoReload), osTimerPeriodic, NULL); /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* Create the thread(s) */ /* definition and creation of defaultTask */ osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 128); defaultTaskHandle = osThreadCreate(osThread(defaultTask), 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 */ osTimerStart(OneShotHandle,3500); osTimerStart(AutoReloadHandle,1000); 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 Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /* StartDefaultTask function */ void StartDefaultTask(void const * argument) { /* USER CODE BEGIN 5 */ /* Infinite loop */ for(;;) { osDelay(1); } /* USER CODE END 5 */ } /* OneShotCallback function */ void OneShotCallback(void const * argument) { /* USER CODE BEGIN OneShotCallback */ char string[50]; uint32_t currentTick; currentTick = osKernelSysTick(); sprintf(string,"One-Shot Timer : %d\n",currentTick); Uart_Print(string); /* USER CODE END OneShotCallback */ } /* AutoReloadCallback function */ void AutoReloadCallback(void const * argument) { /* USER CODE BEGIN AutoReloadCallback */ char string[50]; uint32_t currentTick; currentTick = osKernelSysTick(); sprintf(string,"Auto-Reload Timer : %d\n",currentTick); Uart_Print(string); /* USER CODE END AutoReloadCallback */ } /** * @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
Hocam merhaba diyelim ki 3 tane timer yarattık üçü de 1 saniyelik olsun.Ben bunların sırası ile örneğin önce 1.fonksiyona sonra 2 .fonksiyona sonra 3 e girmesini nasıl sağlayabilirim?
Merhaba, FreeRTOS da birden fazla timer tanımlandığında aralarında bir öncelik belirtemiyoruz malesef. Bu demek değildir ki aynı periyoda sahip olan callback fonksiyonları rastgele çalışacak. Şöyle düşünelim ; bu callback fonksiyonlarını yürüten Daemon task ve bu task a bu callback fonksiyonları arkaplanda bir kuyruk yardımıyla gönderiliyor. Yani önce hangi callback fonksiyonunu yürüteceğini bu kuyruktaki verilere göre belirliyor. Bu kuyruğa önce hangi callback fonksiyonu eklenirse ilk o yürütülecektir(tabi periyotları aynı olduğu sürece). Peki kuyruğa ilk çalışmasını istediğim callback fonksiyonunu nasıl ekleyebiliriz? Bunu ilk olarak ilgili timer’ı başlatarak yapabilirsiniz. Örneğin;
******
xTimerStart(Timer1,0);
xTimerStart(Timer2,0);
xTimerStart(Timer3,0);
vTaskStartScheduler();
*****
şeklinde kullanabilirsiniz. Bu kullanımda sırasıyla timer1 ,timer2 ve timer3 e ait olan callback fonksiyonları yürütülecektir.
Peki hocam xTimerStart(Timer1,0); bu fonksiyon 2.den daha uzun sürdüğünde Timer2 nin fonksiyonu devreye girer mi?Benim istediği diyelim ki timer1 in fonksiyonu içeride 300 ms sürsün Timer 2 ninki 10 ms sürsün bu durumda önce timer2nin işini mi yapar?Yaparsa benim istediğim şekilde yani önce 1 tetiklenecek 1 in fonksiyonu tamalanacak sonra 2 ,sonra 3?
Timer1 callback fonksiyonu işlemlerini bitirmeden Timer2 fonksiyonu çalışmaz. Demaon task önce Timer1’in sonra Timer2’nin ve eğer kuyrukta başka çalıştırılmayı bekleyen bir callback fonksiyonu varsa onu da çalıştırıp sonra diğer normal tasklar çalışmaya başlar. Yani ister 300 ms sürsün isterse 1ms, önce kuyruğa ilk eklenen çalışır. RTOS ile ilgili kitaplarda veya başka kaynaklarda bu fonksiyonların içinin olabildiğince kısa tutulması söylenir. Gerçek zamanlı sistemlerde 300 ms aslında çok uzun bir süre.