HF Interface Wrapper 0.1.0-dev
Embedded C++ hardware abstraction layer
Loading...
Searching...
No Matches
EspPwm Class Reference

ESP32 PWM implementation using LEDC peripheral with comprehensive ESP32 variant support. More...

#include <EspPwm.h>

Inheritance diagram for EspPwm:
[legend]
Collaboration diagram for EspPwm:
[legend]

Classes

struct  ChannelState
 Internal channel state with per-channel callback support. More...
 
struct  ComplementaryPair
 Complementary output pair configuration. More...
 
struct  TimerState
 Internal timer state. More...
 
struct  ValidationContext
 Simple validation context for frequency/resolution validation. More...
 
struct  ValidationResult
 Comprehensive validation result with detailed information. More...
 

Public Member Functions

 EspPwm (const hf_pwm_unit_config_t &config=hf_pwm_unit_config_t{}) noexcept
 Constructor for ESP32C6 PWM controller.
 
virtual ~EspPwm () noexcept override
 Destructor - ensures clean shutdown.
 
 EspPwm (const EspPwm &)=delete
 
EspPwmoperator= (const EspPwm &)=delete
 
 EspPwm (EspPwm &&)=delete
 
EspPwmoperator= (EspPwm &&)=delete
 
hf_pwm_err_t Initialize () noexcept override
 Initialize the LEDC peripheral and PWM subsystem.
 
hf_pwm_err_t Deinitialize () noexcept override
 Deinitialize the LEDC peripheral and release all resources.
 
hf_pwm_err_t SetMode (hf_pwm_mode_t mode) noexcept
 Set PWM operating mode.
 
hf_pwm_mode_t GetMode () const noexcept
 Get current PWM operating mode.
 
hf_pwm_err_t ConfigureChannel (hf_channel_id_t channel_id, const hf_pwm_channel_config_t &config) noexcept
 Configure a PWM channel with comprehensive LEDC feature support.
 
hf_pwm_err_t DeconfigureChannel (hf_channel_id_t channel_id) noexcept
 Deconfigure a channel and release all associated resources.
 
hf_pwm_err_t EnableChannel (hf_channel_id_t channel_id) noexcept override
 Enable a configured PWM channel to start signal generation.
 
hf_pwm_err_t DisableChannel (hf_channel_id_t channel_id) noexcept override
 Disable a PWM channel and stop signal generation.
 
bool IsChannelEnabled (hf_channel_id_t channel_id) const noexcept override
 Check if a PWM channel is currently enabled.
 
hf_pwm_err_t SetDutyCycle (hf_channel_id_t channel_id, float duty_cycle) noexcept override
 Set PWM duty cycle as a percentage (0.0 to 1.0)
 
hf_pwm_err_t SetDutyCycleRaw (hf_channel_id_t channel_id, hf_u32_t raw_value) noexcept override
 Set PWM duty cycle using raw timer counts.
 
hf_pwm_err_t SetFrequency (hf_channel_id_t channel_id, hf_frequency_hz_t frequency_hz) noexcept override
 Set PWM frequency with automatic timer management.
 
hf_pwm_err_t SetPhaseShift (hf_channel_id_t channel_id, float phase_shift_degrees) noexcept override
 Set PWM phase shift (ESP32 LEDC limitation: not supported)
 
hf_pwm_err_t SetFrequencyWithResolution (hf_channel_id_t channel_id, hf_frequency_hz_t frequency_hz, hf_u8_t resolution_bits) noexcept
 Set frequency with explicit resolution choice (user-controlled)
 
hf_pwm_err_t SetFrequencyWithAutoFallback (hf_channel_id_t channel_id, hf_frequency_hz_t frequency_hz, hf_u8_t preferred_resolution) noexcept
 Set frequency with automatic fallback to alternative resolutions.
 
hf_pwm_err_t SetResolution (hf_channel_id_t channel_id, hf_u8_t resolution_bits) noexcept
 Set PWM resolution for a channel.
 
hf_u8_t GetResolution (hf_channel_id_t channel_id) const noexcept
 Get current PWM resolution for a channel.
 
hf_pwm_err_t SetFrequencyAndResolution (hf_channel_id_t channel_id, hf_frequency_hz_t frequency_hz, hf_u8_t resolution_bits) noexcept
 Set frequency and resolution together (atomic operation)
 
hf_pwm_err_t EnableAutoFallback () noexcept
 Enable automatic fallback to alternative resolutions.
 
hf_pwm_err_t DisableAutoFallback () noexcept
 Disable automatic fallback to alternative resolutions.
 
bool IsAutoFallbackEnabled () const noexcept
 Check if auto-fallback mode is enabled.
 
hf_pwm_err_t StartAll () noexcept override
 Start all configured PWM channels simultaneously.
 
hf_pwm_err_t StopAll () noexcept override
 Stop all enabled PWM channels simultaneously.
 
hf_pwm_err_t UpdateAll () noexcept override
 Update all enabled PWM channels with their current settings.
 
hf_pwm_err_t SetComplementaryOutput (hf_channel_id_t primary_channel, hf_channel_id_t complementary_channel, hf_u32_t deadtime_ns) noexcept override
 Configure complementary PWM output pair with deadtime.
 
float GetDutyCycle (hf_channel_id_t channel_id) const noexcept override
 Get current duty cycle as a percentage.
 
hf_frequency_hz_t GetFrequency (hf_channel_id_t channel_id) const noexcept override
 Get current PWM frequency in Hz.
 
hf_pwm_err_t GetChannelStatus (hf_channel_id_t channel_id, hf_pwm_channel_status_t &status) const noexcept
 Get comprehensive channel status and configuration.
 
hf_pwm_err_t GetCapabilities (hf_pwm_capabilities_t &capabilities) const noexcept
 Get ESP32 variant-specific PWM capabilities.
 
hf_pwm_err_t GetLastError (hf_channel_id_t channel_id) const noexcept
 Get the last error code for a specific channel.
 
hf_pwm_err_t SetChannelFadeCallback (hf_channel_id_t channel_id, void(*callback)(hf_channel_id_t)) noexcept
 Set per-channel callback for PWM fade completion events.
 
hf_pwm_err_t SetHardwareFade (hf_channel_id_t channel_id, float target_duty_cycle, hf_u32_t fade_time_ms) noexcept
 Set hardware fade for smooth duty cycle transitions.
 
hf_pwm_err_t StopHardwareFade (hf_channel_id_t channel_id) noexcept
 Stop hardware fade for a channel.
 
bool IsFadeActive (hf_channel_id_t channel_id) const noexcept
 Check if hardware fade is active on a channel.
 
hf_pwm_err_t SetIdleLevel (hf_channel_id_t channel_id, hf_u8_t idle_level) noexcept
 Set idle output level for a channel.
 
int8_t GetTimerAssignment (hf_channel_id_t channel_id) const noexcept
 Get current timer assignment for a channel.
 
hf_pwm_err_t ForceTimerAssignment (hf_channel_id_t channel_id, hf_u8_t timer_id) noexcept
 Force a specific timer for a channel (advanced usage)
 
hf_pwm_err_t SetEvictionPolicy (hf_pwm_eviction_policy_t policy) noexcept
 Set timer eviction policy for resource management.
 
hf_pwm_eviction_policy_t GetEvictionPolicy () const noexcept
 Get current eviction policy.
 
hf_pwm_err_t SetEvictionCallback (hf_pwm_eviction_callback_t callback, void *user_data=nullptr) noexcept
 Set eviction consent callback for user-controlled eviction.
 
