Using Loops in PWM Programming

Pulse Width Modulation (PWM) is a technique used to control the average power delivered to a load by varying the width of the pulses of a square wave signal. Arduino boards provide the analogWrite() function to generate PWM signals. In this guide, we’ll explore how to use loops to create different PWM patterns and control the behavior of devices.  

Basic Loop Structures

  • for Loop: Used to execute a block of code a specified number of times.
  • while Loop: Used to execute a block of code as long as a condition is true.
  • do-while Loop: Used to execute a block of code at least once, then repeat as long as a condition is true.

Creating PWM Patterns

By combining loops with the analogWrite() function, you can create various PWM patterns. Here are some examples:

1. Linear Ramp:

C++

const int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  for (int i = 0; i <= 255; i++) {
    analogWrite(ledPin, i);
    delay(10);
  }

  for (int i = 255; i >= 0; i--) {
    analogWrite(ledPin, i);
    delay(10);   
  }
}

This code creates a linear ramp effect, gradually increasing and decreasing the duty cycle of the PWM signal.

2. Sine Wave:

C++

const int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  for (int i = 0; i <= 255; i++) {
    int value = sin(i * 2 * PI / 255) * 127 + 128;
    analogWrite(ledPin, value);
    delay(10);
  }
}

This code creates a sine wave pattern, simulating a smooth increase and decrease in brightness.

3. Random Patterns:

C++

const int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int value = random(0, 256);
  analogWrite(ledPin, value);
  delay(100);
}

This code generates random PWM values, creating a flickering or flashing effect.

Additional Tips

  • Experiment with Different Patterns: Try different loop structures and mathematical functions to create unique PWM patterns.
  • Adjust Delay: The delay between PWM updates affects the speed and smoothness of the pattern.
  • Combine with Other Techniques: Combine PWM with other techniques, such as sensor inputs or user interaction, to create more complex and interactive projects.

By understanding how to use loops effectively with PWM, you can create a wide range of interesting and dynamic effects in your Arduino projects.

Duty Cycle Control Using Analog Write
I2C Basics and Functionality

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?