Project 6.00 Using the Potentiometer
This project introduces the potentiometer and shows how to use it. A potentiometer is a special type of resistor that allows us to change its resistance value. This feature makes potentiometers very useful for tasks like adjusting the volume on speakers or controlling the brightness of lights, where we need to vary resistance to control an electrical current.
Project Code:
/////////////////////////////////////////////////////////// // 6.00 - Using The Potentiometer byte potPin = A0; void setup() { Serial.begin(9600); pinMode(potPin, INPUT); } void loop() { int potValue = analogRead(potPin); Serial.print("The pot value is at: "); Serial.println(potValue); delay(100); } ///////////////////////////////////////////////////////////
*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.
First, we declare the pin that the potentiometer is connected to as potPin. This variable declaration is different from those you’ve seen so far because it starts with an “A”. This “A” means that the pin we are connecting to is an analog pin. Analog pin refers to a pin that can read analog values. A digital value would be a 1 or a 0 (5v or 0v), but an analog value can be anything in between. Not all pins can be used as analog pins on the MC Trainer.
byte potPin = A0;
In the setup you’ll notice that the pin is still an INPUT pin. This is because we are using the pin to read a value. It does not matter if it is digital or analog, it is still an input.
pinMode(potPin, INPUT);
You can read the analog voltage at an analog pin by using the analogRead function. analogRead returns a 10-bit value (0 – 1023) that represents the voltage at that pin. 5v would be 1023, ~2.5v would be 512, and 0v would be 0.
int potValue = analogRead(potPin);
After that we print the value read out into the Serial port and delay 100 milliseconds. Make sure and open the Serial port to see the data being printed.
Serial.print("The pot value is at: "); Serial.println(potValue); delay(100);
Try rotating the knob of the potentiometer to see the range of values produced!