hf_pwm_err_t SetChannelPriority (hf_channel_id_t channel_id, hf_pwm_channel_priority_t priority) noexcept
 Set channel priority for eviction decisions.
 
hf_pwm_channel_priority_t GetChannelPriority (hf_channel_id_t channel_id) const noexcept
 Get channel priority.
 
hf_pwm_err_t SetChannelCritical (hf_channel_id_t channel_id, bool is_critical) noexcept
 Mark channel as critical (never evict)
 
bool IsChannelCritical (hf_channel_id_t channel_id) const noexcept
 Check if channel is marked as critical.
 
hf_pwm_err_t GetStatistics (hf_pwm_statistics_t &statistics) const noexcept override
 Get PWM statistics.
 
hf_pwm_err_t GetDiagnostics (hf_pwm_diagnostics_t &diagnostics) const noexcept override
 Get PWM diagnostics.
 
- Public Member Functions inherited from BasePwm
virtual ~BasePwm () noexcept=default
 
bool IsInitialized () const noexcept
 Check if PWM system is initialized.
 
bool EnsureInitialized () noexcept
 Ensure PWM is initialized (lazy initialization pattern)
 
bool EnsureDeinitialized () noexcept
 Ensure PWM is deinitialized (lazy deinitialization pattern)
 
virtual hf_pwm_err_t ResetStatistics () noexcept
 Reset PWM operation statistics.
 
virtual hf_pwm_err_t ResetDiagnostics () noexcept
 Reset PWM diagnostic information.
 

Static Public Attributes

static constexpr hf_u8_t MAX_CHANNELS = HF_PWM_MAX_CHANNELS
 Maximum PWM channels.
 
static constexpr hf_u8_t MAX_TIMERS = HF_PWM_MAX_TIMERS
 Maximum timer groups.
 
static constexpr hf_u8_t MAX_RESOLUTION = HF_PWM_MAX_RESOLUTION
 Maximum resolution bits.
 
static constexpr hf_u32_t MIN_FREQUENCY = HF_PWM_MIN_FREQUENCY
 Minimum frequency (Hz)
 
static constexpr hf_u32_t MAX_FREQUENCY = HF_PWM_MAX_FREQUENCY
 Maximum frequency (Hz)
 

Private Member Functions

bool IsValidChannelId (hf_channel_id_t channel_id) const noexcept
 Validate channel ID.
 
hf_i8_t FindOrAllocateTimer (hf_u32_t frequency_hz, hf_u8_t resolution_bits, hf_pwm_clock_source_t clock_source) noexcept
 Unified timer allocation with comprehensive strategy.
 
void ReleaseTimerIfUnused (hf_u8_t timer_id) noexcept
 Release a timer if no longer needed with hardware cleanup.
 
hf_pwm_err_t ConfigurePlatformTimer (hf_u8_t timer_id, hf_u32_t frequency_hz, hf_u8_t resolution_bits, hf_pwm_clock_source_t clock_source) noexcept
 Configure platform timer with LEDC peripheral integration.
 
hf_pwm_err_t ConfigurePlatformChannel (hf_channel_id_t channel_id, const hf_pwm_channel_config_t &config, hf_u8_t timer_id) noexcept
 Configure platform channel.
 
hf_pwm_err_t UpdatePlatformDuty (hf_channel_id_t channel_id, hf_u32_t raw_duty_value) noexcept
 Update platform duty cycle.
 
void SetChannelError (hf_channel_id_t channel_id, hf_pwm_err_t error) noexcept
 Set error for a channel.
 
void HandleFadeComplete (hf_channel_id_t channel_id) noexcept
 Handle fade complete interrupt.
 
hf_pwm_err_t RegisterLedcFadeCallback (hf_channel_id_t channel_id) noexcept
 Register LEDC fade callback using ESP-IDF API.
 
hf_pwm_err_t UnregisterLedcFadeCallback (hf_channel_id_t channel_id) noexcept
 Unregister LEDC fade callback.
 
hf_pwm_err_t InitializeFadeFunctionality () noexcept
 Initialize LEDC fade functionality.
 
hf_pwm_err_t InitializeTimers () noexcept
 Initialize PWM timers.
 
hf_pwm_err_t InitializeChannels () noexcept
 Initialize PWM channels.
 
hf_pwm_err_t EnableFade () noexcept
 Enable fade functionality.
 
hf_u32_t CalculateClockDivider (hf_u32_t frequency_hz, hf_u8_t resolution_bits) const noexcept
 Calculate optimal clock divider for frequency.
 
ValidationResult ValidateFrequencyResolutionComplete (const ValidationContext &context) const noexcept
 Unified comprehensive validation for frequency/resolution combinations.
 
hf_u32_t GetSourceClockFrequency (hf_pwm_clock_source_t clock_source) const noexcept
 Get source clock frequency for a given clock source.
 
hf_u8_t CalculateMaxResolution (hf_u32_t frequency_hz, hf_pwm_clock_source_t clock_source=hf_pwm_clock_source_t::HF_PWM_CLK_SRC_APB) const noexcept
 Calculate maximum achievable resolution for a given frequency.
 
hf_u32_t CalculateMaxFrequency (hf_u8_t resolution_bits, hf_pwm_clock_source_t clock_source=hf_pwm_clock_source_t::HF_PWM_CLK_SRC_APB) const noexcept
 Calculate maximum achievable frequency for a given resolution.
 
bool ValidateDutyCycleRange (hf_u32_t raw_duty, hf_u8_t resolution_bits) const noexcept
 Enhanced duty cycle validation with overflow protection.
 
bool IsClockSourceCompatible (hf_pwm_clock_source_t timer_clock, hf_pwm_clock_source_t requested_clock) const noexcept
 Check if two clock sources are compatible for timer sharing.
 
hf_u8_t FindBestAlternativeResolutionDynamic (hf_u32_t frequency_hz, hf_u8_t preferred_resolution, hf_pwm_clock_source_t clock_source=hf_pwm_clock_source_t::HF_PWM_CLK_SRC_APB) const noexcept
 Find best alternative resolution using dynamic calculation.
 
void NotifyTimerReconfiguration (hf_u8_t timer_id, hf_u32_t new_frequency, hf_u8_t resolution_bits) noexcept
 Notify channels that their timer has been reconfigured.
 
std::string GetTimerUsageInfo (hf_u8_t timer_id) const noexcept
 Get timer usage information for debugging.
 
hf_u8_t PerformTimerHealthCheck () noexcept
 Perform comprehensive timer health check and cleanup.
 
hf_i8_t AttemptSafeEviction (hf_u32_t frequency_hz, hf_u8_t resolution_bits) noexcept
 Attempt safe timer eviction based on user policy.
 
hf_i8_t AttemptEvictionWithConsent (hf_u32_t frequency_hz, hf_u8_t resolution_bits) noexcept
 Attempt eviction with user consent callback.
 
hf_i8_t AttemptEvictionNonCritical (hf_u32_t frequency_hz, hf_u8_t resolution_bits) noexcept
 Attempt eviction of non-critical channels only.
 
hf_i8_t AttemptForceEviction (hf_u32_t frequency_hz, hf_u8_t resolution_bits) noexcept
 Attempt aggressive eviction (original behavior)
 

Static Private Member Functions

static void IRAM_ATTR InterruptHandler (hf_channel_id_t channel_id, void *user_data) noexcept
 Platform-specific interrupt handler.
 
