Tutorial 08: analogRead() and Serial Port Communications

Arduino Course for Absolute Beginners

analogRead() and Serial Port Communications

Knowing if something is on or off can be extremely useful, but often you will want to know more. How bright is the light?

How fast is the satellite moving? These types of answers are often analog – they cover a large range of values, not just on or off.

The Arduino handles analog inputs with 6 dedicated pins, labeled A0 through A5. These pins have access to an analog-to-digital converter, which takes the range of input values and creates a digital version by cutting up the range into tiny pieces. All this is handled behind the scenes – all you have to do is use some very simple functions and you will get what you need.

You Will Need

  1. Potentiometer (any resistance range will work)
  2. Jumper Wires – at least 3
  3. Bicycle tire

Step-by-Step Instructions

  1. Place the potentiometer into your breadboard.
  2. Run a jumper wire from the 5-Volt pin of the Arduino to either one of the outside pins of your potentiometer.
  3. Run another jumper wire from one of the ground pins on your Arduino (labeled GND) to the other outside pin of the potentiometer.
  4. Run the final jumper wire from pin A0 on your Arduino to the middle pin of the potentiometer.
  5. Plug the Arduino into your computer.
  6. Open up the Arduino IDE.
  7. Open the sketch for this section.
  8. Click the Verify button on the top left side of the screen. It will turn orange and then back to blue once it has finished.
  9. Click the Upload button (next to the Verify button). It will turn orange and then back to blue once it has finished.
  10. On the menu bar, go to Tools > Serial Monitor – this will open the Serial Monitor window – you should see numbers rolling down this screen.
  11. Now adjust the knob of the potentiometer and watch the serial monitor window. The numbers should adjust between 0 and 1023.

Using the Arduino analogread and map function with a potentiometer at pin A0

This image composed with Fritzing.

The Arduino Code

/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

Discuss the Sketch

This sketch starts with a multi-line comment describing the sketch and the circuit. You will probably notice that the first block of code is the setup() function – we do not declare or initialize any variables at the beginning of this sketch – instead we will do this inside the loop() function, as in the last example. Inside the curly braces of setup() we revisit the Serial library and use the function Serial.begin().

void setup() {

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

}

If you recall from the last lesson, Serial.begin() takes the baud rate as an argument (this will almost always be 9600). This function allows you to setup a communication channel between the computer and the Arduino. As you may know by now, setup() only runs once, and then we move on to the next block of code.

But wait! Don’t we have to set the mode of the pin we will be using? Great point!

What the Arduino does, by default, is set all the pins on the board as INPUTs unless you tell it otherwise. So in many cases, you do not have to explicitly set a pin as an input using the pinMode() function. That being said – I make it a habit to do this anyway – because it makes things clear to me – and that is worth it in space and effort.

So I dare you, set the mode of the pin using the pinMode(A0, INPUT) function inside the curly braces of setup()– you won’t regret it.

Moving on to the loop() function, we start with a variable declaration and initialization.

int sensorValue = analogRead(A0);

We declare a variable called sensorValue and we initialize it to the output of a new function. This new function is the glamorous analogRead(). So take a wild guess what this new function analogRead() does. It reads the value at the analog pin that you have chosen – in this case, it is the analog pin A0, where we have the center pin of the potentiometer connected. The voltage at pin A0 will be mapped to a number between 0 and 1023, and this value will be assigned to the variable sensorValue.

If you recall from above, the actual voltage at pin A0 will be between 0 and 5 volts, depending on where your potentiometer is adjusted – this value gets mapped to the range 0 – 1023 with the help of the analog-to-digital converter. So we have a variable that has recorded the value at our potentiometer – what next? Well, let’s look at the value. To do that, we need to print it from the Arduino to our computer – and you guessed it, we will use the Serial library function println() to do just that…

Serial.println(sensorValue);

No big surprises here – we send as an argument the sensorValue variable to the function Serial.println() and our serial monitor window will display the resulting values.

To finish the sketch, we invoke the delay() function for one millisecond to make sure our next reading is a stable one and we start at the top of the loop() again. We record a new value using analogRead(), save it to the variable sensorValue and then print it to the computer.

All this is good and well, you might be thinking, but what does a potentiometer have to do with sensors? A potentiometer doesn’t sense anything! You are right – but interestingly, many sensors work by applying the same principle that a potentiometer does – adjusting resistance. Take a photo-resister for example – it can be used to sense light – because the resistance changes based on the brightness of light that it is exposed to – this change in resistance will adjust the amount of voltage that a pin on the receiving end will receive. So now the ball is in your court – what can you use analogRead() for?

Try On Your Own

  • Change the analog pin to A2. Make adjustments in the code and the circuit.
  • Try a different potentiometer in the circuit, does it affect the range of values displayed?

Further Reading

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code

8 Comments

  1. noone on April 9, 2014 at 1:38 am

    ty =)

  2. […] a potentiometer, set up the example circuit from the module “analogRead() and Serial Port Communications.” Copy the code from that previous section and paste it inside the “blink without […]

  3. Gokul on August 23, 2019 at 11:29 pm

    while(1)
    What did this means?

    • Michael James on August 24, 2019 at 4:54 pm

      The while loops checks the value inside the parentheses every time iteration – if the value is evaluates to true, then the while loop runs the code inside it’s curly braces.

      A while(1) means that the while loop will run over and over again, never exiting (because every non-zero integer number evaluates to true).

      Hope that makes some sense.

  4. Andreas on September 19, 2019 at 4:51 pm

    Nice tutorial, thanks.

    However, there’s one thing I’m sort of desperate to find out, and I can’t find a straight answer anywhere:
    If I want to get the value of the potmeter (or another analog pin) from a script/web app (i.e. JavaScript or PHP), what’s the best approach if I already have a web server running on my ESP8266 (NodeMCU)? Is it possible to write the value to a URL/Path, similar to “server.on(“/”, handleRoot)”? Or is there any other conventient methods of getting the values?

    • Andreas on September 19, 2019 at 5:27 pm

      Kind of figured it out. Here’s how I did it:

      void setup() { server.on(“/analog”, getAnalogValues); }
      void getAnalogValues() {
      String a0 = String(analogRead(A0));
      server.send(200, “text/html”, a0);
      }
      Just to keep the amount of code down to a minimum 🙂

      • Michael James on September 19, 2019 at 8:24 pm

        Thanks for posting the solution Andreas!

Leave a Comment