Interaction Design WikiElectrical Engineering

Pulse Width Modulation (en)

German Version

There is no way to generate an analogue value on the Arduino directly, so to make an LED fade we need to use pulse-width modulation. A digital signal from the Arduino switches the corresponding PIN (PWM pins are marked with PWM or ~) ON and OFF very quickly. The longer the ON times of the pin, the brighter the LED appears to us - in contrast, the LED appears darker to us when the OFF times are longer. The PWM function of the microcontroller enables us to set simple values at the corresponding PIN. 0 corresponds to 0V or OFF and 255 corresponds to 5V or ON. Any intermediate value (e.g. 127) can be seen as a combination of 0V and 5V and then corresponds to e.g. 2.5V.

Visualization

This visualization shows how a PWM value is generated by the Arduino.

Function
 

To use a PWM-enabled pin on the Arduino e.g. To dim an LED, we call the following function:

analogWrite(PIN, value);
Value (0-255) at the specified PIN


Here is a short example that fades an LED

Example PWM Expand source
#define LED_PIN 11 // PWM enabled pin
 
void setup()
{
  pinMode(LED_PIN, OUTPUT); 
}
 
void loop()
{
  for(int i=0; i<255; i++)
  {
    analogWrite(LED_PIN, i); // Set the value i on LED_PIN 
    delay(10);
  }
   
  for(int i= 255; i>0; i--)
  {
    analogWrite(LED_PIN, i); // Set the value i on LED_PIN 
    delay(10);
  }
}

Further Information:

PWM - on Arduino.cc
The Secrets of Arduino PWM - on Arduino.cc
analogWrite() - on Arduino.cc
Pulse-Width-Modulation - on Wikipedia.org