static bool IRAM_ATTR LedcFadeEndCallback (const ledc_cb_param_t *param, void *user_arg) noexcept
 Static ESP-IDF LEDC fade callback handler (C-compatible)
 

Private Attributes

PlatformMutex mutex_
 Thread safety mutex.
 
std::atomic< bool > initialized_
 Initialization state (atomic for lazy init)
 
hf_u32_t base_clock_hz_
 Base clock frequency.
 
hf_pwm_clock_source_t clock_source_
 Current clock source.
 
std::array< ChannelState, MAX_CHANNELSchannels_
 Channel states.
 
std::array< TimerState, MAX_TIMERStimers_
 Timer states.
 
std::array< ComplementaryPair, MAX_CHANNELS/2 > complementary_pairs_
 Complementary pairs.
 
hf_pwm_err_t last_global_error_
 Last global error.
 
bool fade_functionality_installed_
 LEDC fade functionality installed.
 
hf_pwm_unit_config_t unit_config_
 Unit configuration.
 
hf_pwm_mode_t current_mode_
 Current operating mode.
 
hf_pwm_statistics_t statistics_
 PWM statistics.
 
hf_pwm_diagnostics_t diagnostics_
 PWM diagnostics.
 
bool auto_fallback_enabled_
 Whether to automatically try alternative resolutions.
 
hf_pwm_eviction_policy_t eviction_policy_
 Timer eviction policy (default: STRICT_NO_EVICTION)
 
hf_pwm_eviction_callback_t eviction_callback_
 User callback for eviction consent.
 
void * eviction_callback_user_data_
 User data for eviction callback.
 

Additional Inherited Members

- Static Public Member Functions inherited from BasePwm
static constexpr hf_u32_t DutyCycleToRaw (float duty_cycle, hf_u8_t resolution_bits) noexcept
 Calculate raw duty value from percentage.
 
static constexpr float RawToDutyCycle (hf_u32_t raw_value, hf_u8_t resolution_bits) noexcept
 Calculate duty cycle percentage from raw value.
 
static constexpr bool IsValidDutyCycle (float duty_cycle) noexcept
 Validate duty cycle range.
 
static constexpr bool IsValidFrequency (hf_u32_t frequency_hz, hf_u32_t min_freq_hz, hf_u32_t max_freq_hz) noexcept
 Validate frequency range.
 
static constexpr bool IsValidRawDuty (hf_u32_t raw_value, hf_u8_t resolution_bits) noexcept
 Validate raw duty value against resolution.
 
static constexpr float CalculateFrequencyAccuracy (hf_u32_t target_freq, hf_u32_t actual_freq) noexcept
 Calculate frequency accuracy percentage.
 
static constexpr float ClampDutyCycle (float duty_cycle) noexcept
 Clamp duty cycle to valid range.
 
- Protected Member Functions inherited from BasePwm
 BasePwm () noexcept
 
 BasePwm (const BasePwm &)=delete
 
BasePwmoperator= (const BasePwm &)=delete
 
 BasePwm (BasePwm &&)=delete
 
BasePwmoperator= (BasePwm &&)=delete
 
- Protected Attributes inherited from BasePwm
bool initialized_
 Initialization state.
 
hf_pwm_statistics_t statistics_
 PWM operation statistics.
 
hf_pwm_diagnostics_t diagnostics_
 PWM diagnostic information.
 

Detailed Description

ESP32 PWM implementation using LEDC peripheral with comprehensive ESP32 variant support.

This class provides PWM generation using the ESP32 family's built-in LEDC (LED Controller) peripheral which offers high-resolution PWM with hardware fade support. The implementation automatically adapts to different ESP32 variants and their specific LEDC capabilities.

ESP32 Variant LEDC Capabilities:

ESP32 (Classic):

  • Channels: 16 channels (8 high-speed + 8 low-speed)
  • Timers: 8 timers (4 high-speed + 4 low-speed)
  • Clock Sources: APB_CLK (80MHz), REF_TICK (1MHz), RTC8M_CLK (LS only)
  • Resolution: Up to 20-bit at low frequencies, 14-bit at high frequencies
  • Special Features: Separate high-speed and low-speed modes

ESP32-S2/S3:

  • Channels: 8 channels (unified mode)
  • Timers: 4 timers (unified)
  • Clock Sources: APB_CLK (80MHz), REF_TICK (1MHz), XTAL_CLK (LS only)
  • Resolution: Up to 14-bit resolution
  • Special Features: Unified speed mode, improved power efficiency

ESP32-C3/C6/H2:

  • Channels: 6 channels (ESP32-C6), 6 channels (ESP32-C3), 4 channels (ESP32-H2)
  • Timers: 4 timers (C3/C6), 2 timers (H2)
  • Clock Sources: APB_CLK (80MHz), REF_TICK (1MHz), XTAL_CLK
  • Resolution: Up to 14-bit resolution
  • Special Features: Compact design, optimized for IoT applications

Clock Source Constraints:

CRITICAL: Different ESP32 variants have different clock source limitations:

  • ESP32 Classic: Each timer can use different clock sources independently
  • ESP32-S2/S3/C3/C6/H2: All timers typically share the same clock source
  • Frequency Limitations: Clock source determines maximum achievable frequency:
    • APB_CLK (80MHz): Max ~78kHz at 10-bit resolution
    • XTAL_CLK (40MHz): Max ~39kHz at 10-bit resolution
    • REF_TICK (1MHz): Max ~976Hz at 10-bit resolution

Timer Resource Management:

The LEDC peripheral uses a timer-channel architecture where:

  • Multiple channels can share the same timer (same frequency/resolution)
  • Each timer supports up to 8 channels (hardware limitation)
  • Timer allocation is automatic but can be controlled manually
  • Smart eviction policies protect critical channels

Key Design Features:

  • Variant-Aware: Automatically detects and adapts to ESP32 variant capabilities
  • Thread-Safe: Full PlatformMutex protection for concurrent access
  • Smart Timer Management: Automatic allocation with conflict resolution
  • Hardware Fade Support: Native LEDC fade functionality
  • Error Recovery: Comprehensive fault detection and recovery mechanisms
  • Motor Control Ready: Complementary outputs, deadtime, and synchronization
  • Resource Protection: Eviction policies prevent accidental channel disruption
  • Performance Optimized: Minimal overhead, efficient memory usage

Constructor & Destructor Documentation

◆ EspPwm() [1/3]

EspPwm::EspPwm ( const hf_pwm_unit_config_t & config = hf_pwm_unit_config_t{})
explicitnoexcept

Constructor for ESP32C6 PWM controller.

Parameters
configPWM unit configuration
Note
Uses lazy initialization - no hardware action until first operation

◆ ~EspPwm()

EspPwm::~EspPwm ( )
overridevirtualnoexcept

Destructor - ensures clean shutdown.

◆ EspPwm() [2/3]

EspPwm::EspPwm ( const EspPwm & )
delete

◆ EspPwm() [3/3]

EspPwm::EspPwm ( EspPwm && )
delete

Member Function Documentation

◆ AttemptEvictionNonCritical()

hf_i8_t EspPwm::AttemptEvictionNonCritical ( hf_u32_t frequency_hz,
hf_u8_t resolution_bits )
privatenoexcept

Attempt eviction of non-critical channels only.

Parameters
frequency_hzRequired frequency
resolution_bitsRequired resolution
Returns
Timer ID if successful, -1 if no non-critical timers available

◆ AttemptEvictionWithConsent()

hf_i8_t EspPwm::AttemptEvictionWithConsent ( hf_u32_t frequency_hz,
hf_u8_t resolution_bits )
privatenoexcept

