Arduino Lesson 5 – Reading Potentiometer Values on Serial Monitor

Fig. 1 - Arduino Lesson 5 - Reading Potentiometer and Showing Values On Serial Monitor

Arduino Lesson 5 – Reading Potentiometer and Showing Values On Serial Monitor


Welcome to Lesson 5 – Basic Arduino Course

Today we are going to learn how to read a Potentiometer end showing the Values on Serial Monitor.
In this example, we will use a potentiometer, however, this same concept is used for most analog sensors.

What will differentiate will be the type of calculation used, with reference to each sensor.

We will use the analogRead() function, to read A0 PIN, in Arduino we have 6 Analog Ports, which goes from A0 to A5, so we can make readings from up to 6 sensors simultaneously without having to use external hardware.

Hardware Required

  • Arduino Board
  • A 10K Potentiometer
  • Wires
  • Protoboard (optional)

The Circuit

The potentiometer works like a voltage divider. When you turn the shaft of the potentiometer, you change the resistance on either side of the center pin (or wiper) of the potentiometer.

This changes the relative resistances between the center pin and the two outer pins, so you get a different voltage at the analog input.

When the shaft is fully rotated in one direction, there is no resistance between the center pin and the pin connected to ground.

The middle pin varies from 0Kohms to 10Kohms, which is the value of the potentiometer we will use.

This resistance is sensed by the voltages at the ends of the potentiometer, causing the center pin to vary between 0V and 5V.

And the voltage variation that comes from the Center Pin of the potentiometer goes to the A0 Analog Port.

In Figure 2, you can see the schematic of the potentiometer and the Arduino. We use a breadboard to make the connections easier, but you can also connect the wires directly from the A0 terminal in the middle of the potentiometer, connecting the outer pin to 5V positive and the outer pin to the negative GND of the Arduino.

Fig. 2 - Reading Potentiometer and Showing Values On Serial Monitor - tinkercad.com

Fig. 2 – Reading Potentiometer and Showing Values On Serial Monitor – tinkercad.com

The Code

The analogRead() function converts the input voltage range, 0 to 5 volts, to a digital value between 0 and 1023. This is done by a circuit within the microcontroller called analog-to-digital converter, or ADC.

Then, if the voltage at the center pin is 0 volts, analogRead() returns 0. When the shaft is turned all the way the other way, there is no resistance between the middle pin and the pin connected to 5 volts.

If the voltage on the middle pin is then 5 volts, analogRead() returns 1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the voltage applied to the pin.

After building the circuit, connect your Arduino board to your computer, launch Arduino Software (IDE), copy the code below and paste it into your Arduino IDE. But first let us understand the code line by line.

  • In Line 3, we declared variable sensorPin which is set to Analog Pin A0 where we receive the value of the connected potentiometer.
  • In Line 4, we create a variable senorPin that stores the value of the sensor that we also use for the potentiometer.
// Arduino: Lesson 5 - Reading Potentiometer and Showing Values On Serial Monitor

int sensorPin = A0;    // Read the Analogic Pin A0 Values into a variable
int sensorValue = 0;   // Variable to store the value coming from the sensor "Potentiometer"
  • In Line 6, we enter the void setup() function. This function is read only once when the Arduino is started.
  • In Line 7, we begin serial communication by declaring the Serial.begin() function. At 9600 bits of data per second, this is the speed at which your computer will communicate with your Arduino Serial.
void setup() {                 // This function is called once when the program starts
  Serial.begin(9600);          // Begin the Serial Monitor with bounce rate in 115200
}
  • After setting the initializations, in Line 10 we will enter the void loop() function.
  • In Line 11, we use the variable sensorValue to store the resistance value, which is between 0 and 10K (read by the Arduino as a value between 0 and 1023) and controlled by the potentiometer.
  • In Line 13, we use the command Serial.println(), it is print out the value controlled by the potentiometer, this value will read with value between 0 and 1023 in your Serial Monitor.
  • In Line 14, we run the delay() function, for greater system stability.
