What is the output of the following code that calculates the PWM duty cycle percentage?
unsigned int timer_period = 1000; unsigned int pulse_width = 250; float duty_cycle = (pulse_width / (float)timer_period) * 100; printf("Duty Cycle: %.1f%%\n", duty_cycle);
Remember to cast integers to float before division to get a decimal result.
The pulse width divided by the timer period gives the fraction of the period the signal is high. Multiplying by 100 converts it to a percentage. Casting to float ensures decimal division.
Which timer configuration will produce a PWM signal with a frequency of 1 kHz if the timer clock is 1 MHz?
Frequency = timer_clock / (prescaler * period)
With a 1 MHz clock, setting prescaler to 1 and period to 1000 gives 1 MHz / (1 * 1000) = 1 kHz.
What error will occur when running this PWM initialization code?
TIM_HandleTypeDef htim; htim.Init.Prescaler = 0; htim.Init.Period = 0; HAL_TIM_PWM_Init(&htim); HAL_TIM_PWM_Start(&htim, TIM_CHANNEL_1);
Check the timer period value before initialization.
Setting period to zero causes division by zero when calculating timer frequency, leading to runtime error.
Which option correctly updates the PWM duty cycle to 50% for a timer with period 1000?
/* Assume htim and channel are properly initialized */ uint32_t new_pulse = 500; // 50% of 1000 // Update PWM pulse here
Check the structure pointer and member access syntax.
htim is a structure, so use dot operator. Instance is a pointer, so use '->' to access CCR1.
Given a timer clock of 8 MHz, prescaler set to 7, and period set to 999, what is the PWM signal frequency?
Frequency = timer_clock / ((prescaler + 1) * (period + 1))
Frequency = 8,000,000 / ((7 + 1) * (999 + 1)) = 8,000,000 / (8 * 1000) = 1000 Hz.