Load the following sketch onto your Arduino board.
/* 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:
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:
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.
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.
leds = 0; for (int i = 0; i < numLEDSLit; i++) { bitSet(leds, i); }
Finally we update the shift register with a call to:
updateShiftRegister();
Page last edited October 12, 2012
Text editor powered by tinymce.