Arduino – PWM with LED (Pulse Width Modulation)

Description:

PWM, or Pulse Width Modulation, allows you to use a digital pin like a dimmer switch. Instead of being only on or off, you can set the amount of power going to the pin. Essentially you are turning on and off the digital pin very quickly to give a dimmer effect. This can be used to change the intensity of an LED, or more usefully change the speed of motors.

On an Arduino only digital pins with the ~ mark can be used for PWM.

Parts:

  • Arduino Uno
  • LED
  • 220 Ohm Resistor
  • Breadboard
  • Wires

Code:

#define led 9

void setup() {
  pinMode(led, OUTPUT);
}
void loop() {

  analogWrite(led, 0);
  delay(500);
  analogWrite(led, 50);
  delay(500);
  analogWrite(led, 100);
  delay(500);
  analogWrite(led, 150);
  delay(500);
  analogWrite(led, 200);
  delay(500);
  analogWrite(led, 255);
  delay(500);
  
}

Code with Comments:

//create pin for led
#define led 9

void setup() {
//set led pin to output
  pinMode(led, OUTPUT);
}
void loop() {
//use analogWrite function to change intensity of led. 0 = off, 255 = fully on
  analogWrite(led, 0);
  delay(500);
  analogWrite(led, 50);
  delay(500);
  analogWrite(led, 100);
  delay(500);
  analogWrite(led, 150);
  delay(500);
  analogWrite(led, 200);
  delay(500);
  analogWrite(led, 255);
  delay(500);
  
}