void loop() {                                                // The loop function runs over and over again forever
  sensorValue = analogRead(sensorPin);     // Read the input on analog pin A0
  
  Serial.println(sensorValue);             // Print out the value you read
  delay(1);                                // delay in between reads for stability
}

Now you can copy the code and upload it to your Arduino. After that, if you open your Serial Monitor in Arduino Software (IDE) (by clicking on the icon that looks like a lens on the right side of the green top bar or using the keyboard shortcut Ctrl+Shift+M), you should see a steady stream of numbers in the range 0-1023 that correlate with the position of the pot. When you turn your potentiometer, these numbers respond almost instantly.

The complete code is showed in the sketch below!

// Arduino: Lesson 5 - Reading Potentiometer and Showing Values On Serial Monitor

int sensorPin = A0;    // Read the Analogic Pin A0 Values into a variable
int sensorValue = 0;   // Variable to store the value coming from the sensor "Potentiometer"

void setup() {                 // This function is called once when the program starts
  Serial.begin(9600);          // Start serial connection
}

void loop() {                                                // The loop function runs over and over again forever
  sensorValue = analogRead(sensorPin);     // Read the input on analog pin A0
  
  Serial.println(sensorValue);             // Print out the value you read
  delay(1);                                // delay in between reads for stability
}
//------------------------------------- www.elcircuits.com --------------------------------------------

Next Lesson

Previous Lesson

✨ Our Gratitude and Next Steps

We sincerely hope this guide has been useful and enriching for your projects! Thank you for dedicating your time to this content.

Your Feedback is Invaluable:

Have any questions, suggestions, or corrections? Feel free to share them in the comments below! Your contribution helps us refine this content for the entire ElCircuits community.

If you found this guide helpful, spread the knowledge!

🔗 Share This Guide

Best regards,
The ElCircuits Team ⚡

Share This Guide

No comments yet

  1. Торжество становится ключевым событием в жизни человека.
    Данный день означает образование общей истории.
    Он соединяет этих близких партнёров перед родными и свидетелями.
    https://www.realbrest.by/prosto-dlja-vas/organizacija-dnja-rozhdenija.html
    Празднование помогает влюблённым открыто признаться в своих чувствах и обменяться клятвами.
    Свадьба является символом навсегда, сохраняя любовь партнёров.

    Your comment is awaiting moderation.
  2. Seeing pictures in a movie theater is far more fun than streaming them at home.
    The giant screen and surround audio deliver a truly theatrical experience.
    movies to watch
    Audiences can fully concentrate on the story free from interruptions like texts.
    Additionally, the collective atmosphere of laughing with others makes the movie more enjoyable.

    Your comment is awaiting moderation.
  3. Enjoying movies in a theater is much more fun than watching them at home.
    The giant display and powerful audio provide a truly theatrical experience.
    movie theaters
    Viewers can completely focus on the film free from notifications like household chores.
    Additionally, the shared experience of reacting together renders the screening far more enjoyable.

    Your comment is awaiting moderation.
  4. Watching films in a theater is far better than streaming them at home.
    The big display and surround sound system create a deeply theatrical atmosphere.
    channelfanbase.co.uk
    Audiences can completely focus on the film without interruptions like household chores.
    Furthermore, the communal energy of laughing together renders the movie more impactful.

    Your comment is awaiting moderation.
  5. Seeing movies in a cinema is significantly more enjoyable than viewing them at home.
    The big display and surround sound system create a genuinely cinematic experience.
    channelfanbase.co.uk
    Viewers can completely concentrate on the story free from notifications like texts.
    Moreover, the shared energy of laughing together renders the movie more impactful.

    Your comment is awaiting moderation.
  6. Такие платформы 18+ призваны служить каналом сексуального просвещения.
    Подобные ресурсы дают возможность людям в приватной обстановке исследовать собственные границы и фантазии.
    erostoryai.com
    Для партнёров общий просмотр может служить причиной для честного беседы о границах.
    Помимо этого такие ресурсы помогают уменьшать психологическое напряжение и сохранять эмоциональное здоровье.

    Your comment is awaiting moderation.

Leave a Reply

Your email address will not be published. Required fields are marked *