Attempt eviction with user consent callback.

Parameters
frequency_hzRequired frequency
resolution_bitsRequired resolution
Returns
Timer ID if approved and successful, -1 if denied/failed

◆ AttemptForceEviction()

hf_i8_t EspPwm::AttemptForceEviction ( hf_u32_t frequency_hz,
hf_u8_t resolution_bits )
privatenoexcept

Attempt aggressive eviction (original behavior)

Parameters
frequency_hzRequired frequency
resolution_bitsRequired resolution
Returns
Timer ID if successful, -1 if failed
Note
Only used with FORCE_EVICTION policy - may disrupt critical channels!

◆ AttemptSafeEviction()

hf_i8_t EspPwm::AttemptSafeEviction ( hf_u32_t frequency_hz,
hf_u8_t resolution_bits )
privatenoexcept

Attempt safe timer eviction based on user policy.

Parameters
frequency_hzRequired frequency
resolution_bitsRequired resolution
Returns
Timer ID if eviction successful, -1 if denied/failed

◆ CalculateClockDivider()

hf_u32_t EspPwm::CalculateClockDivider ( hf_u32_t frequency_hz,
hf_u8_t resolution_bits ) const
privatenoexcept

Calculate optimal clock divider for frequency.

Parameters
frequency_hzTarget frequency
resolution_bitsPWM resolution
Returns
Clock divider value

◆ CalculateMaxFrequency()

hf_u32_t EspPwm::CalculateMaxFrequency ( hf_u8_t resolution_bits,
hf_pwm_clock_source_t clock_source = hf_pwm_clock_source_t::HF_PWM_CLK_SRC_APB ) const
privatenoexcept

Calculate maximum achievable frequency for a given resolution.

Parameters
resolution_bitsTarget resolution in bits
clock_sourceClock source to use (default: APB)
Returns
Maximum frequency in Hz, or 0 if resolution too high

◆ CalculateMaxResolution()

hf_u8_t EspPwm::CalculateMaxResolution ( hf_u32_t frequency_hz,
hf_pwm_clock_source_t clock_source = hf_pwm_clock_source_t::HF_PWM_CLK_SRC_APB ) const
privatenoexcept

Calculate maximum achievable resolution for a given frequency.

Parameters
frequency_hzTarget frequency in Hz
clock_sourceClock source to use (default: APB)
Returns
Maximum resolution in bits, or 0 if frequency too high

◆ ConfigureChannel()

hf_pwm_err_t EspPwm::ConfigureChannel ( hf_channel_id_t channel_id,
const hf_pwm_channel_config_t & config )
noexcept

Configure a PWM channel with comprehensive LEDC feature support.

Parameters
channel_idChannel identifier (0 to MAX_CHANNELS-1)
configComplete channel configuration including GPIO, frequency, resolution
Returns
PWM_SUCCESS on success, error code on failure

This method configures a PWM channel with full LEDC peripheral integration:

  • Timer Assignment: Automatic or manual timer allocation with conflict resolution
  • Frequency/Resolution Validation: Hardware constraint verification against clock source
  • GPIO Configuration: Pin matrix validation and hardware setup
  • Resource Management: Smart timer sharing and eviction policy enforcement
Note
The channel must be enabled separately using EnableChannel()
Warning
Invalid frequency/resolution combinations will be rejected with detailed error codes
See also
SetFrequencyWithResolution() for explicit frequency/resolution control
EnableChannel() to activate the configured channel

◆ ConfigurePlatformChannel()

hf_pwm_err_t EspPwm::ConfigurePlatformChannel ( hf_channel_id_t channel_id,
const hf_pwm_channel_config_t & config,
hf_u8_t timer_id )
privatenoexcept

Configure platform channel.

Parameters
channel_idChannel to configure
configChannel configuration
timer_idAssigned timer
Returns
PWM_SUCCESS on success, error code on failure

◆ ConfigurePlatformTimer()

hf_pwm_err_t EspPwm::ConfigurePlatformTimer ( hf_u8_t timer_id,
hf_u32_t frequency_hz,
hf_u8_t resolution_bits,
hf_pwm_clock_source_t clock_source )
privatenoexcept

Configure platform timer with LEDC peripheral integration.

Parameters
timer_idTimer identifier to configure (0 to MAX_TIMERS-1)
frequency_hzTimer frequency in Hz
resolution_bitsTimer resolution in bits (4-14)
clock_sourceClock source for timer configuration
Returns
PWM_SUCCESS on success, error code on failure

Configures an LEDC timer with specified parameters:

  • Maps clock source enum to ESP-IDF LEDC clock configuration
  • Validates frequency/resolution combination against hardware constraints
  • Updates internal timer state for resource tracking
  • Performs actual LEDC timer hardware configuration
Note
Timer configuration affects all channels assigned to this timer
Warning
Invalid combinations will cause hardware configuration failure

◆ DeconfigureChannel()

hf_pwm_err_t EspPwm::DeconfigureChannel ( hf_channel_id_t channel_id)
noexcept

Deconfigure a channel and release all associated resources.

Parameters
channel_idChannel ID to deconfigure
Returns
PWM_SUCCESS on success, error code on failure
Note
This method:
  1. Stops the channel if it's enabled
  2. Releases timer resources if no other channels are using it
  3. Resets GPIO pin to default state
  4. Completely resets channel state to unconfigured

◆ Deinitialize()

hf_pwm_err_t EspPwm::Deinitialize ( )
overridevirtualnoexcept

Deinitialize the LEDC peripheral and release all resources.

Returns
PWM_SUCCESS on success, error code on failure

Performs comprehensive cleanup and resource release:

  • Stops all active PWM channels with proper idle level setting
  • Releases and resets all LEDC timers with hardware cleanup
  • Resets all GPIO pins to default state
  • Uninstalls fade functionality to prevent conflicts
  • Clears all internal state and statistics
Note
Safe to call multiple times or on already deinitialized instances
Warning
All PWM outputs will stop and GPIOs will be reset to default state
See also
Initialize() for PWM subsystem initialization

() - ESP32-specific cleanup with LEDC peripheral reset

Implements BasePwm.

◆ DisableAutoFallback()

hf_pwm_err_t EspPwm::DisableAutoFallback ( )
noexcept

Disable automatic fallback to alternative resolutions.

Returns
PWM_SUCCESS on success, error code on failure
Note
When disabled, SetFrequency() will fail validation for problematic combinations

◆ DisableChannel()

hf_pwm_err_t EspPwm::DisableChannel ( hf_channel_id_t channel_id)
overridevirtualnoexcept

Disable a PWM channel and stop signal generation.

Parameters
channel_idChannel identifier to disable
Returns
PWM_SUCCESS on success, error code on failure

Stops PWM signal generation and sets output to configured idle level. Timer resources are automatically managed and released if unused.

Note
GPIO pin will be set to the configured idle level (0 or 1)

Implements BasePwm.

◆ EnableAutoFallback()

hf_pwm_err_t EspPwm::EnableAutoFallback ( )
noexcept

Enable automatic fallback to alternative resolutions.

Returns
PWM_SUCCESS on success, error code on failure
Note
When enabled, SetFrequency() will automatically try alternative resolutions

◆ EnableChannel()

hf_pwm_err_t EspPwm::EnableChannel ( hf_channel_id_t channel_id)
overridevirtualnoexcept

Enable a configured PWM channel to start signal generation.

Parameters
channel_idChannel identifier to enable
Returns
PWM_SUCCESS on success, error code on failure

