| 367 | // ============================================================================= |
| 368 | |
| 369 | int attach_timer_handler(const isr_config_t& config, isr_handle_t* out_handle) FL_NOEXCEPT { |
| 370 | if (!config.handler) { |
| 371 | FL_WARN("attachTimerHandler: handler is null"); |
| 372 | return -1; // Invalid parameter |
| 373 | } |
| 374 | |
| 375 | if (config.frequency_hz == 0) { |
| 376 | FL_WARN("attachTimerHandler: frequency_hz is 0"); |
| 377 | return -2; // Invalid frequency |
| 378 | } |
| 379 | |
| 380 | // Allocate a free timer |
| 381 | u8 timer_idx = 0; |
| 382 | if (!allocate_timer(timer_idx)) { |
| 383 | FL_WARN("attachTimerHandler: no free timers"); |
| 384 | return -3; // Out of resources |
| 385 | } |
| 386 | |
| 387 | Tc* timer = get_timer_instance(timer_idx); |
| 388 | if (!timer) { |
| 389 | free_timer(timer_idx); |
| 390 | FL_WARN("attachTimerHandler: invalid timer instance"); |
| 391 | return -4; // Internal error |
| 392 | } |
| 393 | |
| 394 | // Allocate handle data |
| 395 | auto handle_owner = fl::make_unique<samd_isr_handle_data>(); |
| 396 | auto* handle_data = handle_owner.get(); |
| 397 | if (!handle_data) { |
| 398 | free_timer(timer_idx); |
| 399 | FL_WARN("attachTimerHandler: failed to allocate handle data"); |
| 400 | return -5; // Out of memory |
| 401 | } |
| 402 | |
| 403 | handle_data->is_timer = true; |
| 404 | handle_data->timer_instance = timer; |
| 405 | handle_data->timer_index = timer_idx; |
| 406 | handle_data->timer_irq = get_timer_irq(timer_idx); |
| 407 | handle_data->user_handler = config.handler; |
| 408 | handle_data->user_data = config.user_data; |
| 409 | |
| 410 | // Store handle for ISR access |
| 411 | timer_handles[timer_idx] = handle_data; |
| 412 | |
| 413 | // Enable clock for timer |
| 414 | #if defined(FL_IS_SAMD21) |
| 415 | // SAMD21: Use GCLK to route clock to TC peripheral |
| 416 | // Most SAMD21 boards use GCLK_CLKCTRL_ID_TCC2_TC3 for TC3/TC4/TC5 |
| 417 | u16 gclk_id; |
| 418 | if (timer_idx <= 5) { |
| 419 | gclk_id = GCLK_CLKCTRL_ID_TCC2_TC3; |
| 420 | } else { |
| 421 | gclk_id = GCLK_CLKCTRL_ID_TCC2_TC3; // Adjust if TC6/TC7 available |
| 422 | } |
| 423 | |
| 424 | GCLK->CLKCTRL.reg = (u16)(GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | gclk_id); |
| 425 | while (GCLK->STATUS.bit.SYNCBUSY) { |
| 426 | // Wait for sync |
nothing calls this directly
no test coverage detected