p>Potentiometers provide a variable resistance when you turn a knob. They are used for things like volume controls.
In this recipe, we will use the analogue read capability of the Arduino to change to speed at which the built-in LED flashes.
You will need:
Wire up the circuit as follows:
Note that the potentiometer has 3 pins. The middle pin is where we will read the signal. This must be connected to pin A2 on the Arduino. The GND and 5V pins can be wired either way around.
<p>Copy the code below and overwrite the code in the Arduino IDE.</p>
// Constants const int POTPIN = A2; void setup() { // Tell Arduino which pins are input and output pinMode(POTPIN, INPUT); } void loop() { // Read the value (0 to 1023) from the potentiometer int val = analogRead(POTPIN); // Flash the LED, using a delay related to the potentiometer setting digitalWrite(LED_BUILTIN, HIGH); delay(val); digitalWrite(LED_BUILTIN, LOW); delay(val); }
Now upload the code to the Arduino.
The built-in LED should start flashing. Turn the knob on the potentiometer to change the speed of the flashing.
We are connecting the middle pin of the potentiometer to the A2 pin on the Arduino. The A in A2 stands for Analogue. You will see that your Arduino has a few analogue pins.
Any of these could be used instead (but you will need to change the pin number in the code accordingly.
When we call the analogueRead()
function, the Arduino checks the voltage being applied to the pin. The voltage must be between 0 and 5V. The value returned by analogueRead()
will be 0 if the voltage is 0, 1023 if the voltage is 5V, and a number between 0 and 1023 if the voltage is somewhere in between. So applying a voltage of 2.5V will return 512 from analogueRead()
.
The potentiometer is a variable resistor. As we turn the knob, the resistance changes and hence the voltage on the pin changes. The Arduino is reading this change in voltage. The video below shows a multimeter attached to the signal and ground to read the voltage of the potentiometer signal. Notice how the reading moves between 0 and 5V whilst I turn the knob, and how the LED on the Arduino changes its speed of flashing in relation to this voltage.