Activates PWM signal generation on the specified channel using the LEDC peripheral. The channel must be previously configured with ConfigureChannel().

Note
Uses fade-compatible or basic LEDC functions based on current mode
Warning
Channel must be configured before enabling

Implements BasePwm.

◆ EnableFade()

hf_pwm_err_t EspPwm::EnableFade ( )
privatenoexcept

Enable fade functionality.

Returns
PWM_SUCCESS on success, error code on failure

◆ FindBestAlternativeResolutionDynamic()

hf_u8_t EspPwm::FindBestAlternativeResolutionDynamic ( hf_u32_t frequency_hz,
hf_u8_t preferred_resolution,
hf_pwm_clock_source_t clock_source = hf_pwm_clock_source_t::HF_PWM_CLK_SRC_APB ) const
privatenoexcept

Find best alternative resolution using dynamic calculation.

Parameters
frequency_hzTarget frequency in Hz
preferred_resolutionPreferred resolution in bits
clock_sourceClock source for calculation
Returns
Best alternative resolution, or preferred if no better option

◆ FindOrAllocateTimer()

hf_i8_t EspPwm::FindOrAllocateTimer ( hf_u32_t frequency_hz,
hf_u8_t resolution_bits,
hf_pwm_clock_source_t clock_source )
privatenoexcept

Unified timer allocation with comprehensive strategy.

Parameters
frequency_hzRequired frequency in Hz
resolution_bitsRequired resolution in bits (4-14)
clock_sourcePreferred clock source for timer configuration
Returns
Timer ID (0 to MAX_TIMERS-1), or -1 if no timer available

Implements a multi-phase allocation strategy:

  1. Optimal Reuse: Find exact frequency/resolution match
  2. Compatible Reuse: Find compatible frequency within tolerance
  3. New Allocation: Allocate unused timer with validation
  4. Health Check: Clean up orphaned timers and retry
  5. Safe Eviction: Apply user-defined eviction policies
Note
Combines all allocation strategies for maximum efficiency
Warning
Returns -1 if all strategies fail (no available timers)

◆ ForceTimerAssignment()

hf_pwm_err_t EspPwm::ForceTimerAssignment ( hf_channel_id_t channel_id,
hf_u8_t timer_id )
noexcept

Force a specific timer for a channel (advanced usage)

Parameters
channel_idChannel identifier
timer_idTimer identifier (0-3)
Returns
PWM_SUCCESS on success, error code on failure
Note
Use with caution - automatic timer allocation is usually better

◆ GetCapabilities()

hf_pwm_err_t EspPwm::GetCapabilities ( hf_pwm_capabilities_t & capabilities) const
noexcept

Get ESP32 variant-specific PWM capabilities.

Parameters
capabilitiesReference to capabilities structure to populate
Returns
PWM_SUCCESS on success, error code on failure

Returns hardware-specific limits including channel count, timer count, maximum resolution, frequency ranges, and supported features for the current ESP32 variant.

Note
Capabilities are determined at compile-time based on target ESP32 variant

◆ GetChannelPriority()

hf_pwm_channel_priority_t EspPwm::GetChannelPriority ( hf_channel_id_t channel_id) const
noexcept

Get channel priority.

Parameters
channel_idChannel identifier
Returns
Channel priority, or PRIORITY_NORMAL if channel not configured

◆ GetChannelStatus()

hf_pwm_err_t EspPwm::GetChannelStatus ( hf_channel_id_t channel_id,
hf_pwm_channel_status_t & status ) const
noexcept

Get comprehensive channel status and configuration.

Parameters
channel_idChannel identifier to query
statusReference to status structure to populate
Returns
PWM_SUCCESS on success, error code on failure

Provides complete channel state including enabled status, current settings, resolution, raw duty value, and error state for diagnostic purposes.

Note
Status structure is zeroed on error or for unconfigured channels

◆ GetDiagnostics()

hf_pwm_err_t EspPwm::GetDiagnostics ( hf_pwm_diagnostics_t & diagnostics) const
overridevirtualnoexcept

Get PWM diagnostics.

Parameters
diagnosticsDiagnostics structure to fill
Returns
PWM_SUCCESS on success, error code on failure

Reimplemented from BasePwm.

◆ GetDutyCycle()

float EspPwm::GetDutyCycle ( hf_channel_id_t channel_id) const
overridevirtualnoexcept

Get current duty cycle as a percentage.

Parameters
channel_idChannel identifier to query
Returns
Current duty cycle (0.0 to 1.0), or 0.0 if channel not configured

Reads the current LEDC timer compare value and converts to percentage based on the channel's current resolution setting.

Note
Returns 0.0 for unconfigured channels or on error

Implements BasePwm.

◆ GetEvictionPolicy()

hf_pwm_eviction_policy_t EspPwm::GetEvictionPolicy ( ) const
noexcept

Get current eviction policy.

Returns
Current eviction policy

◆ GetFrequency()

hf_frequency_hz_t EspPwm::GetFrequency ( hf_channel_id_t channel_id) const
overridevirtualnoexcept

Get current PWM frequency in Hz.

Parameters
channel_idChannel identifier to query
Returns
Current frequency in Hz, or 0 if channel not configured

Returns the frequency of the timer assigned to this channel. Multiple channels sharing the same timer will return the same frequency.

Note
Returns 0 for unconfigured channels or on error

Implements BasePwm.

◆ GetLastError()

hf_pwm_err_t EspPwm::GetLastError ( hf_channel_id_t channel_id) const
noexcept

Get the last error code for a specific channel.

Parameters
channel_idChannel identifier to query
Returns
Last error code for this channel, or PWM_ERR_INVALID_CHANNEL for invalid ID

Each channel maintains its own error state for detailed error tracking. Useful for debugging channel-specific issues in multi-channel applications.

Note
Error state is cleared on successful operations

◆ GetMode()

hf_pwm_mode_t EspPwm::GetMode ( ) const
noexcept

Get current PWM operating mode.

Returns
Current operating mode

◆ GetResolution()

hf_u8_t EspPwm::GetResolution ( hf_channel_id_t channel_id) const
noexcept

Get current PWM resolution for a channel.

Parameters
channel_idChannel identifier
Returns
Current resolution in bits, or 0 on error

◆ GetSourceClockFrequency()

hf_u32_t EspPwm::GetSourceClockFrequency ( hf_pwm_clock_source_t clock_source) const
privatenoexcept

Get source clock frequency for a given clock source.

Parameters
clock_sourceClock source to query
Returns
Clock frequency in Hz

◆ GetStatistics()

hf_pwm_err_t EspPwm::GetStatistics ( hf_pwm_statistics_t & statistics) const
overridevirtualnoexcept

Get PWM statistics.

Parameters
statisticsStatistics structure to fill
Returns
PWM_SUCCESS on success, error code on failure

Reimplemented from BasePwm.

◆ GetTimerAssignment()

hf_i8_t EspPwm::GetTimerAssignment ( hf_channel_id_t channel_id) const
noexcept

Get current timer assignment for a channel.

Parameters
channel_idChannel identifier
Returns
Timer number (0-3), or -1 if channel not configured

◆ GetTimerUsageInfo()

std::string EspPwm::GetTimerUsageInfo ( hf_u8_t timer_id) const
privatenoexcept

Get timer usage information for debugging.

Parameters
timer_idTimer to get info for
Returns
String with timer usage information

◆ HandleFadeComplete()

void EspPwm::HandleFadeComplete ( hf_channel_id_t channel_id)
privatenoexcept

