A pushbutton is digital: itâs either pressed or not pressed. On or off. Yes or no. But the real world, unfortunately, is rarely that black and white. Temperature, light, soundâtheyâre all messy, continuously varying gradients.
To read these wishy-washy, non-committal real-world values, we canât use digital pins. We need an Analog Input. Today, weâll use a knob called a potentiometer to feed a variable voltage into our Arduino. Because sometimes, you donât just want to turn things on; you want to turn things up.
A potentiometer provides a variable voltage output based on the knobâs rotation.
A potentiometer (or âpotâ) is simply a variable resistor. It has three pins. Inside, the two outer pins are connected to a long track of resistive material. The middle pin is connected to a âwiperâ that slides along that track as you turn the knob.
If you connect the outer pins to 5V and GND, the middle pin will output a voltage somewhere between 0V and 5V, depending on where the wiper is positioned. It acts as a mechanical voltage divider.
The microcontroller inside the Arduino Uno is fundamentally a digital device. It canât âunderstandâ an analog voltage like 2.34V directly.
It uses a built-in circuit called an Analog to Digital Converter (ADC) to measure the voltage and translate it into a digital number that the processor can use. The Uno has a 10-bit ADC, which means it translates a 0V-5V signal into a number between 0 and 1023.
Letâs use the position of the knob to control how fast an LED blinks.
int sensorPin = A0; // The input pin for the potentiometer
int ledPin = 9; // The output pin for the LED
int sensorValue = 0; // Variable to store the value coming from the sensor
void setup() {
// We don't need to declare pinMode for Analog Input pins!
pinMode(ledPin, OUTPUT);
}
void loop() {
// Read the value from the sensor (0 to 1023):
sensorValue = analogRead(sensorPin);
// Turn the LED on
digitalWrite(ledPin, HIGH);
// Use the sensorValue as the delay time!
delay(sensorValue);
// Turn the LED off
digitalWrite(ledPin, LOW);
// Delay again
delay(sensorValue);
}
Now, as you twist the knob, the sensorValue changes between 0 and 1023. That value is passed directly into the delay() function. Turn it one way, and it blinks rapidly (e.g., delay(10)). Turn it the other way, and it blinks slowly (e.g., delay(1000)).
[Need components for your control panel? This Rotary Potentiometer Kit has all the knobs youâll ever need!]
Youâve successfully bridged the analog world and the digital world!