Adjust the LED brightness for different voltages using PWM

PWM Calculation

Helpful video

PWM Frequency: 1 kHz (prevent visible flickering)

  • The number of times per second that the LED turns on and off
  • The frequency is high enough so that you don’t see the LED flashing; you just see it as on
  • Calculate using this formula:
  • is a scale factor to “slow down” the timer frequency

Counter Period (Auto Reload Register): 99 (counter goes from 0 to 99, which is 100 steps. easier to calculate duty cycle)

  • The number of times to count for each period

Prescaler: 839 (solved for prescaler using 1kHz PWM freq and 99 period)

  • The number of cycles per timer count

Used default 84MHz as the frequency

Duty cycle: % of time in a cycle where the signal is high (LED is on)

  • Higher duty cycle brighter LED

Compare value: divide this number by the period to get the duty cycle

  • Duty cycle (%) = (compare value / period) × 100

Configuration

Set the PC6 pin as TIM3 on PWM mode

Changing LED Brightness

  1. Voltage changes and then the voltage manager task notifies the alarm task.
  2. The alarm task calculates the new compare value. If the voltage is above the voltage threshold, the alarm task notifies the PWM controller.
    1. int compareValue = (int)((batteryVoltage / (float)MAX_VOLTAGE) * PERIOD);
  3. The PWM controller task updates the compare value.
void TaskPWMController(void *argument)
{
	// ...
	if(xTaskNotifyWait(0, 0xFFFFFFFF, &receivedValue, pdMS_TO_TICKS(10)) == pdPASS) {
        targetDutyCycle = receivedValue;
        currentDutyCycle = targetDutyCycle;
    }
    __HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, currentDutyCycle);
}