Handle fade complete interrupt.

Parameters
channel_idChannel that completed fade

◆ Initialize()

hf_pwm_err_t EspPwm::Initialize ( )
overridevirtualnoexcept

Initialize the LEDC peripheral and PWM subsystem.

Returns
PWM_SUCCESS on success, error code on failure

Performs comprehensive LEDC peripheral initialization:

  • Initializes timer and channel state arrays
  • Sets up fade functionality if enabled in configuration
  • Validates ESP32 variant capabilities
  • Prepares resource management systems
Note
This method is called automatically by EnsureInitialized() (lazy initialization)
Warning
Multiple calls return PWM_ERR_ALREADY_INITIALIZED (safe to call repeatedly)
See also
Deinitialize() for cleanup and resource release

() - ESP32-specific implementation using LEDC peripheral

Implements BasePwm.

◆ InitializeChannels()

hf_pwm_err_t EspPwm::InitializeChannels ( )
privatenoexcept

Initialize PWM channels.

Returns
PWM_SUCCESS on success, error code on failure

◆ InitializeFadeFunctionality()

hf_pwm_err_t EspPwm::InitializeFadeFunctionality ( )
privatenoexcept

Initialize LEDC fade functionality.

Returns
PWM_SUCCESS on success, error code on failure

◆ InitializeTimers()

hf_pwm_err_t EspPwm::InitializeTimers ( )
privatenoexcept

Initialize PWM timers.

Returns
PWM_SUCCESS on success, error code on failure

◆ InterruptHandler()

void IRAM_ATTR EspPwm::InterruptHandler ( hf_channel_id_t channel_id,
void * user_data )
staticprivatenoexcept

Platform-specific interrupt handler.

Parameters
channel_idChannel that generated interrupt
user_dataUser data passed to interrupt handler (EspPwm instance)

◆ IsAutoFallbackEnabled()

bool EspPwm::IsAutoFallbackEnabled ( ) const
noexcept

Check if auto-fallback mode is enabled.

Returns
true if auto-fallback is enabled, false otherwise

◆ IsChannelCritical()

bool EspPwm::IsChannelCritical ( hf_channel_id_t channel_id) const
noexcept

Check if channel is marked as critical.

Parameters
channel_idChannel identifier
Returns
True if channel is critical, false otherwise

◆ IsChannelEnabled()

bool EspPwm::IsChannelEnabled ( hf_channel_id_t channel_id) const
overridevirtualnoexcept

Check if a PWM channel is currently enabled.

Parameters
channel_idChannel identifier to check
Returns
true if channel is enabled and generating PWM signals, false otherwise
Note
Returns false for unconfigured channels or channels that failed to enable

Implements BasePwm.

◆ IsClockSourceCompatible()

bool EspPwm::IsClockSourceCompatible ( hf_pwm_clock_source_t timer_clock,
hf_pwm_clock_source_t requested_clock ) const
privatenoexcept

Check if two clock sources are compatible for timer sharing.

Parameters
timer_clockCurrent timer's clock source
requested_clockRequested clock source
Returns
true if compatible (can share timer), false otherwise
Note
AUTO clock is compatible with any specific clock

◆ IsFadeActive()

bool EspPwm::IsFadeActive ( hf_channel_id_t channel_id) const
noexcept

Check if hardware fade is active on a channel.

Parameters
channel_idChannel identifier
Returns
true if fade is active, false otherwise

◆ IsValidChannelId()

bool EspPwm::IsValidChannelId ( hf_channel_id_t channel_id) const
privatenoexcept

Validate channel ID.

Parameters
channel_idChannel to validate
Returns
true if valid, false otherwise

◆ LedcFadeEndCallback()

bool IRAM_ATTR EspPwm::LedcFadeEndCallback ( const ledc_cb_param_t * param,
void * user_arg )
staticprivatenoexcept

Static ESP-IDF LEDC fade callback handler (C-compatible)

Parameters
paramESP-IDF callback parameter structure
user_argUser argument (EspPwm instance pointer)
Returns
true if high priority task was woken up, false otherwise

◆ NotifyTimerReconfiguration()

void EspPwm::NotifyTimerReconfiguration ( hf_u8_t timer_id,
hf_u32_t new_frequency,
hf_u8_t resolution_bits )
privatenoexcept

Notify channels that their timer has been reconfigured.

Parameters
timer_idTimer that was reconfigured
new_frequencyNew frequency
resolution_bitsNew resolution in bits

◆ operator=() [1/2]

EspPwm & EspPwm::operator= ( const EspPwm & )
delete

◆ operator=() [2/2]

EspPwm & EspPwm::operator= ( EspPwm && )
delete

◆ PerformTimerHealthCheck()

hf_u8_t EspPwm::PerformTimerHealthCheck ( )
privatenoexcept

Perform comprehensive timer health check and cleanup.

Returns
Number of timers cleaned up

◆ RegisterLedcFadeCallback()

hf_pwm_err_t EspPwm::RegisterLedcFadeCallback ( hf_channel_id_t channel_id)
privatenoexcept

Register LEDC fade callback using ESP-IDF API.

Parameters
channel_idChannel to register callback for
Returns
PWM_SUCCESS on success, error code on failure

◆ ReleaseTimerIfUnused()

void EspPwm::ReleaseTimerIfUnused ( hf_u8_t timer_id)
privatenoexcept

Release a timer if no longer needed with hardware cleanup.

Parameters
timer_idTimer to potentially release

◆ SetChannelCritical()

hf_pwm_err_t EspPwm::SetChannelCritical ( hf_channel_id_t channel_id,
bool is_critical )
noexcept

Mark channel as critical (never evict)

Parameters
channel_idChannel identifier
is_criticalTrue to protect from eviction, false to allow
Returns
PWM_SUCCESS on success, error code on failure

◆ SetChannelError()

void EspPwm::SetChannelError ( hf_channel_id_t channel_id,
hf_pwm_err_t error )
privatenoexcept

Set error for a channel.

Parameters
channel_idChannel identifier
errorError to set

◆ SetChannelFadeCallback()

hf_pwm_err_t EspPwm::SetChannelFadeCallback ( hf_channel_id_t channel_id,
void(*)(hf_channel_id_t) callback )
noexcept

Set per-channel callback for PWM fade completion events.

Parameters
channel_idChannel identifier to set callback for
callbackFunction to call on fade completion (or nullptr to disable)
Returns
PWM_SUCCESS on success, error code on failure

Registers a per-channel callback function that is triggered when a hardware fade operation completes on the specified channel. This uses the native ESP32-C6 LEDC fade completion interrupt mechanism.

Fade Completion Detection:

  • LEDC Hardware Interrupt: Native ESP32-C6 fade completion interrupt
  • Per-Channel Granularity: Each channel can have its own fade callback
  • Automatic Registration: Uses ledc_cb_register() for proper ESP-IDF integration
Note
This callback is only triggered for hardware fade operations (SetHardwareFade())
Warning
Callback functions should be ISR-safe and execute quickly (< 10μs recommended)
Do not call blocking functions or start new fade operations in the callback

Example Usage:

void my_fade_callback(hf_channel_id_t channel) {
// ISR-safe operations only
fade_complete_flags |= (1 << channel); // Set completion flag
// Signal task, update state, etc.
}
pwm.SetChannelFadeCallback(0, my_fade_callback);
pwm.SetHardwareFade(0, 0.8f, 1000); // Fade will trigger callback when complete
hf_u32_t hf_channel_id_t
Platform-agnostic channel identifier type.
Definition HardwareTypes.h:163
See also
SetHardwareFade() for hardware fade operations

