Brightness Control

One pin of the 74HC595 that I have not mentioned is a pin called 'Output Enable'. This is pin 13 and on the breadboard, it is permanently connected to Ground. This pin acts as a switch, that can enable or disable the outputs - the only thing to watch for is it is 'active low' (connect to ground to enable). So, if it is connected to 5V, all the outputs go off. Whereas if it is connected to Ground, those outputs that are supposed to be on are on and those that should be off are off.

We can use this pin along with the 'analogWrite' function, that we used back in Lesson 3, to control the brightness of the LEDs using PWM (also see Lesson 3).

To do this, all you need to do, is to change the connection to pin 13 of the 74HC595 so that instead of connecting it to Ground, you connect it to pin 3 of the Arduino.

The sketch below, will once all the LEDs have been lit gradually fade them back to off.
Download: file
/*
Adafruit Arduino - Lesson 4. 8 LEDs and a Shift Register - Brightness
*/

int latchPin = 5;
int clockPin = 6;
int dataPin = 4;
int outputEnablePin = 3;

byte leds = 0;

void setup() 
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);  
  pinMode(clockPin, OUTPUT);
  pinMode(outputEnablePin, OUTPUT); 
}

void loop() 
{
  setBrightness(255);
  leds = 0;
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(500);
  }
  for (byte b = 255; b > 0; b--)
  {
    setBrightness(b);
    delay(50);
  }
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

void setBrightness(byte brightness) // 0 to 255
{
  analogWrite(outputEnablePin, 255-brightness);
}
This guide was first published on Dec 03, 2012. It was last updated on Dec 03, 2012. This page (Brightness Control) was last updated on Nov 16, 2019.