### Analog Read and a Potentiometer

A potentiometer is a variable resistor. By twisting the knob we can change the value of resistance. For more on the inner workings of a variable resistor just watch this video I created last year or check out this description.

Here's the Analog Input sketch from the Examples in the Sketchbook. For this circuit you need an LED in pin 13 (as we've done before) and a potentiometer (any size) in analog pin 2. To wire up the potentiometer you connect the center lead to analog pin 2. The two sides get hooked to power. One side goes to positive volts and the other goes to the ground.

 /* * AnalogInput * by DojoDave  * * Turns on and off a light emitting diode(LED) connected to digital   * pin 13. The amount of time the LED will be on and off depends on * the value obtained by analogRead(). In the easiest case we connect * a potentiometer to analog pin 2. * * http://www.arduino.cc/en/Tutorial/AnalogInput */int potPin = 2;    // select the input pin for the potentiometerint ledPin = 13;   // select the pin for the LEDint val = 0;       // variable to store the value coming from the sensorvoid setup() {  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT}void loop() {  val = analogRead(potPin);    // read the value from the sensor  digitalWrite(ledPin, HIGH);  // turn the ledPin on  delay(val);                  // stop the program for some time  digitalWrite(ledPin, LOW);   // turn the ledPin off  delay(val);                  // stop the program for some time}

By adjusting the potentiometer you should be adjusting the blink rate of your LED. Notice we do not need to do pinMode for the potPin. All analog pins are inputs. If we want an analog output we need to use one of the digital PWM pins.

Now lets use the potentiometer as a light dimmer. We're going to leave the potentiometer in pin two, but we're moving the LED to pin 11, which is a PWM pin. The easiest thing would be to read the potPin and use that as the val in analogWrite(ledPin, val), but this will not work. analogRead will return a value between 0 and 1023, while analogWrite wants a value between 0 and 255. To do this we're going to use a new command. The map command will work for this.

 val = map (val, 0, 1023, 0, 255);map(our number, min value we can have, max value we can have, min value we want, max value we want)

 int potPin = 2;    // select the input pin for the potentiometerint ledPin = 11;   // select the pin for the LEDint val = 0;       // variable to store the value coming from the sensorvoid setup() {  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT}void loop() {  val = analogRead(potPin);    // read the value from the sensor  val = map(val, 0, 1023, 0, 255);  // make val a number between 0 and 255  analogWrite (ledPin, val);   // turn on LED with a value between 0-255}