◆ SetChannelPriority()

hf_pwm_err_t EspPwm::SetChannelPriority ( hf_channel_id_t channel_id,
hf_pwm_channel_priority_t priority )
noexcept

Set channel priority for eviction decisions.

Parameters
channel_idChannel identifier
priorityPriority level
Returns
PWM_SUCCESS on success, error code on failure

◆ SetComplementaryOutput()

hf_pwm_err_t EspPwm::SetComplementaryOutput ( hf_channel_id_t primary_channel,
hf_channel_id_t complementary_channel,
hf_u32_t deadtime_ns )
overridevirtualnoexcept

Configure complementary PWM output pair with deadtime.

Parameters
primary_channelPrimary channel identifier
complementary_channelComplementary channel identifier
deadtime_nsDeadtime between transitions in nanoseconds
Returns
PWM_SUCCESS on success, error code on failure

Creates a complementary PWM pair where outputs are never high simultaneously. Deadtime prevents shoot-through in power electronics applications.

Note
Both channels must be configured and use the same timer
Warning
Complementary operation is implemented in software, not hardware
See also
ConfigureChannel() to set up both channels before pairing

() - Software-based complementary PWM for motor control

Implements BasePwm.

◆ SetDutyCycle()

hf_pwm_err_t EspPwm::SetDutyCycle ( hf_channel_id_t channel_id,
float duty_cycle )
overridevirtualnoexcept

Set PWM duty cycle as a percentage (0.0 to 1.0)

Parameters
channel_idChannel identifier to update
duty_cycleDuty cycle as percentage (0.0 = 0%, 1.0 = 100%)
Returns
PWM_SUCCESS on success, error code on failure

Converts percentage to raw value based on channel's current resolution and updates the LEDC peripheral. Supports both fade and basic modes.

Note
Duty cycle is automatically clamped to valid range [0.0, 1.0]
Warning
Channel must be configured and enabled for immediate effect

Implements BasePwm.

◆ SetDutyCycleRaw()

hf_pwm_err_t EspPwm::SetDutyCycleRaw ( hf_channel_id_t channel_id,
hf_u32_t raw_value )
overridevirtualnoexcept

Set PWM duty cycle using raw timer counts.

Parameters
channel_idChannel identifier to update
raw_valueRaw duty cycle value (0 to (2^resolution - 1))
Returns
PWM_SUCCESS on success, error code on failure

Directly sets LEDC timer compare value for maximum precision. Value is validated against current channel resolution.

Note
Raw value is clamped to maximum for current resolution
Warning
Use GetResolution() to determine valid raw value range

Implements BasePwm.

◆ SetEvictionCallback()

hf_pwm_err_t EspPwm::SetEvictionCallback ( hf_pwm_eviction_callback_t callback,
void * user_data = nullptr )
noexcept

Set eviction consent callback for user-controlled eviction.

Parameters
callbackCallback function to approve/deny eviction requests
user_dataUser data passed to callback
Returns
PWM_SUCCESS on success, error code on failure
Note
Only used when policy is ALLOW_EVICTION_WITH_CONSENT

◆ SetEvictionPolicy()

hf_pwm_err_t EspPwm::SetEvictionPolicy ( hf_pwm_eviction_policy_t policy)
noexcept

Set timer eviction policy for resource management.

Parameters
policyEviction policy to use
Returns
PWM_SUCCESS on success, error code on failure
Note
Default is STRICT_NO_EVICTION for safety

◆ SetFrequency()

hf_pwm_err_t EspPwm::SetFrequency ( hf_channel_id_t channel_id,
hf_frequency_hz_t frequency_hz )
overridevirtualnoexcept

Set PWM frequency with automatic timer management.

Parameters
channel_idChannel identifier to update
frequency_hzTarget frequency in Hz
Returns
PWM_SUCCESS on success, error code on failure

Automatically manages timer allocation and sharing for efficient resource usage. May trigger timer reconfiguration or reallocation if frequency change is significant.

Note
Frequency is validated against current resolution and clock source
Warning
Large frequency changes may affect other channels sharing the same timer
See also
SetFrequencyWithResolution() for explicit frequency/resolution control
EnableAutoFallback() for automatic resolution adjustment

Implements BasePwm.

◆ SetFrequencyAndResolution()

hf_pwm_err_t EspPwm::SetFrequencyAndResolution ( hf_channel_id_t channel_id,
hf_frequency_hz_t frequency_hz,
hf_u8_t resolution_bits )
noexcept

Set frequency and resolution together (atomic operation)

Parameters
channel_idChannel identifier
frequency_hzFrequency in Hz
resolution_bitsResolution in bits
Returns
PWM_SUCCESS on success, error code on failure
Note
This is the most efficient way to change both parameters simultaneously

◆ SetFrequencyWithAutoFallback()

hf_pwm_err_t EspPwm::SetFrequencyWithAutoFallback ( hf_channel_id_t channel_id,
hf_frequency_hz_t frequency_hz,
hf_u8_t preferred_resolution )
noexcept

Set frequency with automatic fallback to alternative resolutions.

Parameters
channel_idChannel identifier
frequency_hzTarget frequency in Hz
preferred_resolutionPreferred resolution in bits
Returns
PWM_SUCCESS on success, error code on failure
Note
Automatically tries alternative resolutions if preferred fails

◆ SetFrequencyWithResolution()

hf_pwm_err_t EspPwm::SetFrequencyWithResolution ( hf_channel_id_t channel_id,
hf_frequency_hz_t frequency_hz,
hf_u8_t resolution_bits )
noexcept

Set frequency with explicit resolution choice (user-controlled)

Parameters
channel_idChannel identifier
frequency_hzTarget frequency in Hz
resolution_bitsExplicit resolution choice in bits (4-14)
Returns
PWM_SUCCESS on success, error code on failure

This method allows precise control over both frequency and resolution. The combination is validated against LEDC hardware constraints:

  • Formula: Required Clock = frequency_hz × (2^resolution_bits)
  • APB Clock (80MHz): Max frequency = 80MHz / (2^resolution_bits)
  • Example: 1kHz @ 10-bit requires 1.024MHz (1.28% of 80MHz) ✓
  • Example: 100kHz @ 10-bit requires 102.4MHz (128% of 80MHz) ✗
Warning
This method performs strict validation and will fail if the frequency/resolution combination exceeds hardware capabilities. Use SetFrequencyWithAutoFallback() for automatic resolution adjustment.

◆ SetHardwareFade()

hf_pwm_err_t EspPwm::SetHardwareFade ( hf_channel_id_t channel_id,
float target_duty_cycle,
hf_u32_t fade_time_ms )
noexcept

Set hardware fade for smooth duty cycle transitions.

Parameters
channel_idChannel identifier
target_duty_cycleTarget duty cycle (0.0 - 1.0)
fade_time_msFade duration in milliseconds
Returns
PWM_SUCCESS on success, error code on failure

◆ SetIdleLevel()

hf_pwm_err_t EspPwm::SetIdleLevel ( hf_channel_id_t channel_id,
hf_u8_t idle_level )
noexcept

Set idle output level for a channel.

Parameters
channel_idChannel identifier
idle_levelIdle level (0 or 1)
Returns
PWM_SUCCESS on success, error code on failure

◆ SetMode()

hf_pwm_err_t EspPwm::SetMode ( hf_pwm_mode_t mode)
noexcept

Set PWM operating mode.

