In this lesson, you will learn how to calculate the duty cycle to precisely control the average power delivered to a load, such as an LED or a DC motor.
The Concept of Average Voltage
In digital systems, a pin is either "on" (High, ) or "off" (Low, ). While we cannot output a true analog voltage like 2.5V from a 5V digital pin, we can simulate it using Pulse Width Modulation (PWM). By switching the pin high and low very rapidly, the load sees the average voltage over time. This average is determined by the duty cycle, which is the ratio of the "on" time to the total period of the signal.
The Mathematical Relationship
To calculate the duty cycle (), we use the high-state duration () and the total period ():
Where the period is the sum of the high-state time () and the low-state time (). Consequently, the average voltage () delivered to your load is:
Implementation Example
If your timer is configured for a period of 1000 clock cycles and you want to deliver 50% power, you must set your timer compare register to trigger a state change at 500 cycles.
// Target: 50% duty cycle on a 1000-cycle timer
uint16_t period = 1000;
uint16_t duty_cycle = 50; // Percentage
// Calculate the number of ticks the signal should be HIGH
uint16_t compare_value = (period * duty_cycle) / 100;
// Update the Timer Compare Register (pseudo-code)
TIMER_CMP_REG = compare_value;
By manipulating the compare_value, you directly control how long the pin remains high within each cycle. If you increase the compare_value, the average voltage increases, making a motor spin faster or an LED glow brighter. As long as the frequency is high enough, the load integrates these pulses into a smooth, effective power level.
Key Takeaway: The duty cycle is the mathematical ratio of the high-state duration to the total signal period, allowing you to regulate average power by adjusting the portion of time a digital signal remains active.