| 272 | // ============================================================================ |
| 273 | |
| 274 | int setPwmFrequency(int pin, u32 frequency_hz) { |
| 275 | // Check if pin already has a channel |
| 276 | pwm_state::PwmPinState* ch = pwm_state::findByPin(pin); |
| 277 | |
| 278 | if (ch) { |
| 279 | // Pin already configured — release and reconfigure |
| 280 | pwm_state::releaseChannel(ch); |
| 281 | ch = nullptr; |
| 282 | } |
| 283 | |
| 284 | // Validate frequency |
| 285 | if (frequency_hz == 0) { |
| 286 | FL_WARN("setPwmFrequency: Frequency must be > 0"); |
| 287 | return -1; |
| 288 | } |
| 289 | |
| 290 | // Query platform: can it handle this natively? |
| 291 | bool needs_isr = platforms::needsPwmIsrFallback(pin, frequency_hz); |
| 292 | |
| 293 | if (!needs_isr) { |
| 294 | // Native path |
| 295 | int result = platforms::setPwmFrequencyNative(pin, frequency_hz); |
| 296 | if (result != 0) { |
| 297 | FL_WARN("setPwmFrequency: Native backend failed: " << result); |
| 298 | return result; |
| 299 | } |
| 300 | |
| 301 | // Allocate tracking slot |
| 302 | ch = pwm_state::allocate(); |
| 303 | if (!ch) { |
| 304 | FL_WARN("setPwmFrequency: All " << static_cast<int>(pwm_state::MAX_PWM_CHANNELS) << " channels in use"); |
| 305 | return -2; |
| 306 | } |
| 307 | |
| 308 | ch->pin = pin; |
| 309 | ch->frequency_hz = frequency_hz; |
| 310 | ch->backend = pwm_state::PwmBackend::Native; |
| 311 | ch->duty_cycle = 0; |
| 312 | return 0; |
| 313 | } |
| 314 | |
| 315 | // ISR software fallback path |
| 316 | if (frequency_hz > pwm_state::MAX_ISR_PWM_FREQUENCY) { |
| 317 | FL_WARN("setPwmFrequency: ISR fallback max " << pwm_state::MAX_ISR_PWM_FREQUENCY << " Hz, requested " << frequency_hz); |
| 318 | return -1; |
| 319 | } |
| 320 | |
| 321 | // Allocate channel |
| 322 | ch = pwm_state::allocate(); |
| 323 | if (!ch) { |
| 324 | FL_WARN("setPwmFrequency: All " << static_cast<int>(pwm_state::MAX_PWM_CHANNELS) << " channels in use"); |
| 325 | return -2; |
| 326 | } |
| 327 | |
| 328 | // Ensure ISR is running |
| 329 | int isr_result = pwm_state::ensureIsrActive(); |
| 330 | if (isr_result != 0) { |
| 331 | return -3; |
no test coverage detected