Parameters
modeOperating mode (Basic or Fade)
Returns
PWM_SUCCESS on success, error code on failure

◆ SetPhaseShift()

hf_pwm_err_t EspPwm::SetPhaseShift ( hf_channel_id_t channel_id,
float phase_shift_degrees )
overridevirtualnoexcept

Set PWM phase shift (ESP32 LEDC limitation: not supported)

Parameters
channel_idChannel identifier (unused)
phase_shift_degreesPhase shift in degrees (unused)
Returns
PWM_ERR_INVALID_PARAMETER (LEDC doesn't support phase shift)

The ESP32 LEDC peripheral does not support hardware phase shifting. This method is provided for interface compatibility but will always return an error.

Note
For phase relationships, consider using timer offsets or software timing
Warning
This method will always fail on ESP32 LEDC peripheral

() - Required by base class interface but not supported by ESP32 LEDC hardware

Implements BasePwm.

◆ SetResolution()

hf_pwm_err_t EspPwm::SetResolution ( hf_channel_id_t channel_id,
hf_u8_t resolution_bits )
noexcept

Set PWM resolution for a channel.

Parameters
channel_idChannel identifier
resolution_bitsResolution in bits (4-14)
Returns
PWM_SUCCESS on success, error code on failure
Note
This may require timer reallocation if resolution changes significantly

◆ StartAll()

hf_pwm_err_t EspPwm::StartAll ( )
overridevirtualnoexcept

Start all configured PWM channels simultaneously.

Returns
PWM_SUCCESS on success, error code on failure

Enables all configured channels in a coordinated manner for synchronized startup. Channels that are already enabled remain unaffected.

Note
Only affects channels that have been configured with ConfigureChannel()
Warning
Individual channel errors are logged but don't stop the overall operation

Implements BasePwm.

◆ StopAll()

hf_pwm_err_t EspPwm::StopAll ( )
overridevirtualnoexcept

Stop all enabled PWM channels simultaneously.

Returns
PWM_SUCCESS on success, error code on failure

Disables all enabled channels in a coordinated manner for synchronized shutdown. Each channel's GPIO will be set to its configured idle level.

Note
Timer resources are automatically managed and released as appropriate

Implements BasePwm.

◆ StopHardwareFade()

hf_pwm_err_t EspPwm::StopHardwareFade ( hf_channel_id_t channel_id)
noexcept

Stop hardware fade for a channel.

Parameters
channel_idChannel identifier
Returns
PWM_SUCCESS on success, error code on failure

◆ UnregisterLedcFadeCallback()

hf_pwm_err_t EspPwm::UnregisterLedcFadeCallback ( hf_channel_id_t channel_id)
privatenoexcept

Unregister LEDC fade callback.

Parameters
channel_idChannel to unregister callback for
Returns
PWM_SUCCESS on success, error code on failure

◆ UpdateAll()

hf_pwm_err_t EspPwm::UpdateAll ( )
overridevirtualnoexcept

Update all enabled PWM channels with their current settings.

Returns
PWM_SUCCESS on success, error code on failure

Forces a synchronized update of all active LEDC channels to ensure any pending duty cycle or configuration changes take effect simultaneously.

Note
Useful after multiple SetDutyCycle() calls to ensure synchronized updates

Implements BasePwm.

◆ UpdatePlatformDuty()

hf_pwm_err_t EspPwm::UpdatePlatformDuty ( hf_channel_id_t channel_id,
hf_u32_t raw_duty_value )
privatenoexcept

Update platform duty cycle.

Parameters
channel_idChannel to update
raw_duty_valueRaw duty value
Returns
PWM_SUCCESS on success, error code on failure

◆ ValidateDutyCycleRange()

bool EspPwm::ValidateDutyCycleRange ( hf_u32_t raw_duty,
hf_u8_t resolution_bits ) const
privatenoexcept

Enhanced duty cycle validation with overflow protection.

Parameters
raw_dutyRaw duty cycle value
resolution_bitsResolution in bits
Returns
true if duty cycle is valid and safe
Note
Implements ESP-IDF overflow protection: duty < 2^resolution

◆ ValidateFrequencyResolutionComplete()

EspPwm::ValidationResult EspPwm::ValidateFrequencyResolutionComplete ( const ValidationContext & context) const
privatenoexcept

Unified comprehensive validation for frequency/resolution combinations.

Parameters
contextValidation context with all parameters
Returns
Detailed validation result with recommendations
Note
This replaces all individual validation functions with a unified approach

Member Data Documentation

◆ auto_fallback_enabled_

bool EspPwm::auto_fallback_enabled_
private

Whether to automatically try alternative resolutions.

◆ base_clock_hz_

hf_u32_t EspPwm::base_clock_hz_
private

Base clock frequency.

◆ channels_

std::array<ChannelState, MAX_CHANNELS> EspPwm::channels_
private

Channel states.

◆ clock_source_

hf_pwm_clock_source_t EspPwm::clock_source_
private

Current clock source.

◆ complementary_pairs_

std::array<ComplementaryPair, MAX_CHANNELS / 2> EspPwm::complementary_pairs_
private

Complementary pairs.

◆ current_mode_

hf_pwm_mode_t EspPwm::current_mode_
private

Current operating mode.

◆ diagnostics_

hf_pwm_diagnostics_t EspPwm::diagnostics_
private

PWM diagnostics.

◆ eviction_callback_

hf_pwm_eviction_callback_t EspPwm::eviction_callback_
private

User callback for eviction consent.

◆ eviction_callback_user_data_

void* EspPwm::eviction_callback_user_data_
private

User data for eviction callback.

◆ eviction_policy_

hf_pwm_eviction_policy_t EspPwm::eviction_policy_
private

Timer eviction policy (default: STRICT_NO_EVICTION)

◆ fade_functionality_installed_

bool EspPwm::fade_functionality_installed_
private

LEDC fade functionality installed.

◆ initialized_

std::atomic<bool> EspPwm::initialized_
private

Initialization state (atomic for lazy init)

◆ last_global_error_

hf_pwm_err_t EspPwm::last_global_error_
private

Last global error.

◆ MAX_CHANNELS

constexpr hf_u8_t EspPwm::MAX_CHANNELS = HF_PWM_MAX_CHANNELS
staticconstexpr

Maximum PWM channels.

◆ MAX_FREQUENCY

constexpr hf_u32_t EspPwm::MAX_FREQUENCY = HF_PWM_MAX_FREQUENCY
staticconstexpr

Maximum frequency (Hz)

◆ MAX_RESOLUTION

constexpr hf_u8_t EspPwm::MAX_RESOLUTION = HF_PWM_MAX_RESOLUTION
staticconstexpr

Maximum resolution bits.

◆ MAX_TIMERS

constexpr hf_u8_t EspPwm::MAX_TIMERS = HF_PWM_MAX_TIMERS
staticconstexpr

Maximum timer groups.

◆ MIN_FREQUENCY

constexpr hf_u32_t EspPwm::MIN_FREQUENCY = HF_PWM_MIN_FREQUENCY
staticconstexpr

Minimum frequency (Hz)

◆ mutex_

PlatformMutex EspPwm::mutex_
mutableprivate

Thread safety mutex.

◆ statistics_

hf_pwm_statistics_t EspPwm::statistics_
private

PWM statistics.

◆ timers_

std::array<TimerState, MAX_TIMERS> EspPwm::timers_
private

Timer states.

◆ unit_config_

hf_pwm_unit_config_t EspPwm::unit_config_
private

Unit configuration.


The documentation for this class was generated from the following files: