Arduino – LED brightness

This article shows how to use PWM (Pulse Width Modulation) to control LED brightness. Arduino boards based on ATmega328 have up to 6 hardware PWM channels mapped to pins 3, 5, 6, 9, 10, 11 @490 Hz (pins 5 and 6: 980 Hz). Thanks to Arduino API (analogWrite) we can easly control these PWM channels. Bellow you can find an example code that uses simple class -BasicLed. The object of this class can manipulate single LED. In presentend example the LED brightness has been set to roughly 4%. The code is also on GithHub, here.

Parts List

Software

This code is written in C++ and can be compiled using an Arduino IDE. All information about how to compile this project is here.

#include <stdint.h>

/**
 * The instance of this class can control single LED.
 * - on, off, toggle (any digital pin)
 * - brightness (only PWM pins; i.e. for Arduino Uno: 3, 5, 6, 9, 10, 11)
 */
class BasicLed {
public:
  BasicLed(uint8_t pin): pin_(pin) {
    pinMode(pin, OUTPUT); 
  }
  /* Light the LED up */
  void on(void) {
    digitalWrite(pin_, HIGH);
  }
  /* Turn the LED off */
  void off(void) {
    digitalWrite(pin_, LOW);
  }
  /* Toogle LED on/off */
  void toggle(void) {
    digitalWrite(pin_, !digitalRead(pin_));
  }
  /* Set LED brightness from range <0, 255> */
  void setBrightness(uint8_t value) {
    analogWrite(pin_, value);
  }
private:
  uint8_t pin_;
}; /* End of class BasicLed */

BasicLed led(11);

void setup() {
  // do nothing
}

void loop() {
    led.setBrightness(10); // 10/255 ~= 4%
}

Leave a Comment