Arduino Code

Load the following sketch onto your Arduino board.  

Download: file
/*
Adafruit Arduino - Lesson 8. Analog Inputs - LEDs
*/

int potPin = 0;
int latchPin = 5;
int clockPin = 6;
int dataPin = 4;

int leds = 0;

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

void loop() 
{
  int reading  = analogRead(potPin);
  int numLEDSLit = reading / 114;  //1023 / 9
  leds = 0;
  for (int i = 0; i < numLEDSLit; i++)
  {
    bitSet(leds, i); 
  }
  updateShiftRegister();
}

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

You should recognize much of this code from lesson 4. So refer back to that lesson for more information about how the LEDs are controlled.

The key parts of the sketch as far as analog inputs are concerned are the line where we define the analog pin that we are going to connect to the slider of the pot:

Download: file
int potPin = 0;

Note that we do not need to put anything in 'setup' to set the pin mode for an analog input.

In the main loop, we read the analog value like this:

Download: file
  int reading  = analogRead(potPin);

But then this reading between 0 and 1023 needs converting into a number of LEDs to light, between 0 and 8. The range of numbers, between 0 and 8 is actually 9 values. So we need to scale the reading by 1023 divided by 9 or 114.

Download: file
int numLEDSLit = reading / 114;

To light the right number of LEDs, we use the 'for' loop to count from 0 up to 'numLEDSLit' setting the bit at that position.

Download: file
  leds = 0;
  for (int i = 0; i < numLEDSLit; i++)
  {
    bitSet(leds, i); 
  }

Finally we update the shift register with a call to:

Download: file
updateShiftRegister();
This guide was first published on Dec 10, 2012. It was last updated on Dec 10, 2012.
This page (Arduino Code) was last updated on Aug 13, 2020.