Arduino: Control LEDs with a Potentiometer
I’m waiting for some more parts to build my bike computer so I figured I should play around with the parts I got with my Arduino. Here I used a potentiometer to control some LEDs. The output from the pot is connected to an analog pin, and each LED is hooked up to a digital pin.
Code:
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
int mappedValue = 0;
void setup() {
// declare the LED pins as OUTPUTs:
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
Serial.begin(9600); //for testing
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// map the sensor range (0-1023) to the number of LEDs (4, plus one for off)
mappedValue = map(sensorValue, 0, 1023, 0, 4);
// for testing
Serial.println(sensorValue);
Serial.println(mapped);
// loop through all of the pins
for(int i = 0; i <= 4; i++){
// if a pin is within the mapped sensor value, turn it on
if(i < mappedValue){
// +2 because pins 0 and 1 are for serial I/O
digitalWrite(i+2, HIGH);
// if a pin is outside sensor value, turn it off
} else {
digitalWrite(i+2, LOW);
}
}
}
