0
0
Embedded Cprogramming~5 mins

Duty cycle control for motor/LED in Embedded C

Choose your learning style9 modes available
Introduction

Duty cycle control helps change how strong or bright a motor or LED works by turning it on and off very fast.

To make an LED glow dimmer or brighter without changing the LED itself.
To control the speed of a small motor in a toy or gadget.
To save power by reducing how long a device is on.
To create effects like blinking lights or motor speed changes.
To adjust heating elements by controlling power delivery.
Syntax
Embedded C
void setDutyCycle(int dutyCyclePercent) {
    // dutyCyclePercent is from 0 to 100
    int compareValue = (MAX_TIMER_VALUE * dutyCyclePercent) / 100;
    TIMER_COMPARE_REGISTER = compareValue;
}

The duty cycle is usually given as a percentage from 0 (off) to 100 (fully on).

The timer compare register sets how long the output stays on in each cycle.

Examples
Sets the duty cycle to 0%, so the device is off.
Embedded C
setDutyCycle(0); // LED or motor off
Sets the duty cycle to 50%, so the device is on half the time.
Embedded C
setDutyCycle(50); // Half brightness or speed
Sets the duty cycle to 100%, so the device is fully on.
Embedded C
setDutyCycle(100); // Full brightness or speed
Sample Program

This program simulates setting the duty cycle for a motor or LED by calculating the timer compare register value and printing it.

Embedded C
#include <stdio.h>

#define MAX_TIMER_VALUE 1000

int TIMER_COMPARE_REGISTER = 0;

void setDutyCycle(int dutyCyclePercent) {
    if (dutyCyclePercent < 0) dutyCyclePercent = 0;
    if (dutyCyclePercent > 100) dutyCyclePercent = 100;
    int compareValue = (MAX_TIMER_VALUE * dutyCyclePercent) / 100;
    TIMER_COMPARE_REGISTER = compareValue;
    printf("Duty cycle set to %d%%, compare register = %d\n", dutyCyclePercent, TIMER_COMPARE_REGISTER);
}

int main() {
    setDutyCycle(0);    // Off
    setDutyCycle(25);   // 25% on
    setDutyCycle(50);   // 50% on
    setDutyCycle(75);   // 75% on
    setDutyCycle(100);  // Fully on
    return 0;
}
OutputSuccess
Important Notes

Duty cycle control uses a technique called PWM (Pulse Width Modulation).

Changing the duty cycle changes how long the device is powered in each cycle, affecting brightness or speed.

Always check your hardware limits to avoid damage when setting duty cycles.

Summary

Duty cycle controls how long a device is on in each cycle to adjust brightness or speed.

It is expressed as a percentage from 0 to 100.

Use a timer compare register to set the duty cycle in embedded systems.